拼写错误的“future”import将导致稍后在脚本中出现错误,而不是在导入位置

2024-04-25 01:47:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我发现了一些奇怪的东西,我不小心把printfunction拼错了printfuncionfrom __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__导入时,这就没有什么意义了!在


Tags: frompyimportas错误future语句will
1条回答
网友
1楼 · 发布于 2024-04-25 01:47:12

from future ...导入的特殊之处在于它们设置的标志可以影响两个组件:解析器和编译器。如果缺少标志,解析和编译都会失败,但是解析器不会报告编译器可能会接受的拼写错误的名称。在

禁用print语句是一个影响解析器的标志(与with_statementunicode_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个可能的名称,这会增加编译器已经捕捉到的错误的复杂性。在

相关问题 更多 >