當對 dict 型別的變數進行型別注解時,通常你會像這樣注解它:
numeralToInteger: dict[str, int] = {...}
但是我用冒號而不是逗號重寫了這個:
numeralToInteger: dict[str : int] = {...}
這也有效,不會引發 SyntaxError 或 NameError 。
在檢查__annotations__全域變數時:
colon: dict[str : int] = {...}
comma: dict[str, int] = {...}
print(__annotations__)
輸出是:
{'colon': dict[slice(<class 'str'>, <class 'int'>, None)],
'comma': dict[str, int]}
因此,冒號被視為切片物件,逗號被視為普通型別提示。
我應該在字典型別中使用冒號還是應該堅持使用逗號?
我正在使用 Python 3.10.1 版。
uj5u.com熱心網友回復:
如果你有一個字典,其鍵是字串,值是整數,你應該這樣做dict[str, int]。這不是可選的。IDE 和型別檢查器使用這些型別提示來幫助您。當你說dict[str : int]時,它是一個切片物件。完全不同的東西。
在mypy 操場上試試這些:
d: dict[str, int]
d = {'hi': 20}
c: dict[str: int]
c = {'hi': 20}
資訊:
main.py:4: error: "dict" expects 2 type arguments, but 1 given
main.py:4: error: Invalid type comment or annotation
main.py:4: note: did you mean to use ',' instead of ':' ?
Found 2 errors in 1 file (checked 1 source file)
錯誤資訊說明一切
uj5u.com熱心網友回復:
dict[str:int]您傳遞的提示是其dict鍵是切片,因為 x:y 是 python 中的切片。
傳遞正確的dict[str, int]鍵和值提示,以前也有一個typing.Dict,但已被棄用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/417294.html
標籤:
下一篇:函式列印正確的結果,回傳錯誤的值
