Skip to content

Commit

Permalink
Add more support for private attributes in model_construct call (#8525
Browse files Browse the repository at this point in the history
)
  • Loading branch information
sydney-runkle committed Jan 9, 2024
1 parent 54d1185 commit 2b09cf4
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
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__

0 comments on commit 2b09cf4

Please sign in to comment.