In this lesson, you will learn how to create "read-only" data structures using frozen dataclasses and how to fine-tune field initialization behaviors.
Making Dataclasses Immutable
By default, instances of a dataclass are mutable, meaning you can change their attributes at any time. Sometimes, you want to ensure that once an object is created, its data cannot be modified. We achieve this by setting frozen=True in the decorator.
When a dataclass is frozen, Python prevents you from assigning new values to fields after initialization. Attempting to do so will raise a FrozenInstanceError.
from dataclasses import dataclass
@dataclass(frozen=True)
class Coordinates:
x: int
y: int
point = Coordinates(10, 20)
# point.x = 5 # This would raise a FrozenInstanceError
Controlling Field Initialization
Sometimes, you have fields that shouldn't be set manually by the user during initialization, such as an internal id or a calculated cache. You can control which fields appear in the __init__ method by using field(init=False).
When you set init=False, the dataclass will not include that field as a parameter in the constructor. However, you must provide a default_factory or a default value, otherwise the class will not know how to generate that field when an object is created.
from dataclasses import dataclass, field
import uuid
@dataclass
class User:
name: str
# The ID is generated automatically and not passed during creation
user_id: str = field(init=False, default_factory=lambda: str(uuid.uuid4()))
user = User(name="Alice")
print(user.user_id) # A unique ID is generated automatically
Why use these configurations?
Using frozen=True makes your code safer by preventing accidental state changes, which is especially useful for objects representing configuration or unique data points. Using init=False allows you to maintain clean class signatures, hiding implementation details like auto-generated IDs or internal counters from the user of your class.
Key Takeaway: Use frozen=True to create immutable data structures and init=False to hide internal or auto-generated fields from the class constructor.