Sub topic 10
Reducing per-instance memory with __slots__
This chapter assumes you know Python classes and instance attributes, and that you have seen sys.getsizeof and the idea of a shallow size. By the end you will know what __slots__ changes inside an instance, how to measure the saving, and which restrictions come with it.
Why instances cost memory
By default, each instance of a class carries a __dict__, a dictionary that maps attribute names to values. That dictionary gives you flexibility, because you can add attributes at any time. It also costs memory for every instance, which matters when a program creates hundreds of thousands of small objects.
Declaring __slots__ in a class tells CPython to reserve a fixed set of attribute storage slots in each instance. The per-instance __dict__ is no longer created.
A first example
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class SlotPoint:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
print(hasattr(Point(1, 2), "__dict__")) # True
print(hasattr(SlotPoint(1, 2), "__dict__")) # FalsePoint instances have a __dict__. SlotPoint instances do not. Their two attributes live in fixed positions inside the object itself.
Measuring the saving
sys.getsizeof is shallow, so for a regular instance you must add the size of its __dict__ to get a fair comparison. The exact numbers depend on your Python version.
import sys
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class SlotPoint:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
s = SlotPoint(1, 2)
regular = sys.getsizeof(p) + sys.getsizeof(p.__dict__)
slotted = sys.getsizeof(s)
print(regular, slotted, regular > slotted) # True on typical buildsFor a more realistic check, use tracemalloc (covered later in this tutorial) to compare the total memory of a list of a million instances of each class.
What you give up
Slots trade flexibility for memory. Watch for these behaviors:
| Behavior | Regular class | Class with `__slots__` |
|---|---|---|
| Add an undeclared attribute | Allowed | Raises `AttributeError` |
| Per-instance `__dict__` | Present | Absent |
| Weak references | Supported | Need `"__weakref__"` in the slots |
| Default values as class attributes | Allowed for any name | Conflict with a slot of the same name |
class SlotPoint:
__slots__ = ("x", "y")
p = SlotPoint()
p.x = 1
try:
p.z = 3
except AttributeError as error:
print(error)Common mistakes
- Using a plain string,
__slots__ = "x", works for one name but is easy to misread. Prefer a tuple. - Listing a name in
__slots__and also giving it a class-level default raises aValueError. - Expecting a large saving for a few objects. The saving is a fixed amount per instance, so it only matters at scale.
Exercise
A class declares __slots__ = ("a", "b"). A subclass of it declares no __slots__ and adds self.c = 3 in its constructor. Does this work, and does the subclass still save memory per instance?
Show answer
It works, because the subclass has no __slots__ and therefore gets a __dict__ that holds c. The subclass loses part of the saving, since each instance now carries a dictionary. To keep the saving, declare __slots__ = ("c",) in the subclass.
Exercise
Why does sys.getsizeof(Point(1, 2)) alone understate the memory used by a regular instance compared with a slotted one?
Show answer
sys.getsizeof is shallow. It reports the instance object but not the separate __dict__ the instance refers to, so you must add sys.getsizeof(instance.__dict__) for a fair comparison.