How can I access to __annotations__ of parent class?
In Python, each class has an attribute called __annotations__
which is a dictionary that maps attribute names to type hints. This dictionary is used by type checkers to validate the types of attributes and arguments. It can also be used to introspect a class and get information about the types of its attributes.
However, the __annotations__
attribute is not inherited by subclasses. This means that if a subclass defines an attribute with the same name as an attribute in the parent class, the type hint for the subclass attribute will not be included in the __annotations__
attribute of the subclass.
To access the __annotations__
attribute of a parent class, you can use the following trick:
class Person: name: str address: str @classmethod def get_annotations(cls): d = {} for c in cls.mro(): try: d.update(**c.__annotations__) except AttributeError: # object, at least, has no __annotations__ attribute. pass return d def __init__(self): print(self.get_annotations()) class Student(Person): year: int
The get_annotations()
method in the Person
class iterates over the method resolution order (MRO) of the class and updates the d
dictionary with the __annotations__
attribute of each class in the MRO. The MRO is a list of classes that are searched for attributes and methods when an instance of a class is created.
The __init__()
method in the Student
class calls the get_annotations()
method to print the __annotations__
attribute of the Student
class. The output of this method is:
{'name':, 'address': , 'year': }
This shows that the __annotations__
attribute of the Student
class includes the type hints for all of the attributes defined in the Student
class and its parent classes.
Here are some other ways to access the __annotations__
attribute of a parent class:
- You can use the
getattr()
function to get the__annotations__
attribute of a class. - You can use the
type()
function to get the type of a class and then use the__annotations__
attribute of the type. - You can use the
inspect.getmro()
function to get the MRO of a class and then iterate over the MRO to get the__annotations__
attribute of each class.
In addition to the above methods, you can also use a third-party library such as attrs
to access the __annotations__
attribute of a parent class.