如何跳过 Python 中函数定义的 Pylint 消息?

How to skip the Pylint message for function definition in Python?

我的代码中有一个函数定义,其开头为:

def pivotIndex(self, nums: List[int]) -> int:

我在 Visual Studio 代码中安装了 pylint,现在单词 List:

下方有波浪符号

当运行我的代码时,我得到一个异常:`

    def pivotIndex(self, nums: List[int]) -> int:
NameError: name 'List' is not defined

如何跳过或纠正pylint错误信息?

您需要导入 typing.List object:

from typing import List

类型提示使用 实际 Python 个对象。如果你不这样做,类型提示也会抱怨:

$ mypy filename.py
filename.py:1: error: Name 'List' is not defined
filename.py:1: note: Did you forget to import it from "typing"? (Suggestion: "from typing import List")

即使您使用 from __future__ import annotations 推迟注释的评估(请参阅 PEP 563),或者使用带有类型提示的字符串值,这也适用。您仍然必须导入名称,因为类型提示检查器需要知道它们具体指的是什么对象。那是因为 List 可以是任何东西,它 不是内置名称

例如你可以在某处

赋予List你自己的意义
List = Union[List, CustomListSubclass]

然后导入该对象并使用 List 的定义将是一个有效的(如果混淆)类型提示。

请注意,将注释转换为字符串 (nums: 'List[int]) 可能会使 pylint 错误消失,使用类型提示时仍会出现错误。如果没有导入,检查提示的工具无法解析 List 对象。在将 from typing import List 添加到模块之前,您也可以 删除类型提示 在这种情况下(例如 def pivotIndex(self, nums):)。