Read-only model state
Prevent accidental reassignment of validated model attributes in configuration or value-object models.
Pydantic · Pipe
Set frozen=True to make a Pydantic model faux-immutable and generate a __hash__() method. Hashing is only possible when all attribute values are hashable.
The frozen configuration option makes a model faux-immutable: existing attributes cannot be reassigned, and Pydantic generates a __hash__() method. The resulting instance is hashable only when all its attribute values are hashable.
model_config = ConfigDict(frozen=True)| Name | Type | Description |
|---|---|---|
frozen | bool | Whether a model is faux-immutable and whether Pydantic generates its hash method. |
A boolean configuration value controlling model mutability and hash-method generation.
from pydantic import BaseModel, ConfigDict
class User(BaseModel):
model_config = ConfigDict(frozen=True)
name: str
user = User(name='Ada')
print(hash(user))
try:
user.name = 'Grace'
except Exception as exc:
print(type(exc).__name__)Setting frozen=True prevents attribute assignment after initialization and causes Pydantic to generate a hash method. Hashing succeeds here because the model's only field contains a hashable string.
Prevent accidental reassignment of validated model attributes in configuration or value-object models.
Use models as dictionary keys or set members when every field value is hashable.
Signal that updates should produce a new model instance instead of mutating the current one.
Set model_config = ConfigDict(frozen=True) on the model. Pydantic then disallows attribute assignment and generates a __hash__() method.
Follow-up: Does frozen guarantee hashability? No: hashability still depends on all model attributes being hashable.
The model becomes faux-immutable, meaning attempts to assign to its attributes are rejected after construction. The option also requests generation of a hash method.
Follow-up: What happens if a field contains a list? The model may not be hashable because the list is unhashable, even though assignment to the field is blocked.
The documented default is False, so ordinary models allow attribute assignment unless frozen is enabled. The setting is the inverse of the older V1 allow_mutation option.
Follow-up: What was the V1 counterpart? allow_mutation was the inverse setting and defaulted to True.
ConfigDictBaseModel__setattr____hash__allow_mutation