Skip to content

Commit

Permalink
Raise an Error When Computed Field Overrides Field (#7346)
Browse files Browse the repository at this point in the history
Co-authored-by: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>
  • Loading branch information
sydney-runkle and adriangb committed Sep 5, 2023
1 parent 99555e9 commit d78afb5
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
6 changes: 6 additions & 0 deletions pydantic/_internal/_fields.py
Expand Up @@ -19,6 +19,7 @@
from ..fields import FieldInfo
from ..main import BaseModel
from ._dataclasses import StandardDataclass
from ._decorators import DecoratorInfos


def get_type_hints_infer_globalns(
Expand Down Expand Up @@ -196,6 +197,11 @@ def collect_model_fields( # noqa: C901
except AttributeError:
pass # indicates the attribute was on a parent class

# Use cls.__dict__['__pydantic_decorators__'] instead of cls.__pydantic_decorators__
# to make sure the decorators have already been built for this exact class
decorators: DecoratorInfos = cls.__dict__['__pydantic_decorators__']
if ann_name in decorators.computed_fields:
raise ValueError("you can't override a field with a computed field")
fields[ann_name] = field_info

if typevars_map:
Expand Down
13 changes: 13 additions & 0 deletions tests/test_computed_fields.py
Expand Up @@ -741,3 +741,16 @@ def double_x(self) -> T:

with pytest.warns(UserWarning, match='Expected `int` but got `str` - serialized value may not be as expected'):
B[int]().model_dump()


def test_computed_field_override_raises():
class Model(BaseModel):
name: str = 'foo'

with pytest.raises(ValueError, match="you can't override a field with a computed field"):

class SubModel(Model):
@computed_field
@property
def name(self) -> str:
return 'bar'

0 comments on commit d78afb5

Please sign in to comment.