Python Frozen Dataclass Modification Error Fix
In this tutorial, you'll learn about Python Frozen Dataclass Modification Error Fix. We cover key concepts, practical examples, and best practices.
Python frozen dataclasses raise "FrozenInstanceError: cannot assign to field" when you try to modify an attribute after initialization. Frozen dataclasses are immutable — once created, their values cannot change.
The Problem
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
p = Point(10, 20)
p.x = 30
Error:
dataclasses.FrozenInstanceError: cannot assign to field 'x'
Wrong Code
from dataclasses import dataclass
@dataclass(frozen=True)
class Config:
host: str
port: int
config = Config("localhost", 8080)
config.port = 9090 # FrozenInstanceError!
Right Code
from dataclasses import dataclass
@dataclass(frozen=True)
class Config:
host: str
port: int
def with_port(self, new_port: int) -> 'Config':
return Config(self.host, new_port)
config = Config("localhost", 8080)
new_config = config.with_port(9090)
print(f"Old: {config}")
print(f"New: {new_config}")
Expected output:
Old: Config(host='localhost', port=8080)
New: Config(host='localhost', port=9090)
Step-by-Step Fix
Step 1: Make the dataclass non-frozen
# Remove frozen=True to allow mutation
@dataclass
class Point:
x: int
y: int
p = Point(10, 20)
p.x = 30 # Works now
Step 2: Use object.setattr to bypass frozen (not recommended)
@dataclass(frozen=True)
class Point:
x: int
y: int
p = Point(10, 20)
object.__setattr__(p, 'x', 30) # Works but breaks immutability contract
Step 3: Create a new instance with modified values
@dataclass(frozen=True)
class Point:
x: int
y: int
def move(self, dx: int, dy: int) -> 'Point':
return Point(self.x + dx, self.y + dy)
p = Point(10, 20)
p2 = p.move(5, -3)
print(p2) # Point(x=15, y=17)
Step 4: Use init for conditional initialization
@dataclass(frozen=True)
class Temperature:
celsius: float
def __post_init__(self):
# Validation works even with frozen=True
if self.celsius < -273.15:
raise ValueError("Below absolute zero")
Step 5: Use replace for partial updates
from dataclasses import replace
@dataclass(frozen=True)
class Person:
name: str
age: int
email: str
p = Person("Alice", 30, "alice@example.com")
p2 = replace(p, age=31, email="alice@newdomain.com")
print(p2) # Person(name='Alice', age=31, email='alice@newdomain.com')
Step 6: Use a mutable dataclass with frozen fields pattern
@dataclass
class Config:
_host: str = field(init=True, repr=True)
_port: int = field(init=True, repr=True)
@property
def host(self):
return self._host
@property
def port(self):
return self._port
Prevention Tips
- Use frozen dataclasses for value objects that should never change
- Use
replace()to create modified copies of frozen dataclasses - Design frozen dataclasses with methods that return new instances
- Use non-frozen dataclasses for objects that require mutation
- Add
__post_init__validation even in frozen dataclasses
Common Mistakes with dataclass frozen
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro