Skip to content

Commit 8b6d5fc

Browse files
authored
Fix class access of deprecated computed fields (#10391)
1 parent a031acd commit 8b6d5fc

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

pydantic/_internal/_model_construction.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -690,7 +690,7 @@ def set_deprecated_descriptors(cls: type[BaseModel]) -> None:
690690

691691

692692
class _DeprecatedFieldDescriptor:
693-
"""Data descriptor used to emit a runtime deprecation warning before accessing a deprecated field.
693+
"""Read-only data descriptor used to emit a runtime deprecation warning before accessing a deprecated field.
694694
695695
Attributes:
696696
msg: The deprecation message to be emitted.
@@ -709,6 +709,8 @@ def __set_name__(self, cls: type[BaseModel], name: str) -> None:
709709

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

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

720-
# Defined to take precedence over the instance's dictionary
722+
# Defined to make it a data descriptor and take precedence over the instance's dictionary.
721723
# Note that it will not be called when setting a value on a model instance
722724
# as `BaseModel.__setattr__` is defined and takes priority.
723725
def __set__(self, obj: Any, value: Any) -> NoReturn:

tests/test_deprecated_fields.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,3 +229,24 @@ class Model(BaseModel):
229229
instance = Model(a=1, b=1)
230230

231231
pytest.warns(DeprecationWarning, lambda: instance.a, match='deprecated')
232+
233+
234+
def test_computed_field_deprecated_class_access() -> None:
235+
class Model(BaseModel):
236+
@computed_field(deprecated=True)
237+
def prop(self) -> int:
238+
return 1
239+
240+
assert isinstance(Model.prop, property)
241+
242+
243+
def test_computed_field_deprecated_subclass() -> None:
244+
"""https://github.com/pydantic/pydantic/issues/10384"""
245+
246+
class Base(BaseModel):
247+
@computed_field(deprecated=True)
248+
def prop(self) -> int:
249+
return 1
250+
251+
class Sub(Base):
252+
pass

0 commit comments

Comments
 (0)