Search code examples
pythonpydanticclass-method

pydantic basemodel breaks classmethod access to attributes


I am trying to export some properties of a class in python. Introducing pydantic breaks the access to attributes in a classmethod.

Take this working example:

class Person:
    age: int = 25
    
    @classmethod
    def printAge(cls):
        print('The age is:', cls.age)

If I extend it towards pydantic, it somehow breaks

class Person(BaseModel):
    age: int = 25
    
    @classmethod
    def printAge(cls):
        print('The age is:', cls.age)

Raises the following error:

 type object 'Person' has no attribute 'age'

Anyone knows what is going on here ? And even more importantly, how to overcome the issue ?


Solution

  • The BaseModel class uses the ModelMetaclass metaclass to construct new model types. Part of this is transforming the class fields into ModelField instances. If you really need to introspect this data, you can use the __fields__ attribute on the class to gain access to its configuration. In this case you can do:

    class Person(BaseModel):
        age: int = 25
    
        @classmethod
        def printAge(cls):
            print('The age is:', cls.__fields__["age"].default)