__slots__ & Dataclasses
__slots__ optimizes memory for classes with many instances. dataclasses (Python 3.7+) auto-generate boilerplate like __init__, __repr__, and __eq__.
__slots__
class Point:
__slots__ = ("x", "y") # only these attributes allowed
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(3, 4)
print(p.x) # 3
# p.z = 5 # AttributeError — not in __slots__
import sys
class PointNoSlots:
def __init__(self, x, y): self.x = x; self.y = y
p1 = Point(1, 2)
p2 = PointNoSlots(1, 2)
print(sys.getsizeof(p1)) # smaller
print(sys.getsizeof(p2)) # largerdataclasses
from dataclasses import dataclass, field
@dataclass
class Product:
name: str
price: float
quantity: int = 0
tags: list = field(default_factory=list)
def total_value(self):
return self.price * self.quantity
p = Product("Widget", 9.99, 100, ["sale", "popular"])
print(p) # Product(name='Widget', ...)
print(p.total_value()) # 999.0
print(p == Product("Widget", 9.99, 100, ["sale", "popular"])) # Truefrozen dataclass (Immutable)
@dataclass(frozen=True)
class Point:
x: float
y: float
pt = Point(3.0, 4.0)
# pt.x = 5 # FrozenInstanceError