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

Fix extra fields check in Model.__getattr__() #9082

Merged
merged 1 commit into from Mar 22, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion pydantic/main.py
Expand Up @@ -764,7 +764,7 @@ def __getattr__(self, item: str) -> Any:
except AttributeError:
pydantic_extra = None

if pydantic_extra is not None:
if pydantic_extra:
try:
return pydantic_extra[item]
except KeyError as exc:
Expand Down
24 changes: 23 additions & 1 deletion tests/test_fields.py
Expand Up @@ -3,7 +3,7 @@
import pytest

import pydantic.dataclasses
from pydantic import BaseModel, Field, PydanticUserError, RootModel, ValidationError, fields
from pydantic import BaseModel, ConfigDict, Field, PydanticUserError, RootModel, ValidationError, computed_field, fields


def test_field_info_annotation_keyword_argument():
Expand Down Expand Up @@ -122,3 +122,25 @@ class Model(BaseModel):
"{'a': FieldInfo(annotation=Union[int, NoneType], required=False, default=None), "
"'b': FieldInfo(annotation=Union[int, NoneType], required=False, default=None)}"
)


def test_computed_field_raises_correct_attribute_error():
class Model(BaseModel):
model_config = ConfigDict(extra='allow')

@computed_field
def comp_field(self) -> str:
raise AttributeError('Computed field attribute error')

@property
def prop_field(self):
raise AttributeError('Property attribute error')

with pytest.raises(AttributeError, match='Computed field attribute error'):
Model().comp_field

with pytest.raises(AttributeError, match='Property attribute error'):
Model().prop_field

with pytest.raises(AttributeError, match=f"'{Model.__name__}' object has no attribute 'invalid_field'"):
Model().invalid_field