简体   繁体   English

缺少“输入导入列表”-脚本中的错误,但 function 中没有

[英]missing "from typing import List" - error in script, but not in function

I was recently surprised to see that some of our code had a linter warning on the "List" in something equivalent to:我最近很惊讶地看到我们的一些代码在“列表”上有一个 linter 警告,相当于:

class MyClass:
    def method(self):
        myVar: List[str] = []

The linter warning is because this file is missing from typing import List in the imports. linter 警告是因为在导入中from typing import List时缺少此文件。 So, PyCharm flags this as a linter error.因此,PyCharm 将此标记为 linter 错误。 Certainly the code is incorrect.当然代码不正确。 What's surprising is this code runs, and has run properly for months!令人惊讶的是这段代码可以运行,并且已经正常运行了几个月!

Digging in, I found that this:深入研究,我发现这是:

class MyClass:
    def method(self):
        myVar: List[str] = []

m = MyClass()
m.method()

And this:和这个:

def method(self):
    l: List[str] = []

method(None)

run properly, but this:运行正常,但是这个:

l: List[str] = []

Raises the expected error!引发预期错误!

Traceback (most recent call last):
  File ".../scratches/scratch_3.py", line 5, in <module>
    l: List[str] = []
NameError: name 'List' is not defined

So... what gives?那么......什么给了?

(Versions: I am running (版本:我在跑步

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.
>>>

But the code works on several different versions of PYTHON on WINDOWS and LINUX (UBUNTU) builds.但是该代码适用于 WINDOWS 和 LINUX (UBUNTU) 构建的几个不同版本的 PYTHON。
) )

Python treats annotations for global & local variables differently, as outlined in PEP 526 . Python 以不同方式处理全局和局部变量的注释,如PEP 526中所述。 Annotations for module- & class-level variables are evaluated, but annotations for local variables are not.模块级和类级变量的注释会被评估,但局部变量的注释不会。

This makes some sense, as module- and class-level annotations can be accessed through the __annotations__ dictionary, so it must evaluate the annotation and record it.这是有道理的,因为可以通过__annotations__字典访问模块级和类级注释,因此它必须评估注释并记录它。 On the other hand, local variable annotations can not be programmatically accessed, so there's no point in evaluating them.另一方面,不能以编程方式访问局部变量注释,因此评估它们没有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM