首页 > 解决方案 > 如何在 Python 中跳过函数定义的 Pylint 消息?

问题描述

我的代码中有一个函数定义,它以:

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

我在 Visual Studio Code 中安装了 pylint,现在单词下方有波浪符号List

在此处输入图像描述

运行我的代码时,出现异常:`

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

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

标签: pythonvisual-studio-codepython-3.7pylinttype-hinting

解决方案


您需要导入typing.List对象

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):)。


推荐阅读