python - 如何在 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 错误消息?
解决方案
您需要导入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):
)。
推荐阅读
- mysql - 保存和检索日期时间到 mysql 日期时间,它使用 TypeOrm,NestJs | 存储前一天的日期 节点
- java - 我可以将 XML 文件存储在 jar 文件中吗?
- ios - 在 Swift 中使用 EventKit 框架或为预订屏幕使用自定义 UI
- python - 在python的目录中解压.bz2文件
- javascript - 使用 Auth0 在 Vercel 上部署:无法解析“/vercel/path0/pages”中的“@auth0/nextjs-auth0”
- amazon-web-services - 如何根据域名阻止对我的 api-gateway url 的任何请求?
- c++ - C++ 程序仅将固定的随机数/字母打印到 output.txt 文件
- php - Yii2 kartik DateControl 小部件设计麻烦
- azure - 代表 api(不是用户)从另一个 WebAp 获取 401 Unauthorized call WebApi
- python - Seaborn 概率直方图 - KDE 归一化