Python 拼写错误的_ufuture __;导入将导致脚本中稍后出现错误,而不是在导入位置
我发现了一些奇怪的事情,在from _uFuture _; import printfunction中,我意外地将printfunction拼写为printfunction。这并没有像我预期的那样在import语句的位置出现错误,而是import语句似乎被忽略了,当我试图以与print语句形式不兼容的方式使用函数print时,随后出现了一个错误。这使得错误的真正原因比其他情况下要明显得多 有人能解释为什么在导入行没有发现错误吗 文件'bad_printfunc_import.py':Python 拼写错误的_ufuture __;导入将导致脚本中稍后出现错误,而不是在导入位置,python,python-2.7,syntax,python-internals,Python,Python 2.7,Syntax,Python Internals,我发现了一些奇怪的事情,在from _uFuture _; import printfunction中,我意外地将printfunction拼写为printfunction。这并没有像我预期的那样在import语句的位置出现错误,而是import语句似乎被忽略了,当我试图以与print语句形式不兼容的方式使用函数print时,随后出现了一个错误。这使得错误的真正原因比其他情况下要明显得多 有人能解释为什么在导入行没有发现错误吗 文件'bad_printfunc_import.py': #!/us
#!/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调用,那么在导入行中确实会出现错误:
在导入失败之前,它通常会报告语法错误,这对我来说是有意义的,但当所执行的语法依赖于该导入时,这就没有什么意义了 来自未来。。。导入的特殊之处在于它们设置了可能影响两个组件的标志:解析器和编译器。如果缺少标志,解析和编译都可能失败,但解析器不会报告编译器可能会遵守的拼写错误的名称
禁用print语句是一个影响解析器的标志,它与with_语句和unicode_文本标志一起影响解析器,因此解析器只查找这些标志。因此,由于没有找到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__名称,但这会使解析器进一步复杂化。就目前情况而言,编译器只能依赖解析的AST。每次必须检查所有7个可能的名称会增加编译器已经捕获的错误的复杂性。但它必须已经解释了_ufuture _;导入,因为要执行的语法取决于此!或者,它只是忽略了它不知道的影响语法规则的导入,即使这些导入来自未来?实际上,我是不精确的;在写答案的过程中,先确认一些事情。
>>> 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