4
的Python腳本「from __future__進口必須出現在文件的開頭」:什麼定義了文件的開頭?
'''
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說:
未來的語句必須在其旁邊模塊的頂部。能夠在未來的語句之前出現的唯一 線:
- 模塊文檔字符串(如果有的話),
- 評論,
- 空行,並
- 其他未來的語句。
第二個例子只包含註釋和空行的from __future__ import print_function
之前,但它不工作。
我使用Python 2.7。
有一點研究很長。從官方文檔開始:https://docs.python.org/2/reference/simple_stmts.html#future –
@BryanOakley謝謝,你鏈接到的文檔表明可以在'from __future__ import print_function'之前放置註釋,它似乎與我給出的第二個例子相矛盾。 –
在第二個示例中,您具有模塊docstring,那麼您有_another_三引號字符串。第二個字符串既不是註釋也不是文檔字符串。 –