Created
February 26, 2025 22:04
-
-
Save gregglind/0ee7074a1642dfc485564f5bdf245d59 to your computer and use it in GitHub Desktop.
Pydantic: Freezing an instance workaround
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pydantic import BaseModel | |
from typing import Any | |
class UnfrozenThing(BaseModel): | |
model_config = {"extra": "allow", "validate_assignment": True} | |
f: str | None = None | |
def model_post_init(self, __context: Any) -> None: | |
self.f = 'a' | |
self.model_config | |
class FrozenThing(UnfrozenThing): | |
model_config = {"extra":"ignore", "validate_assignment": True, "frozen": True} | |
def model_post_init(self, __context: Any) -> None: | |
pass | |
t = FrozenThing.model_validate(UnfrozenThing(f="some string",extra_val=3).model_dump()) | |
t.model_dump() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment