1 回答

TA貢獻2021條經驗 獲得超8個贊
讓我提醒您,當使用 時未考慮以下約束時,就會出現問題中描述的問題Union
:
僅當操作對每個聯合項都有效時,它們才對聯合類型有效。這就是為什么通常需要使用
isinstance()
檢查來首先將聯合類型縮小為非聯合類型。這也意味著建議避免使用union
類型作為函數返回類型,因為調用者可能必須isinstance()
在對值進行任何有趣的操作之前使用。[1]
作為解決方法,我建議使用帶有可選參數的單個函數。我用來Protocol
定義帶有可選參數的回調類型,該參數無法使用Callable[...]
from typing import Protocol, Optional, Dict
class Fn(Protocol):
def __call__(self, name: Optional[str] = None) -> None:
...
def fn(name: Optional[str] = None) -> None:
if name is None:
print("Hello World")
else:
print("goodbye world", name)
d: Dict[str, Dict[str, Fn]] = {
"hello": {
"world": fn
},
"goodbye": {
"world": fn
}
}
d["hello"]["world"]()
d["goodbye"]["world"]("john")
[1] https://mypy.readthedocs.io/en/stable/kinds_of_types.html#union-types
添加回答
舉報