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...
The import statement always initializes the whole module. The modules are stored in the sys.modules
dictionary.
When you use from sys import argv
the sys
module is not bound locally, only argv
is. You cannot use the name sys
in your module, because you didn't import that name.
You can only reach the sys
module if you imported sys
separately:
from sys import argv
script, input = argv
import sys
print sys.path
And you can always access all imported modules by accessing sys.modules
:
from sys import modules
print modules['sys'].path
Here I bound the name modules
to the sys.modules
dictionary, and through that reference, find the sys
module, and reference the path
attribute.
Demo:
>>> from sys import modules
>>> modules['sys']
<module 'sys' (built-in)>
>>> sys
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sys' is not defined
Best Answer
__future__
features are self-documenting. Try this:These respectively indicate the first release supporting
from __future__ import with_statement
and the first release to support it without usingfrom __future__
.Also, read this: