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

Keep values of private attributes set within model_post_init in subclasses #7775

Merged
merged 3 commits into from Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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 pydantic/_internal/_model_construction.py
Expand Up @@ -259,6 +259,8 @@ def init_private_attributes(self: BaseModel, __context: Any) -> None:
self: The BaseModel instance.
__context: The context.
"""
if getattr(self, '__pydantic_private__', None) is not None:
return
pydantic_private = {}
for name, private_attr in self.__private_attributes__.items():
default = private_attr.get_default()
alexmojaki marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
32 changes: 32 additions & 0 deletions tests/test_main.py
Expand Up @@ -2021,6 +2021,38 @@ class C(B):
assert calls == ['C.model_post_init']


def test_model_post_init_subclass_setting_private_attrs():
"""https://github.com/pydantic/pydantic/issues/7091"""

class Model(BaseModel):
_priv1: int = PrivateAttr(91)
_priv2: int = PrivateAttr(92)

def model_post_init(self, __context) -> None:
self._priv1 = 100

class SubModel(Model):
_priv3: int = PrivateAttr(93)
_priv4: int = PrivateAttr(94)
_priv5: int = PrivateAttr()
_priv6: int = PrivateAttr()

def model_post_init(self, __context) -> None:
self._priv3 = 200
self._priv5 = 300
super().model_post_init(__context)

m = SubModel()

assert m._priv1 == 100
assert m._priv2 == 92
assert m._priv3 == 200
assert m._priv4 == 94
assert m._priv5 == 300
with pytest.raises(AttributeError):
assert m._priv6 == 94


def test_model_post_init_correct_mro():
"""https://github.com/pydantic/pydantic/issues/7293"""
calls = []
Expand Down