[Python] How to solve mypy error for @property with pydantic @computed_field?

Discussão em 'Python' iniciado por Stack, Fevereiro 1, 2025.

  1. Stack

    Stack Membro Participativo

    I need to decorate @property with the @computed_field from pydantic (to automatically generate key-value pairs and include them in a FastAPI JSON Response). In the following example, mypy displays an error. If there is an error, how can I fix it? If everything is correct, how do I disable this mypy message?

    from pydantic import BaseModel, computed_field

    class MyClass(BaseModel):

    value1: str
    value2: str

    @computed_field
    @property
    def joined_values(self) -> str:
    return self.value1 + self.value2


    obj = MyClass(value1="1", value2="2")
    print(f"{obj.joined_values=}") # obj.joined_values='12'


    mypy error:

    $ mypy .
    stackperflow_pydantic_property.py:25: error: Decorators on top of @property are not supported [misc]
    Found 1 error in 1 file (checked 2 source files)


    versions:

    $ python -V
    Python 3.10.11

    $ pip list
    mypy 1.7.1
    pydantic 2.5.2

    Continue reading...

Compartilhe esta Página