[Tutor] How to get both 2.6 scripts as well as 3.1 scripts to run at command line?

Steven D'Aprano steve at pearwood.info
Fri Sep 17 02:15:20 CEST 2010


On Thu, 16 Sep 2010 01:35:17 pm David Hutto wrote:
> print("a is", a)
> or
> from future import *

Neither of those lines are correct. Given (say) a=42, in Python 2.6 the 
first line will print the tuple:

("a is", 42)

while in Python 3.1 it will print the string:

a is 42

Note the extra punctuation in the first version. For a quick-and-dirty 
script, you might not care about that, so passing tuples to print in 
2.x is a reasonably simple work-around, but they are not the same.

On the other hand, the second line does behave the same in both Python 
2.6 and 3.1:

>>> from future import *
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named future

It might be the same, but I'm pretty sure it's not useful.

What you are thinking of is the special module __future__ with leading 
and trailing double-underscores. __future__ is special -- the line 

from __future__ import ...

(where ... is one or more feature) tells the Python compiler to change 
behaviour. If you use a "from __future__ import" line, it MUST be the 
first executable line in a module or script. It's okay for it to follow 
blank lines, comments or a doc-string, but it must be before any other 
line of Python code.

In the case of Python 2.6 you can execute:

from __future__ import print_function

to turn print into a function like in 3.1.

However, you can't use the asterisk form:

>>> from __future__ import *
  File "<stdin>", line 1
SyntaxError: future feature * is not defined



-- 
Steven D'Aprano


More information about the Tutor mailing list