Python “从 __future__ 导入必须发生在文件的开头”:什么定义了文件的开头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38688504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"from __future__ imports must occur at the beginning of the file": what defines the beginning of the file?
提问by Franck Dernoncourt
The Python script
Python脚本
'''
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#futuresays that:
https://docs.python.org/2/reference/simple_stmts.html#future说:
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.
future 语句必须出现在模块顶部附近。可以出现在 future 语句之前的唯一行是:
- 模块文档字符串(如果有),
- 评论,
- 空行,和
- 其他未来声明。
The second example only contains comments and blank lines before the from __future__ import print_function
, and yet it doesn't work.
第二个示例只包含 之前的注释和空行from __future__ import print_function
,但它不起作用。
I use Python 2.7.
我使用 Python 2.7。
回答by Ignacio Vazquez-Abrams
... 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 mustbe before allcode-relevant lines, even those that have no effect.
第一个字符串作为文档字符串从代码中删除,但第二个字符串成为由字符串本身组成的代码中的语句。__future__
导入必须在所有与代码相关的行之前,即使是那些没有效果的行。