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)?
Best Answer
I would say that no, this is baloney. Even with those imports, there are still significant differences between Python 2 and 3: for example,
input()
in Python 3 is likeraw_input()
in Python 2;range()
in Python 3 is likexrange()
in Python 2. In the case ofxrange()
you could probably get away with usingrange()
in Python 2 as long as the ranges are small, but if they're large, your program could have very different memory usage under Python 2 and Python 3.You could add something like this to your code:
But then you've got to find all those edge cases and fix them up. For example, there are the
keys()
andvalues()
methods ofdict
that return iterators in Python 3 but lists in Python 2, so you'd need to write adict
subclass that "fixes" that (and then never use dictionary literals in your code without wrapping them, since those would otherwise be of the built-indict
type).I suppose that, by using
__future__
and various fix-ups, and by limiting yourself to writing code in a subset of Python thus created that will run under both 2.x and 3.x, it might be possible to write code that runs in both versions. Seems like a lot of work, though. There's a reason there's a2to3
utility...