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

Adding extra field via setattr adds field to model_extra #6365

Merged
merged 3 commits into from
Jul 2, 2023
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: 2 additions & 0 deletions changes/6365-aaraney.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Extra fields added via `setattr` (i.e. `m.some_extra_field = 'extra_value'`)
are added to `.model_extra` if `model_config` `extra='allowed'`. Fixed #6333.
3 changes: 3 additions & 0 deletions pydantic/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -737,6 +737,9 @@ def __setattr__(self, name: str, value: Any) -> None:
elif self.model_config.get('extra') != 'allow' and name not in self.model_fields:
# TODO - matching error
raise ValueError(f'"{self.__class__.__name__}" object has no field "{name}"')
elif self.model_config.get('extra') == 'allow' and name not in self.model_fields:
# SAFETY: __pydantic_extra__ is not None when extra = 'allow'
self.__pydantic_extra__[name] = value # type: ignore
else:
self.__dict__[name] = value
self.__pydantic_fields_set__.add(name)
Expand Down
4 changes: 4 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,10 @@ class Model(BaseModel):
assert m.a == 10.2
assert m.b == 12
assert m.model_extra == {'b': 12}
m.c = 42
assert 'c' not in m.__dict__
assert m.__pydantic_extra__ == {'b': 12, 'c': 42}
assert m.model_dump() == {'a': 10.2, 'b': 12, 'c': 42}


@pytest.mark.parametrize('extra', ['ignore', 'forbid', 'allow'])
Expand Down