我发现了一些奇怪的东西,我不小心把printfunction
拼错了printfuncion
在from __future__ import printfunction
中。这并没有像我预期的那样在import语句的位置给我一个错误,而是import语句似乎被忽略了,并且在我试图以与print
的语句形式不兼容的方式使用函数print
时引发了一个错误。这使得错误的真正原因变得不那么明显
有人能解释一下为什么在import
行没有发现错误吗?在
文件'bad\u printfunc_导入.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')
产生的错误:
^{pr2}$有趣的是,如果我从文件中删除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
语句是一个影响解析器的标志(与with_statement
和unicode_literals
标志一起使用),因此解析器只查找那些标志。同样,由于没有找到print_function
关键字,因此没有设置禁用print
语句的解析器标志,解析失败,这将导致语法错误。在只有到了编译阶段,Python才会对不正确的名称抛出语法错误:
理论上,解析器可以在编译器到达无效的
from __future__
名称之前尽早报告它们,但这会使解析器更加复杂。现在,parser already manually looks for those 3 special flags,而编译器只能依赖解析的AST。每次都要检查所有7个可能的名称,这会增加编译器已经捕捉到的错误的复杂性。在相关问题 更多 >
编程相关推荐