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

Raise an Error When Computed Field Overrides Field #7346

Merged
merged 4 commits into from Sep 5, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
15 changes: 15 additions & 0 deletions tests/test_computed_fields.py
Expand Up @@ -741,3 +741,18 @@ 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) as e:

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

assert e.value.args == ("you can't override a field with a computed field",)
sydney-runkle marked this conversation as resolved.
Show resolved Hide resolved