Create Immutable Python Dataclasses from JSON
Learn how to generate frozen (immutable) Python dataclasses from JSON data. Prevent accidental mutations and enable hashing for use in sets and as dict keys.
Detailed Explanation
Immutable Dataclasses with frozen=True
Setting frozen=True on a dataclass makes all fields read-only after construction. Any attempt to modify a field raises a FrozenInstanceError.
Example JSON
{
"id": "usr_001",
"name": "Alice",
"created_at": "2024-01-15T08:00:00Z"
}
Generated Python
from dataclasses import dataclass
@dataclass(frozen=True)
class User:
id: str
name: str
created_at: str
What frozen=True Provides
- Immutability —
user.name = "Bob"raisesFrozenInstanceError. - Hashability — Frozen dataclasses automatically get a
__hash__method, so instances can be used in sets and as dict keys. - Thread safety — Immutable objects are inherently safe to share across threads.
Using Frozen Instances
user = User(id="usr_001", name="Alice", created_at="2024-01-15T08:00:00Z")
# Use in sets
users = {user}
# Use as dict keys
cache = {user: "some_value"}
# Attempting modification raises an error
user.name = "Bob" # FrozenInstanceError!
Creating Modified Copies
Since frozen instances cannot be mutated, use dataclasses.replace() to create a new instance with some fields changed:
from dataclasses import replace
updated = replace(user, name="Bob")
# User(id='usr_001', name='Bob', created_at='2024-01-15T08:00:00Z')
frozen=True vs slots=True
In Python 3.10+, you can combine both:
@dataclass(frozen=True, slots=True)
class User:
id: str
name: str
slots=True uses __slots__ instead of __dict__, reducing memory usage and improving attribute access speed. Combined with frozen=True, you get an immutable, memory-efficient value object.
When to Use Frozen Dataclasses
- Value objects — IDs, coordinates, monetary amounts that should never change after creation.
- Configuration — Parsed once, used everywhere, never mutated.
- Cache keys — Hashability is required for dict keys and set members.
- Domain events — Events represent things that happened; they should be immutable records.
Use Case
You are building a caching layer that uses API response objects as dictionary keys, requiring them to be hashable and immutable to prevent cache corruption.
Try It — JSON to Python Converter
Related Topics
Convert Simple JSON to a Python Dataclass
Dataclasses
Python Dataclass Fields with Default Values from JSON
Dataclasses
Convert JSON to a Pydantic BaseModel in Python
Pydantic & TypedDict
Convert JSON to Python TypedDict for Dict-Like Access
Pydantic & TypedDict
Handle Optional and Nullable JSON Fields in Python
Type Annotations