是否有内置方法从 Python 中的所有基数 类 获取所有 __annotations__?

Is there built in method to get all __annotations__ from all base classes in Python?

我们有内置的 dir() 函数来获取 class 或实例的所有可用属性,定义在 based classes.

注解也一样吗?我想要 get_annotations() 函数,其工作方式如下:

def get_annotations(cls: type): ...  # ?


class Base1:
    foo: float


class Base2:
    bar: int


class A(Base1, Base2):
    baz: str


assert get_annotations(A) == {'foo': float, 'bar': int, 'baz': str}

这应该可以解决问题,对吧?

def get_annotations(cls: type):
    all_ann = [c.__annotations__ for c in cls.mro()[:-1]]
    all_ann_dict = dict()
    for aa in all_ann[::-1]:
        all_ann_dict.update(**aa) 
return all_ann_dict

get_annotations(A)
# {'bar': int, 'foo': float, 'baz': str}

或者它的 one-liner 版本:

get_annotations = lambda cls: {k:v for c in A.mro()[:-1][::-1] for k,v in c.__annotations__.items()}

get_annotations(A)
# {'bar': int, 'foo': float, 'baz': str}