Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introducing classproperty decorator for model_computed_fields #8437

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 11 additions & 3 deletions pydantic/main.py
Expand Up @@ -58,6 +58,14 @@
_object_setattr = _model_construction.object_setattr


class classproperty:
def __init__(self, function) -> None:
self.fget = function

def __get__(self, instance, owner) -> Any:
return self.fget(owner)
Jocelyn-Gas marked this conversation as resolved.
Show resolved Hide resolved


class BaseModel(metaclass=_model_construction.ModelMetaclass):
"""Usage docs: https://docs.pydantic.dev/2.6/concepts/models/

Expand Down Expand Up @@ -167,14 +175,14 @@ def __init__(self, /, **data: Any) -> None: # type: ignore
# The following line sets a flag that we use to determine when `__init__` gets overridden by the user
__init__.__pydantic_base_init__ = True

@property
def model_computed_fields(self) -> dict[str, ComputedFieldInfo]:
@classproperty
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
"""Get the computed fields of this model instance.

Returns:
A dictionary of computed field names and their corresponding `ComputedFieldInfo` objects.
"""
return {k: v.info for k, v in self.__pydantic_decorators__.computed_fields.items()}
return {k: v.info for k, v in cls.__pydantic_decorators__.computed_fields.items()}

@property
def model_extra(self) -> dict[str, Any] | None:
Expand Down
7 changes: 7 additions & 0 deletions tests/test_computed_fields.py
Expand Up @@ -62,6 +62,13 @@ def double_width(self) -> int:
assert rect.model_dump() == {'width': 10, 'length': 5, 'area': 50, 'area2': 50}
assert rect.model_dump_json() == '{"width":10,"length":5,"area":50,"area2":50}'

assert set(Rectangle.model_fields) == {'width', 'length'}
assert set(Rectangle.model_computed_fields) == {'area', 'area2'}

assert Rectangle.model_computed_fields['area'].description == 'An awesome area'
assert Rectangle.model_computed_fields['area2'].title == 'Pikarea'
assert Rectangle.model_computed_fields['area2'].description == 'Another area'
Comment on lines +69 to +70
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would also check what happens when trying to set the model_computed_fields attribute to some value (for reference, having the chain of @classmethod + @property was deprecated in 3.11 partly because of unsupported behavior when setting values on those properties).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it supposed to be settable ?



def test_computed_fields_json_schema():
class Rectangle(BaseModel):
Expand Down