[英]What is the correct way to test a type is bare typing.Dict in Python?
我想編寫一個函數is_bare_dict
為Dict
返回 True ,為任何類型的 dict 返回 false ,例如Dict[int, str]
。
我想出的一種方法是這樣的:
from typing import Dict, KT, VT
def is_bare_dict(typ) -> bool:
ktype = typ.__args__[0]
vtype = typ.__args__[1]
return ktype is KT and vtype is VT
你可以運行上面的代碼: https : //wandbox.org/permlink/sr9mGbWo3Lh7VrPh
也可以在一行中完成
from typing import Dict, KT, VT
def is_bare_dict(typ) -> bool:
return not isinstance(typ.__args__, tuple)
print(is_bare_dict(Dict)) # Print True
print(is_bare_dict(Dict[int, str])) # Print False
def is_typing_dot_dict(typ) -> bool:
return typ is typing.Dict
如果你真的想測試是否有什么東西在typing.Dict
,那么就這樣做。 不過,這可能不是要測試的正確內容 - 似乎您也希望將dict
視為相同,並且可能typing.Dict[Any, Any]
。 (另外, typing.Dict
已被棄用,最終可能會消失。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.