Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does from __future__ import * raise an error?

I used the following import:

from __future__ import *

but got this error:

SyntaxError: future feature * is not defined (<pyshell#0>, line 1)

What does this error mean?

like image 827
lxjhk Avatar asked Dec 17 '14 04:12

lxjhk


2 Answers

While importing * from the future module is probably dangerous and should be avoided for the reasons John Zwinck mentions, it was interesting to find out why this doesn't work. It does work differently to the usual Python import syntax which lets you grab everything from the module using *.

You can see what's happening by opening up Lib/compiler/future.py in your Python install directory: all import statements that import from __future__ are run through a special parser that only allows you to try and import one of the predefined features. From the source code of FutureParser:

features = ("nested_scopes", "generators", "division",
            "absolute_import", "with_statement", "print_function",
            "unicode_literals")

So basically, you were right to notice that importing from __future__ is a special case that works a bit differently from the usual Python import process, but there are good reasons for this.

like image 164
Marius Avatar answered Nov 20 '22 06:11

Marius


Importing "everything" from the future is neither desirable nor sensible. In fact, most of the time you should not import * at all, but in the case of __future__ it's particularly insidious: what features do you intend to get? It would be very difficult to write a correct program which will work with future versions of Python whose features are not yet known.

like image 7
John Zwinck Avatar answered Nov 20 '22 05:11

John Zwinck