Skip to content

Commit

Permalink
Fix class access of deprecated computed fields (#10391)
Browse files Browse the repository at this point in the history
  • Loading branch information
Viicos authored Sep 12, 2024
1 parent a031acd commit 8b6d5fc
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
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

0 comments on commit 8b6d5fc

Please sign in to comment.