Junior — Middle
What is the use of a Decorator for computed fields in a pydantic model?
sobes.tech AI
Answer from AI
In Pydantic, to create computed fields, the @property decorator or a special @pydantic.validator decorator (for validation) is used, but most often, @property allows defining a field whose value is computed dynamically based on other model fields.
This is useful when you need to obtain a value that is not stored directly but is computed upon access. For example:
from pydantic import BaseModel
class User(BaseModel):
first_name: str
last_name: str
@property
def full_name(self) -> str:
return f"{self.first_name} {self.last_name}"
Here, full_name is a computed field that is not passed during initialization but is accessible as a model attribute. This approach helps keep the calculation logic inside the model while maintaining convenient data access.