Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

We have builtin dir() function to get all attributes available for class or instance, defined in based classes.

Is there same for annotations? I'd like to have get_annotations() function, which works like this:

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}

like image 401
Anton Ovsyannikov Avatar asked Dec 10 '25 06:12

Anton Ovsyannikov


1 Answers

This should do the trick, right?

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}

Or a one-liner version of it:

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}
like image 200
Sep Avatar answered Dec 11 '25 19:12

Sep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!