SyntaxStudy
Sign Up
Python __slots__ & Dataclasses
Python Intermediate 10 min read

__slots__ & Dataclasses

__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))   # larger

dataclasses

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"]))  # True

frozen dataclass (Immutable)

@dataclass(frozen=True)
class Point:
    x: float
    y: float

pt = Point(3.0, 4.0)
# pt.x = 5   # FrozenInstanceError
Example
from dataclasses import dataclass, field
from typing import List

@dataclass(order=True)
class Student:
    name:   str
    gpa:    float
    grades: List[int] = field(default_factory=list, compare=False)

    def average(self):
        return sum(self.grades) / len(self.grades) if self.grades else 0.0

students = [
    Student("Alice", 3.9, [95, 92, 98]),
    Student("Bob",   3.5, [85, 88, 82]),
    Student("Carol", 3.7, [90, 91, 93]),
]
students.sort(reverse=True)
for s in students:
    print(f"{s.name}: GPA {s.gpa}, avg grade {s.average():.1f}")
Pro Tip

Use field(default_factory=list) — NEVER use a mutable default like grades: list = [] in a dataclass. A mutable default is shared across all instances.