Issue
I'm not interested in warming up the "Python 2 or Python 3?" questions (even though the most recent one I found is over one year old), but I stumbled upon this claim:
You can write the Python 3 code under Python 2 if your file begins with the line:
from __future__ import absolute_import, division, generators, unicode_literals, print_function, nested_scopes, with_statement
With that line in place, your code will work with either Python 2 or Python 3. There may be rare cases in which it doesn't work, but I have not found any,
Is this true? Is this single line enough to make sure the code you write will run on both Python 2.x (>=2.5 I assume) and 3.x (assuming the modules imported are available in both)?
Solution
"It depends"
No: Adding these imports to your Python 2 code will not make it run under Python 3.
Yes: With these imports in place you can write code that runs under both Python 2 and Python 3.
But: Then again, you can do that without those imports as well, and several of them, such as unicode_literals
have turned out to simply not be helpful. generators
and with_statement
have nothing to do with Python 2 to Python 3 at all, those are features added in versions of Python 2.
So in conclusion, these imports are a bit of a red herring, and the statement is more wrong than right.
However, that doesn't mean writing code that runs under both Python 2 and Python 3 is impossible, or even necessarily very hard. See http://python3porting.com/ for more info.
Answered By - Lennart Regebro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.