簡體   English   中英

在 python 3.9 之后輸入提示的最佳做法是什么?

[英]What's the best practice of typing hint after python 3.9?

python3.9之后,至少有三種使用打字提示的方式。 以內置集合set為例:

# way 1
def f(s: set[str]) -> str:
    pass

# way 2
def f(s: typing.Set[str]) -> str:
    pass

# way 3
def f(s: collections.abc.Set[str]) -> str:
    pass

# way 3': or arguable collections.abc.MutableSet vs collections.abc.Set
def f(s: collections.abc.MutableSet[str]) -> str:
    pass

此外,對於某些抽象類型,在typingcollections.abc中有兩個版本,以Mapping為例:

def f(m: typing.Mapping[str, int]) -> int:
    pass

def f(m: collections.abc.Mapping[str, int]) -> int:
    pass

根據Python 的禪宗

應該有一種——最好只有一種——明顯的方法來做到這一點。

我很困惑哪個最好?

您應該使用set[str]類型的打字。 查看PEP 585

不推薦從打字中導入那些。 由於 PEP 563 和盡量減少鍵入的運行時影響的意圖,此棄用不會生成 DeprecationWarnings。 相反,當被檢查程序的目標版本被指示為 Python 3.9 或更高版本時,類型檢查器可能會警告這種不推薦使用的用法。

因此,現在不推薦從 python 的typing package 導入那些,理想情況下你不應該再使用它們了; 但是,如果您需要向后兼容舊版本的 python,您可以暫時使用它們。 請注意,在 5 年內您可能需要 go 並更新您的代碼庫,因為您將需要 python 3.9:

工具,包括類型檢查器和短絨,必須適應將標准 collections 識別為 generics。

在源代碼級別,新描述的功能需要 Python 3.9

暫無
暫無

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

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