Singledispatch并输入作为输入参数

问题描述 投票:6回答:1

我希望能够这样做:

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

python python-3.7 python-typing
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.