Search code examples
pythonmodelpydantic

In a pydantic model, how do I define the type of property which is a decorated method?


Consider this code snippet:

from pydantic import BaseModel

class SomeModel(BaseModel):
    property_1: str
    property_2: Dict[str, str]
    property_3: int = 12

    @property
    def property_4(self) -> int:
        response = external_call()  # returns '22.0' (a string)

>>> a = SomeModel(property_1="a", property_2={"k": "v"}, property_3="12.0")
>>> a.property_3
12
>>> a.property_4
'22.0'

property_3 gets properly casted to int. How do I achieve the same with the @property decorator? Is it possible to get pydantic do its magic on those decorated properties?


Solution

  • My Answer

    You can use pydantic.validate_call to cast the property: https://docs.pydantic.dev/latest/concepts/validation_decorator/

    My Example

    from pydantic import VERSION, BaseModel, validate_call
    
    
    print(VERSION)
    # > 2.0.3
    
    
    class SomeModel(BaseModel):
        property_1: str
        property_2: dict[str, str]
        property_3: int = 12
    
        @property
        @validate_call(validate_return=True)  # and cast by type annotation
        def property_4(self) -> int:
            return '22.0'
    
    
    a = SomeModel(property_1="a", property_2={"k": "v"}, property_3="12.0")
    print(a.property_4, type(a.property_4))
    # 22 <class 'int'>