Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a from __future__ import ... guarantee Python 2 and 3 compatibility?

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)?

like image 729
Tobias Kienzler Avatar asked Jun 19 '12 14:06

Tobias Kienzler


1 Answers

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 like raw_input() in Python 2; range() in Python 3 is like xrange() in Python 2. In the case of xrange() you could probably get away with using range() 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:

try:
    range = xrange
    input = raw_input
except NameError:
    pass

But then you've got to find all those edge cases and fix them up. For example, there are the keys() and values() methods of dict that return iterators in Python 3 but lists in Python 2, so you'd need to write a dict subclass that "fixes" that (and then never use dictionary literals in your code without wrapping them, since those would otherwise be of the built-in dict 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 a 2to3 utility...

like image 141
kindall Avatar answered Sep 22 '22 06:09

kindall