簡體   English   中英

如何跳過 Python 中 function 定義的 Pylint 消息?

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

我的代碼中有一個 function 定義,它以:

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 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 ),或者使用帶有類型提示的字符串值,這也適用。 您仍然必須導入名稱,因為類型提示檢查器需要知道它們所指的確切 object 是什么。 那是因為List可以是其他任何東西,它不是內置名稱

例如,您可以將自己的含義分配給List某處

List = Union[List, CustomListSubclass]

然后導入 object 並使用List的定義將是一個有效的(如果令人困惑的)類型提示。

請注意,將注釋轉換為字符串( nums: 'List[int] )可能會使 pylint 錯誤 go 消失,但在使用類型提示時仍然會出現錯誤。 檢查提示的工具在沒有導入的情況下無法解析List object。 直到您from typing import List添加到模塊中,您也可以在這種情況下刪除類型提示(例如def pivotIndex(self, nums): )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM