Sobes.tech
Middle

Will an immutable dataclass with slots and frozen attributes be?

sobes.tech AI

Answer from AI

Yes, a dataclass with parameters slots=True and frozen=True will be immutable and more memory-efficient.

  • frozen=True makes class instances immutable: after creation, attribute values cannot be changed — any assignment attempt will raise an error.
  • slots=True prevents the creation of a __dict__ for each instance, saving memory and speeding up attribute access.

Example:

from dataclasses import dataclass

@dataclass(slots=True, frozen=True)
class Point:
    x: int
    y: int

p = Point(1, 2)
print(p.x)  # 1
p.x = 3     # Error: cannot assign to field 'x'

Thus, this dataclass combines the benefits of immutability and memory optimization.