Skip to content

Instantly share code, notes, and snippets.

@gregglind
Created February 26, 2025 22:04
Show Gist options
  • Save gregglind/0ee7074a1642dfc485564f5bdf245d59 to your computer and use it in GitHub Desktop.
Save gregglind/0ee7074a1642dfc485564f5bdf245d59 to your computer and use it in GitHub Desktop.
Pydantic: Freezing an instance workaround
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