在Python中,我很难定义类型.我想要这样的东西:
def foo(x: int) -> int:
return x
def bar(x: str) -> str:
return x
# [...] MyDictType would be defined here...
my_dict: MyDictType = {
int: foo, # Good
str: bar, # Good
float: bar # WRONG! Type warning!
}
MyDictType应指示它是将类型与接收该类型的变量的可调用对象映射的字典.我在想怎么用泛型来做这件事.但我不确定.我试过这个:
T = TypeVar("T")
MyDictType = dict[Type[T], Callable[[T], T]]
然而,编辑没有在词典的第三个条目中显示我预期的错误...
如何定义MyDictType?