Skip to content

Inheritance of Models with private attributes causes unexpected behavior via model_post_initΒ #7091

Closed
@dsayling

Description

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

When a class defines a private attribute that inherits from a model containing its own private attribute. Values set in model_post_init are reset due to the wrapped_model_post_init in ModelMetaclass

Example Code

from typing import Any, Optional
from pydantic import BaseModel, PrivateAttr


class BadBase(BaseModel):
    _random: Optional[str] = PrivateAttr(None)


class OkBase(BaseModel):
    random: Optional[str] = None


class DoesNotWork(BadBase):
    a: str
    _b: Optional[str] = PrivateAttr(None)

    def model_post_init(self, __context: Any) -> None:
        self._b = "cool"
        return super().model_post_init(__context)


class Works(OkBase):
    a: str
    _b: Optional[str] = PrivateAttr(None)

    def model_post_init(self, __context: Any) -> None:
        self._b = "cool"
        return super().model_post_init(__context)


if __name__ == "__main__":
    a_dict = {"a": "string"}
    bad_model = DoesNotWork.model_validate(a_dict)
    good_model = Works.model_validate(a_dict)
    assert bad_model._b is None  # should be "cool"
    print(bad_model._b)
    assert good_model._b == "cool"
    print(good_model._b)

Python, Pydantic & OS Version

pydantic version: 2.1.1
        pydantic-core version: 2.4.0
          pydantic-core build: profile=release pgo=false mimalloc=true
                 install path: /Users/drewayling/Library/Caches/pypoetry/virtualenvs/libs-vsna-tools-IjJ702vs-py3.8/lib/python3.8/site-packages/pydantic
               python version: 3.8.16 (default, Apr 25 2023, 14:05:36)  [Clang 14.0.3 (clang-1403.0.22.14.1)]
                     platform: macOS-13.5-x86_64-i386-64bit
     optional deps. installed: ['typing-extensions']

Selected Assignee: @lig

Metadata

Assignees

Labels

bug V2Bug related to Pydantic V2help wantedPull Request welcome

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions