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

Init private attributes from supertypes in model_post_init #9134

Merged
merged 1 commit into from Mar 29, 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
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