snippetpythonModeratepending
Python dataclass frozen and slots for performance
Viewed 0 times
dataclassfrozenslotsimmutablememoryperformance
Problem
Regular Python classes use __dict__ for attributes, consuming more memory. Dataclasses can be made immutable and memory-efficient.
Solution
Use frozen=True and slots=True for optimized dataclasses:
from dataclasses import dataclass
@dataclass(frozen=True, slots=True) # Python 3.10+
class Point:
x: float
y: float
z: float = 0.0
# frozen=True:
# - Instances are immutable (hashable, can be dict keys/set members)
# - Assignment raises FrozenInstanceError
p = Point(1.0, 2.0)
# p.x = 3.0 # FrozenInstanceError!
points_set = {Point(1, 2), Point(3, 4)} # Works! (hashable)
# slots=True:
# - Uses __slots__ instead of __dict__
# - 30-40% less memory per instance
# - Slightly faster attribute access
# - Can't add arbitrary attributes
# Combining with field():
from dataclasses import field
@dataclass(frozen=True, slots=True)
class Config:
host: str = 'localhost'
port: int = 8080
tags: tuple[str, ...] = () # Use tuple for frozen (list is mutable)
# Don't use list with frozen! Use tuple instead
# Performance comparison (1M instances):
# Regular class: ~200MB
# dataclass: ~200MB
# slots dataclass: ~130MB
# namedtuple: ~100MB
from dataclasses import dataclass
@dataclass(frozen=True, slots=True) # Python 3.10+
class Point:
x: float
y: float
z: float = 0.0
# frozen=True:
# - Instances are immutable (hashable, can be dict keys/set members)
# - Assignment raises FrozenInstanceError
p = Point(1.0, 2.0)
# p.x = 3.0 # FrozenInstanceError!
points_set = {Point(1, 2), Point(3, 4)} # Works! (hashable)
# slots=True:
# - Uses __slots__ instead of __dict__
# - 30-40% less memory per instance
# - Slightly faster attribute access
# - Can't add arbitrary attributes
# Combining with field():
from dataclasses import field
@dataclass(frozen=True, slots=True)
class Config:
host: str = 'localhost'
port: int = 8080
tags: tuple[str, ...] = () # Use tuple for frozen (list is mutable)
# Don't use list with frozen! Use tuple instead
# Performance comparison (1M instances):
# Regular class: ~200MB
# dataclass: ~200MB
# slots dataclass: ~130MB
# namedtuple: ~100MB
Why
slots=True reduces memory ~35% and frozen=True enables use as dict keys and set members. Combined, they create efficient value objects.
Revisions (0)
No revisions yet.