我发现了一些奇怪的事情,我不小心将 from __future__ import printfunction
中的 printfunction
拼写成了 printfuncion
。正如我所期望的那样,这并没有在 import 语句的位置给我带来错误,而是 import 语句似乎被忽略了,并且当我尝试使用函数 print
时,随后引发了错误> 与 print
的语句形式不兼容。这使得错误的真正原因变得不那么明显
谁能解释一下为什么在 import
行没有发现错误?
文件“bad_printfunc_import.py”:
#!/usr/bin/env python
from __future__ import printfuncion
print('I will use the named param "sep" in this fuction call.',
'That will cause an error, as with print as a statement',
'rather than a function, these arguments will presumably be',
'interpretted as a tuple rather than function arguments,',
'and tuples can\'t have named elements.',
sep='\n')
产生错误:
$ ./bad_printfunc_import.py
File "./bad_printfunc_import.py", line 10
sep='\n')
^
SyntaxError: invalid syntax
有趣的是,如果我从文件中删除 print
调用,那么我会在 import
行收到错误:
$ ./bad_printfunc_import.py
File "./bad_printfunc_import.py", line 3
from __future__ import printfuncion
SyntaxError: future feature printfuncion is not defined
对我来说,它通常会在导入失败之前报告语法错误,这确实有意义,但是当强制执行的语法依赖于 __future__
导入时,这就没有多大意义了!
最佳答案
from future ...
导入的特殊之处在于它们设置可以影响两个组件的标志:解析器和编译器。如果缺少标志,解析和编译都可能失败,但解析器不会报告编译器可能认可的拼写错误的名称。
禁用print
statements 是一个影响解析器的标志(与 with_statement
和 unicode_literals
标志一起),因此解析器只查找这些标志。因此,因为没有 print_function
找到关键字,禁用 print
的解析器标志语句未设置,解析失败,这会导致语法错误。
只有到达编译阶段,Python 才会抛出错误名称的语法错误:
>>> compile('''from __future__ import nonsuch; parser error here''', '', 'exec')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "", line 1
from __future__ import nonsuch; parser error here
^
SyntaxError: invalid syntax
>>> compile('''from __future__ import nonsuch''', '', 'exec')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "", line 1
SyntaxError: future feature nonsuch is not defined
理论上,解析器可以报告无效的 from __future__
在编译器获取它们之前尽早命名,但这会使解析器进一步复杂化。就目前情况而言,parser already manually looks for those 3 special flags ,而编译器只能依赖解析后的 AST。每次都必须检查所有 7 个可能的名称,这会增加编译器已捕获的错误的复杂性。
关于python - 拼写错误的 __future__ 导入会导致脚本稍后出错,而不是导入位置出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44174669/