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

Add more support for private attributes in model_construct call #8525

Merged
merged 4 commits into from Jan 9, 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
8 changes: 4 additions & 4 deletions pdm.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions pydantic/main.py
Expand Up @@ -237,6 +237,12 @@ def model_construct(cls: type[Model], _fields_set: set[str] | None = None, **val

if cls.__pydantic_post_init__:
m.model_post_init(None)
# update private attributes with values set
if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
for k, v in values.items():
if k in m.__private_attributes__:
m.__pydantic_private__[k] = v

elif not cls.__pydantic_root_model__:
# Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
# Since it doesn't, that means that `__pydantic_private__` should be set to None
Expand Down
10 changes: 10 additions & 0 deletions tests/test_construction.py
Expand Up @@ -519,3 +519,13 @@ class MyModel(BaseModel):
m = MyModel.model_construct(b='b')

assert m.model_dump_json() == '{"a":"a","b":"b"}'


def test_initialize_with_private_attr():
class MyModel(BaseModel):
_a: str

m = MyModel.model_construct(_a='a')

assert m._a == 'a'
assert '_a' in m.__pydantic_private__