如何为各自接受父类不同子类型的回调函数正确标注类型
如何为各自接受父类不同子类型的回调函数正确标注类型
Right now I have this code:
class A(abc.ABC): pass class B(A): pass class C(A): pass def fn_b(b: B) -> None: pass def fn_c(c: C) -> None: pass d : dict[type[A], Union[Callable[[A], None], Callable[[B], None]]] = { B: fn_b, C: fn_c, }
Now this is simplified, in practice I can have dozens of subclasses of A. New classes may be added over time, and key/value pairs could be added/changed in d.
Is there a better way to type d than a massive Union? An option would be dict[type[A], Callable[..., None]] but obviously this doesn't convey that the Callables should only accept A subclasses.
The fn_* functions are meant to be decoupled from the B, C and so on classes. So moving them to methods won't solve the issue.
Edit: InSync's answer below does work however it looks like quite a bit of overhead to type this. Is there something simpler and more concise?
备注:内容来源于stack exchange,提问作者foo
相关产品推荐
相关产品推荐

