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=Truemakes class instances immutable: after creation, attribute values cannot be changed — any assignment attempt will raise an error.slots=Trueprevents 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.