You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为各自接受父类不同子类型的回调函数正确标注类型

如何为各自接受父类不同子类型的回调函数正确标注类型

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 13:44:52