gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:12:11 33 4
gpt4 key购买 nike

Python脚本

'''
a
'''

from __future__ import print_function

运行良好(即什么都不做),但是

'''
a
'''

'''
b
'''
from __future__ import print_function

原因:

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

为什么?


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.

第二个例子在from __future__ import print_function之前只包含注释和空行,但它不起作用。

我使用 Python 2.7。

最佳答案

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

不,因为那些不是注释,它们是字符串。

第一个字符串作为文档字符串从代码中删除,但第二个字符串成为代码中由字符串本身组成的语句。 __future__ 导入必须所有代码相关行之前,即使那些没有效果。

关于python - "from __future__ imports must occur at the beginning of the file": what defines the beginning of the file?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38688504/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com