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

Fix class access of deprecated computed fields #10391

Merged
merged 1 commit into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions pydantic/_internal/_model_construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -690,7 +690,7 @@ def set_deprecated_descriptors(cls: type[BaseModel]) -> None:


class _DeprecatedFieldDescriptor:
"""Data descriptor used to emit a runtime deprecation warning before accessing a deprecated field.
"""Read-only data descriptor used to emit a runtime deprecation warning before accessing a deprecated field.

Attributes:
msg: The deprecation message to be emitted.
Expand All @@ -709,6 +709,8 @@ def __set_name__(self, cls: type[BaseModel], name: str) -> None:

def __get__(self, obj: BaseModel | None, obj_type: type[BaseModel] | None = None) -> Any:
if obj is None:
if self.wrapped_property is not None:
return self.wrapped_property.__get__(None, obj_type)
raise AttributeError(self.field_name)

warnings.warn(self.msg, builtins.DeprecationWarning, stacklevel=2)
Expand All @@ -717,7 +719,7 @@ def __get__(self, obj: BaseModel | None, obj_type: type[BaseModel] | None = None
return self.wrapped_property.__get__(obj, obj_type)
return obj.__dict__[self.field_name]

# Defined to take precedence over the instance's dictionary
# Defined to make it a data descriptor and take precedence over the instance's dictionary.
# Note that it will not be called when setting a value on a model instance
# as `BaseModel.__setattr__` is defined and takes priority.
def __set__(self, obj: Any, value: Any) -> NoReturn:
Expand Down
21 changes: 21 additions & 0 deletions tests/test_deprecated_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,3 +229,24 @@ class Model(BaseModel):
instance = Model(a=1, b=1)

pytest.warns(DeprecationWarning, lambda: instance.a, match='deprecated')


def test_computed_field_deprecated_class_access() -> None:
class Model(BaseModel):
@computed_field(deprecated=True)
def prop(self) -> int:
return 1

assert isinstance(Model.prop, property)


def test_computed_field_deprecated_subclass() -> None:
"""https://github.com/pydantic/pydantic/issues/10384"""

class Base(BaseModel):
@computed_field(deprecated=True)
def prop(self) -> int:
return 1

class Sub(Base):
pass
Loading