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

↘锁芯ラ 提交于 2019-12-03 17:43:33

问题


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.


回答1:


... 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.



来源:https://stackoverflow.com/questions/38688504/from-future-imports-must-occur-at-the-beginning-of-the-file-what-defines

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!