How to Replace Fields in an Immutable Dataclass in Python
Create a new copy of a frozen dataclass with selected fields changed, leaving the original unchanged.
Python code
17 linesfrom dataclasses import dataclass, replace
@dataclass(frozen=True)
class ServerConfig:
name: str
cpu: int = 2
ram: int = 4096
tags: tuple = ()
original = ServerConfig("web-01", cpu=4, tags=("env:prod",))
updated = replace(original, ram=8192, tags=("env:prod", "region:us-east"))
print("Original:", original)
print("Updated: ", updated)
print("Original unchanged:", original)
Output
Original: ServerConfig(name='web-01', cpu=4, ram=4096, tags=('env:prod',))
Updated: ServerConfig(name='web-01', cpu=4, ram=8192, tags=('env:prod', 'region:us-east'))
Original unchanged: ServerConfig(name='web-01', cpu=4, ram=4096, tags=('env:prod',))
How it works
The dataclasses.replace() function creates a new instance of the dataclass, copying all fields and overriding only the ones you specify. Because the dataclass is frozen (immutable), you cannot modify attributes in place, so replace() is the idiomatic way to produce an updated version. This pattern is key for configuration objects that must remain immutable during a deployment, ensuring that no part of the system accidentally changes a shared config. The original object remains untouched, which makes behavior predictable and easier to reason about.
Common mistakes
- Forgetting that `replace()` returns a new object; ignoring the return value leaves the original unchanged and the update lost.
- Trying to assign to a field of a frozen dataclass (e.g., `original.ram = 8192`), which raises `FrozenInstanceError`.
- Using `dataclasses.replace()` on a dataclass with fields that are not hashable if you also rely on `frozen=True` for dictionary keys.
Variations
- Use `dataclasses.asdict()` to convert to a dict, modify, and rebuild — less type-safe.
- Define a method on the dataclass that returns `replace(self, **changes)` for a fluid API.
Real-world use cases
- In deployment pipelines, immutable environment configs are copied with a new revision while keeping the base template untouched.
- During feature flag rollouts, create a modified copy of a service configuration for canary instances.
- When building immutable data models for audit logs, clone records with an updated timestamp without mutating the original event.
Sponsored
More from Production deployment patterns
- Auto Rollback on Error Rate Exceeded in Python medium
- Automate Semantic Versioning with Conventional Commits in Python medium
- Design a Data Helper for Beginners in Python easy
- Docker healthcheck CMD mock in Python easy
- Generate a Mock Artifact Version Tag in Python easy
- Generate a docker-compose.yml with mock services in Python easy
Keep learning
Related tutorials and quizzes for this topic.