views:

285

answers:

3

I'd like to use with statement in Python 2.5 in some production code. It was backported, should I expect any problems (e.g. with availability/compatibility on other machines/etc)?

Is this code

from __future__ import with_statement

compatible with Python 2.6?

+4  A: 

Yes, that statement is a no-operation in Python 2.6, so you can freely use it to make with a keyword in your 2.5 code as well, without affecting your code's operation in 2.6. This is in fact the general design intention of "importing from the future" in Python!

Alex Martelli
+3  A: 

You can call this in Python 2.6 and 3.0/1 without problems (it's a no-op there).

Tim Pietzcker
+3  A: 

with_statement wasn't back ported but implemented in Python 2.5. Adding new keywords or syntax can break existing applications. With Python the way they decided to handle this is allow people to opt-in to those features early so you can slowly transition your code over.

From http://python.org/doc/2.5.2/ref/future.html

A future statement is a directive to the compiler that a particular module should be compiled using syntax or semantics that will be available in a specified future release of Python. The future statement is intended to ease migration to future versions of Python that introduce incompatible changes to the language. It allows use of the new features on a per-module basis before the release in which the feature becomes standard.

You can actually inspect futures to get information on when first supported, when the import isn't needed anymore, etc.

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import __future__
>>> dir(__future__)
['CO_FUTURE_ABSOLUTE_IMPORT', 'CO_FUTURE_DIVISION', 'CO_FUTURE_WITH_STATEMENT', 'CO_GENERATOR_ALLOWED', 'CO_NESTED', '_Feature', '__all__', '__builtins__',
__doc__', '__file__', '__name__', 'absolute_import', 'all_feature_names', 'division', 'generators', 'nested_scopes', 'with_statement']
>>> __future__.with_statement
_Feature((2, 5, 0, 'alpha', 1), (2, 6, 0, 'alpha', 0), 32768)
>>>

I personally have been heavily using the with_statement in Python 2.5 for well over a year and have not had issues. I also transparently run that code with Python 2.6. There are some weird corner cases they have worked at cleaning up in the language, mostly related to cleanly and correctly compacting nested with statements.

Ed
Good point on inspecting some meta-info about future statements.
gorsky