简体   繁体   English

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

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

I have a function definition in my code, which starts with:我的代码中有一个 function 定义,它以:

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

I installed pylint in Visual Studio Code and now there are tildes symbols beneath the word List :我在 Visual Studio Code 中安装了 pylint,现在List一词下方有波浪符号:

在此处输入图像描述

When running my code, I get an exception:`运行我的代码时,出现异常:`

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

How to skip or rectify the pylint error message?如何跳过或纠正 pylint 错误消息?

You need to import the typing.List object :您需要导入typing.List object

from typing import List

Type hinting uses actual Python objects .类型提示使用实际的 Python 对象 If you don't, type hinters will complain too:如果你不这样做,类型提示也会抱怨:

$ 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")

This applies even if you use from __future__ import annotations to postpone evaluation of annotations (see PEP 563 ), or use a string value with the type hint.即使您使用from __future__ import annotations来推迟对注释的评估(参见PEP 563 ),或者使用带有类型提示的字符串值,这也适用。 You must still import the names as the type hint checker needs to know what exact object they refer to.您仍然必须导入名称,因为类型提示检查器需要知道它们所指的确切 object 是什么。 That's because List can otherwise be just about anything, it is not a built-in name .那是因为List可以是其他任何东西,它不是内置名称

Eg you could have assigned your own meaning to List somewhere例如,您可以将自己的含义分配给List某处

List = Union[List, CustomListSubclass]

and then importing that object and using that definition of List would be a valid (if confusing) type hint.然后导入 object 并使用List的定义将是一个有效的(如果令人困惑的)类型提示。

Note that turning the annotation into a string ( nums: 'List[int] ) may make pylint error go away, you will still get errors when you use type hinting.请注意,将注释转换为字符串( nums: 'List[int] )可能会使 pylint 错误 go 消失,但在使用类型提示时仍然会出现错误。 The tool checking the hints can't resolve the List object without the import.检查提示的工具在没有导入的情况下无法解析List object。 Until you add from typing import List to the module, you may as well just remove the type hints in that case (eg def pivotIndex(self, nums): ).直到您from typing import List添加到模块中,您也可以在这种情况下删除类型提示(例如def pivotIndex(self, nums): )。

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

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