[英]TypeScript vs. Python typing default arguments and autocompletion
在 TypeScript 中,我曾經有以下內容,它將用作類型推斷:
function func(x: "#1" | "#2" | "#3" = "#2"): void {}
上面的示例應該在鍵入時為您提供選項和自動完成,並在您鍵入不在選項列表中的選項時出錯。
當我探索 Python 時,我發現了typing
模塊。 但是我嘗試的方法沒有用,我找不到我希望找到的東西。
我的預期代碼:
def func(x: "#1" | "#2" | "#3" = "#2") -> None:
pass
我的預期結果應該與 TypeScript 中的結果類似。
from typing import Literal, TypeAlias
Valid: TypeAlias = Literal["#1", "#2", "#3"]
def func(x: Valid = "#2") -> None:
print(x)
if __name__ == "__main__":
func("#1")
func("#2")
func("#3")
func("#4")
一切都有效,除了最后一行讓mypy
合理地抱怨:
error: Argument 1 to "func" has incompatible type "Literal['#4']"; expected "Literal['#1', '#2', '#3']" [arg-type]
請注意,在 Python 中,解釋器不關心類型注釋,並將毫無問題地執行最后一個 function 調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.