8000 Improve error thrown when overriding field with a property (#11459) · pydantic/pydantic@7ccad67 · GitHub
[go: up one dir, main page]

Skip to content

Commit 7ccad67

Browse files
Improve error thrown when overriding field with a property (#11459)
Co-authored-by: Victorien <65306057+Viicos@users.noreply.github.com>
1 parent 588436e commit 7ccad67

File tree

3 files changed

+12
-5
lines changed

3 files changed

+12
-5
lines changed

pydantic/_internal/_fields.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,10 @@ def collect_model_fields( # noqa: C901
264264
# to make sure the decorators have already been built for this exact class
265265
decorators: DecoratorInfos = cls.__dict__['__pydantic_decorators__']
266266
if ann_name in decorators.computed_fields:
267-
raise ValueError("you can't override a field with a computed field")
267+
raise TypeError(
268+
f'Field {ann_name!r} of class {cls.__name__!r} overrides symbol of same name in a parent class. '
269+
'This override with a computed_field is incompatible.'
270+
)
268271
fields[ann_name] = field_info
269272

270273
if typevars_map:

pydantic/fields.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1421,9 +1421,11 @@ class Child(Parent):
14211421
def a(self) -> str:
14221422
return 'new a'
14231423
1424-
except ValueError as e:
1425-
print(repr(e))
1426-
#> ValueError("you can't override a field with a computed field")
1424+
except TypeError as e:
1425+
print(e)
1426+
'''
1427+
Field 'a' of class 'Child' overrides symbol of same name in a parent class. This override with a computed_field is incompatible.
1428+
'''
14271429
```
14281430
14291431
Private properties decorated with `@computed_field` have `repr=False` by default.

tests/test_computed_fields.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff 74AC line change
@@ -774,7 +774,9 @@ def test_computed_field_override_raises():
774774
class Model(BaseModel):
775775
name: str = 'foo'
776776

777-
with pytest.raises(ValueError, match="you can't override a field with a computed field"):
777+
with pytest.raises(
778+
TypeError, match="Field 'name' of class 'SubModel' overrides symbol of same name in a parent class"
779+
):
778780

779781
class SubModel(Model):
780782
@computed_field

0 commit comments

Comments
 (0)
0