缺少 "from typing import List" - 脚本错误,但不是函数错误
missing "from typing import List" - error in script, but not in function
我最近惊讶地发现我们的一些代码在“列表”上有一个 linter 警告,类似于:
class MyClass:
def method(self):
myVar: List[str] = []
linter 警告是因为此文件在导入中丢失 from typing import List
。因此,PyCharm 将此标记为 linter 错误。当然代码不正确。令人惊讶的是这段代码 运行s,并且 运行 几个月都正确!
深入挖掘,我发现:
class MyClass:
def method(self):
myVar: List[str] = []
m = MyClass()
m.method()
还有这个:
def method(self):
l: List[str] = []
method(None)
运行 正确,但是这个:
l: List[str] = []
引发预期错误!
Traceback (most recent call last):
File ".../scratches/scratch_3.py", line 5, in <module>
l: List[str] = []
NameError: name 'List' is not defined
那么……是什么原因?
(版本:
我是运行宁
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
但该代码适用于 WINDOWS 和 LINUX (UBUNTU) 构建的 PYTHON 的多个不同版本。
)
Python 以不同方式处理全局变量和局部变量的注释,如 PEP 526 中所述。评估模块级和 class 级变量的注释,但不评估局部变量的注释。
这是有道理的,因为可以通过 __annotations__
字典访问模块级别和 class 级别的注释,因此它必须评估注释并记录它。另一方面,不能以编程方式访问局部变量注释,因此评估它们没有意义。
我最近惊讶地发现我们的一些代码在“列表”上有一个 linter 警告,类似于:
class MyClass:
def method(self):
myVar: List[str] = []
linter 警告是因为此文件在导入中丢失 from typing import List
。因此,PyCharm 将此标记为 linter 错误。当然代码不正确。令人惊讶的是这段代码 运行s,并且 运行 几个月都正确!
深入挖掘,我发现:
class MyClass:
def method(self):
myVar: List[str] = []
m = MyClass()
m.method()
还有这个:
def method(self):
l: List[str] = []
method(None)
运行 正确,但是这个:
l: List[str] = []
引发预期错误!
Traceback (most recent call last):
File ".../scratches/scratch_3.py", line 5, in <module>
l: List[str] = []
NameError: name 'List' is not defined
那么……是什么原因?
(版本: 我是运行宁
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
但该代码适用于 WINDOWS 和 LINUX (UBUNTU) 构建的 PYTHON 的多个不同版本。
)
Python 以不同方式处理全局变量和局部变量的注释,如 PEP 526 中所述。评估模块级和 class 级变量的注释,但不评估局部变量的注释。
这是有道理的,因为可以通过 __annotations__
字典访问模块级别和 class 级别的注释,因此它必须评估注释并记录它。另一方面,不能以编程方式访问局部变量注释,因此评估它们没有意义。