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.

Easy Python 3.9+ Aug 9, 2026 Production deployment patterns 15 views 0 copies

Python code

17 lines
Python 3.9+
from 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

stdout
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

  1. Use `dataclasses.asdict()` to convert to a dict, modify, and rebuild — less type-safe.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Production deployment patterns

Related tutorials and quizzes for this topic.