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

Address case where model_construct on a class which defines model_post_init fails with AttributeError: __pydantic_private__ when subsequently model_copy'd #9168

Merged
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
6 changes: 3 additions & 3 deletions pydantic/main.py
Expand Up @@ -721,7 +721,7 @@ def __copy__(self: Model) -> Model:
_object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
_object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

if self.__pydantic_private__ is None:
if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
sydney-runkle marked this conversation as resolved.
Show resolved Hide resolved
_object_setattr(m, '__pydantic_private__', None)
else:
_object_setattr(
Expand All @@ -742,7 +742,7 @@ def __deepcopy__(self: Model, memo: dict[int, Any] | None = None) -> Model:
# and attempting a deepcopy would be marginally slower.
_object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

if self.__pydantic_private__ is None:
if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
sydney-runkle marked this conversation as resolved.
Show resolved Hide resolved
_object_setattr(m, '__pydantic_private__', None)
else:
_object_setattr(
Expand Down Expand Up @@ -902,7 +902,7 @@ def __eq__(self, other: Any) -> bool:
# Perform common checks first
if not (
self_type == other_type
and self.__pydantic_private__ == other.__pydantic_private__
and getattr(self, '__pydantic_private__', None) == getattr(other, '__pydantic_private__', None)
and self.__pydantic_extra__ == other.__pydantic_extra__
):
return False
Expand Down
14 changes: 14 additions & 0 deletions tests/test_main.py
Expand Up @@ -3280,3 +3280,17 @@ class Y(BaseModel):
x: Union[X, None]

assert Y(x={'y': None}).x.y is None


def test_model_construct_with_model_post_init_and_model_copy() -> None:
class Model(BaseModel):
id: int

def model_post_init(self, context: Any) -> None:
super().model_post_init(context)

m = Model.model_construct(id=1)
copy = m.model_copy(deep=True)

assert m == copy
assert id(m) != id(copy)