Part 14 / Topic 5 of 11
__slots__
Normally each object can take any new attribute, because its attributes live in a flexible dict. __slots__ is a class variable that lists the only attributes the objects may have. Python then stores them in fixed places instead of a dict.
Think of an egg tray versus a bag: the tray holds exactly 12 eggs in fixed holes and takes less space, but you cannot put a melon in it.
class Reading:
def __init__(self, sensor, celsius):
self.sensor = sensor
self.celsius = celsius
class SlimReading:
__slots__ = ("sensor", "celsius")
def __init__(self, sensor, celsius):
self.sensor = sensor
self.celsius = celsius
slim = SlimReading("pune-01", 31.5)
print(Reading("pune-01", 31.5).__dict__) # {'sensor': 'pune-01', 'celsius': 31.5}
print(hasattr(slim, "__dict__")) # False
try:
slim.location = "roof"
except AttributeError as error:
print(error)
# 'SlimReading' object has no attribute 'location' and no __dict__ for setting new attributes
Measure it
sys.getsizeof(obj) gives an object's size in bytes, but it is shallow: it does not count the objects it points to, such as the attribute dict. For the real total, use tracemalloc (trace memory allocations), which counts every byte Python allocates while it is running.
import tracemalloc
class Reading:
def __init__(self, sensor, celsius):
self.sensor, self.celsius = sensor, celsius
class SlimReading:
__slots__ = ("sensor", "celsius")
def __init__(self, sensor, celsius):
self.sensor, self.celsius = sensor, celsius
def bytes_for(cls):
tracemalloc.start()
items = [cls("pune-01", 31.5) for _ in range(100_000)]
used = tracemalloc.get_traced_memory()[0] # (current, peak)
tracemalloc.stop()
return used
print(bytes_for(Reading) // 1024, "KiB") # 9384 KiB (varies)
print(bytes_for(SlimReading) // 1024, "KiB") # 5478 KiB (varies)
About 40% less memory on CPython 3.13 for 100,000 small objects.
✅ Use __slots__ when |
❌ Skip it when |
|---|---|
| you create many (100,000+) small objects | you have a handful of objects |
| the attributes are fixed and known | code needs to add attributes later |
| memory really is a problem (you measured) | you use multiple inheritance with several slotted bases |
🔍 Going deeper:
@dataclass(slots=True)writes__slots__for you. A subclass without its own__slots__gets a__dict__again. Slotted objects cannot be weak-referenced unless you add"__weakref__"to the slots.
Full program: examples/04_slots_memory.py.
Done here? The practice set for Part 14 — 8 exercises with solutions — is on the part page.