Singledispatch和类型作为输入参数

时间:2019-03-28 08:36:58

标签: python python-3.7 python-typing

我希望能够做到这一点:

from typing import Type
from functools import singledispatch

class A:
    pass

class B(A):
    pass

@singledispatch
def foo(arg):
    print('default')

@foo.register
def _(arg: Type[A]):
    print(arg)

foo(A)
foo(B)

但是,我得到Invalid annotation for 'arg'. typing.Type[__main__.arg] is not a class.

我想singledispatch暂时还不完全支持typing。有什么优雅的解决方法吗?

UPD 我无法修改AB

1 个答案:

答案 0 :(得分:2)

您可以给A一个元类,然后A的所有子类都是该元类的实例:

from functools import singledispatch

class AMeta(type): pass

class A(metaclass=AMeta): pass

class B(A): pass

@singledispatch
def foo(arg):
    print('default')

@foo.register
def _(arg: AMeta):
    print('A or B')

foo(A) # A or B
foo(B) # A or B
foo(A()) # default

class C: pass

foo(C) # default