从实例中获取自定义泛型 Class 的 TypeVars

Get TypeVars of custom Generic Class from instance

我有这样的东西:

from typing import TypeVar, Generic, Tuple

T = TypeVar('T')
S = TypeVar('S')
U = TypeVar('U')

class Foo(Generic[T, S]):
    def get_type_vars(self) -> Tuple[TypeVar]:
        return  #TODO how do I return T and S here?

assert Foo().get_type_vars() == (T, S)

有什么办法可以实现这种行为吗?我需要一种方法来找出 ST 是泛型 Class Foo 的 TypeVars。有什么想法吗?

我应该提一下,我写了一些 class 装饰器,方法 get_type_vars() 将由装饰器添加到 class 中。所以我只有方法中的实例 self:

def get_type_vars(self) -> Tuple[TypeVar]:
        return  #TODO how do I return T and S here in case that self is an instance of Foo?

您可以结合使用 get_args__orig_bases__ 来检查基类的泛型类型 class:

class Foo(Generic[T, S]):
    def get_type_vars(self) -> Tuple[TypeVar]:
        return get_args(type(self).__orig_bases__[0])

虽然对于更复杂的继承链,这会变得有点复杂。