Skip to content

Commit

Permalink
Init private attributes from supertypes in model_post_init
Browse files Browse the repository at this point in the history
  • Loading branch information
Viicos committed Mar 29, 2024
1 parent b900fe2 commit 358f24c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pydantic/_internal/_model_construction.py
Expand Up @@ -93,7 +93,7 @@ def __new__(
private_attributes = inspect_namespace(
namespace, config_wrapper.ignored_types, class_vars, base_field_names
)
if private_attributes:
if private_attributes or base_private_attributes:
original_model_post_init = get_model_post_init(namespace, bases)
if original_model_post_init is not None:
# if there are private_attributes and a model_post_init function, we handle both
Expand Down
17 changes: 17 additions & 0 deletions tests/test_main.py
Expand Up @@ -2081,6 +2081,23 @@ class C(B):
assert calls == ['C.model_post_init']


def test_model_post_init_supertype_private_attrs():
"""https://github.com/pydantic/pydantic/issues/9098"""

class Model(BaseModel):
_private: int = 12

class SubModel(Model):
def model_post_init(self, __context: Any) -> None:
if self._private == 12:
self._private = 13
super().model_post_init(__context)

m = SubModel()

assert m._private == 13


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

Expand Down

0 comments on commit 358f24c

Please sign in to comment.