Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"from __future__ imports must occur at the beginning of the file": what defines the beginning of the file?

Tags:

The Python script

''' a '''  from __future__ import print_function 

works well (i.e., does nothing), but

''' a '''  ''' b ''' from __future__ import print_function 

causes:

File "C:\test.py", line 8     from __future__ import print_function SyntaxError: from __future__ imports must occur at the beginning of the file 

Why?


https://docs.python.org/2/reference/simple_stmts.html#future says that:

A future statement must appear near the top of the module. The only lines that can appear before a future statement are:

  • the module docstring (if any),
  • comments,
  • blank lines, and
  • other future statements.

The second example only contains comments and blank lines before the from __future__ import print_function, and yet it doesn't work.

I use Python 2.7.

like image 883
Franck Dernoncourt Avatar asked Jul 31 '16 21:07

Franck Dernoncourt


People also ask

What does __ future __ mean in Python?

__future__ module is a built-in module in Python that is used to inherit new features that will be available in the new Python versions.. This module includes all the latest functions which were not present in the previous version in Python.

What is Absolute_import?

from __future__ import absolute_import means that if you import string , Python will always look for a top-level string module, rather than current_package.string . However, it does not affect the logic Python uses to decide what file is the string module.


1 Answers

... which seems to be in contradiction with the second example I gave.

No, because those are not comments, they are strings.

The first string is elided from the code as a docstring, but the second string becomes a statement in the code consisting of the string itself. __future__ imports must be before all code-relevant lines, even those that have no effect.

like image 131
Ignacio Vazquez-Abrams Avatar answered Sep 18 '22 13:09

Ignacio Vazquez-Abrams