Search code examples
pythonwith-statementbackport

with statement - backport for Python 2.5


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?


Solution

  • 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.