Sub topic 11
When slots are worth it and when they are not
This chapter helps you decide whether a class should declare __slots__. It assumes you have read the earlier chapters. You should know how the instance __dict__ works, what member descriptors are, how slots interact with inheritance, and how to add __weakref__. It also assumes you can read basic output from tracemalloc.
Slots are an optimization with side effects. They save memory per instance and they restrict what instances can do. Whether that trade is good depends on how many instances you create and how much dynamic behavior your code needs.
What slots give you
Slots provide three benefits, and they differ a lot in value.
- Lower memory per instance. Each instance no longer carries its own
__dict__. This is the main benefit, and it only matters when instances are numerous. - A fixed set of attributes. Assigning to a name that is not declared raises
AttributeError. This catches typos such asp.xx = 5, though it is a side effect of the design and not a full validation system. - Slightly different attribute access cost. Reading a slot goes through a member descriptor, which reads a fixed offset in the object. Differences in speed are small and vary with the Python version. Do not choose slots for speed without measuring.
The first benefit is smaller than it used to be. Recent CPython versions (3.11 and later) store attribute values compactly and often avoid building a full dictionary for an instance until something asks for it, for example by reading obj.__dict__. The gap between a plain and a slotted instance has narrowed on those versions. The size of the saving depends on your Python version and implementation, so treat any number from a blog post, including old ones, as a hypothesis to test.
What slots cost you
Every restriction from the earlier chapters becomes a cost when your design needs the flexibility it removed.
| Feature | Plain class | Slotted class |
|---|---|---|
| Add arbitrary attributes at runtime | Works | `AttributeError` |
| `vars(obj)` and `obj.__dict__` | Works | No `__dict__` unless you add it as a slot |
| Weak references | Works | Fail unless `__weakref__` is a slot |
| Class-level default with the same name as a slot | Works | `ValueError` at class creation |
| `functools.cached_property` | Works | Fails, because it needs `__dict__` |
| Multiple inheritance from several bases with non-empty slots | Works | Can raise a layout conflict |
| Subclass keeps the memory savings | Not applicable | Only if the subclass also declares `__slots__` |
Two of these are easy to miss until they bite, so the next section shows them in code.
Two gotchas worth seeing
The first is cached_property. It stores its computed result in the instance __dict__, so it cannot work on an instance that has none.
from functools import cached_property
class Circle:
__slots__ = ("radius",)
def __init__(self, radius):
self.radius = radius
@cached_property
def area(self):
return 3.14159 * self.radius ** 2
try:
print(Circle(2).area)
except TypeError as exc:
print("TypeError:", exc)Running this prints a TypeError that says there is no __dict__ attribute to cache the property. You have two fixes. You can add "__dict__" to __slots__, which gives up most of the memory saving. Or you can replace cached_property with a plain property or with an explicit slot such as _area that you fill in yourself.
The second gotcha is multiple inheritance. Each slotted base with non-empty __slots__ fixes a memory layout for its instances. CPython cannot merge two such layouts.
class A:
__slots__ = ("a",)
class B:
__slots__ = ("b",)
try:
class C(A, B):
pass
except TypeError as exc:
print("TypeError:", exc)This raises a TypeError that mentions a layout conflict between multiple bases. Empty slots do not conflict, because they add no storage. That is why mixins in slotted hierarchies usually declare __slots__ = ().
class LoggingMixin:
__slots__ = ()
def log(self, message):
print(f"[{type(self).__name__}] {message}")
class Account(LoggingMixin):
__slots__ = ("owner", "balance")
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
acct = Account("Ana", 100)
acct.log("created")
print(hasattr(acct, "__dict__"))The mixin contributes behavior and no storage, so Account stays dict-free and the last line prints False.
Measure with your own class
Do not decide from general advice. Measure the class you are thinking about, on the Python version you deploy. The earlier chapter used sys.getsizeof for a quick estimate. For a decision, tracemalloc is better, because it counts everything allocated while you build many instances, including any dictionaries and other overhead that getsizeof does not add up for you.
import tracemalloc
class PlainPoint:
def __init__(self, x, y):
self.x = x
self.y = y
class SlottedPoint:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
def bytes_per_instance(cls, count=100_000):
tracemalloc.start()
before, _ = tracemalloc.get_traced_memory()
items = [cls(i, i) for i in range(count)]
after, _ = tracemalloc.get_traced_memory()
tracemalloc.stop()
del items
return (after - before) / count
print("plain :", round(bytes_per_instance(PlainPoint)), "bytes")
print("slotted:", round(bytes_per_instance(SlottedPoint)), "bytes")Some points on reading the result:
- The figure includes the list slot that holds each instance (8 bytes on a 64-bit build) and the integer objects. These are the same for both classes, so they shrink the relative difference. This is the honest way to see it: slots save a fixed amount per object, not a percentage of your program.
- Multiply the per-instance difference by the number of instances you expect. A saving of tens of bytes across a hundred objects is invisible. Across ten million objects it is hundreds of megabytes.
- Run the same script on every Python version you support. The numbers can differ noticeably between versions.
- Measure the whole program when you can, not only the class. If instances are small and your data is dominated by large strings or lists held in attributes, the slot saving is a small part of the total.
A rough break-even picture
The saving scales with instance count and is a constant per instance, so the question is whether the constant times the count matters to you. The chart below uses an illustrative saving of 100 bytes per instance. Replace it with the number you measured.
When slots are worth it
Slots are a good fit when most of these are true:
- You create very many instances of the same class, typically hundreds of thousands or more. Examples are parsed records, graph nodes, tokens, events, points in a simulation, or cached rows.
- The set of attributes is small, known in advance, and stable.
- Instances are not meant to be extended or patched at runtime.
- Memory pressure is a measured problem, or you must fit a data set into a fixed amount of RAM.
- You value catching misspelled attribute names early, and your tests do not already cover that.
A typical good case is a node class in a large tree or graph. Every node has the same few fields, nodes are created in bulk, and nobody adds attributes to them.
class TreeNode:
__slots__ = ("value", "left", "right")
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
root = TreeNode(1, TreeNode(2), TreeNode(3))
print(root.left.value, root.right.value)When slots are not worth it
Skip slots, or remove them, in these situations:
- You have few instances. Configuration objects, service classes, and singletons exist in small numbers. The saving is a handful of bytes, and you still pay the restrictions.
- The class relies on dynamic attributes. Frameworks, ORMs, test doubles, and code that uses
setattrwith arbitrary names orvars()to copy state all expect a__dict__. - You use
cached_propertyor other tools that store data in the instance dictionary and you do not want to work around them. - The class is a base class for third-party users. You cannot control whether subclasses declare their own slots. If they do not, they get a
__dict__and the saving disappears silently. If they combine your class with other slotted bases, they may hit a layout conflict. - You cannot show a memory problem. Adding slots before you measure is premature optimization with a compatibility price.
- Your data is mostly large values. If each instance holds a big list or a long string, the dictionary is a small part of the footprint.
Related options deserve a look before you commit. If you only need a record with a few fields, a dataclass(slots=True) gives you slots with less boilerplate. If you have millions of homogeneous records, a different data layout, such as arrays or a columnar library, can save far more than slots do.
Compatibility notes
Pickling and copying work with slotted classes in the normal case. The default pickle protocol in modern Python handles slots without extra code. Very old protocols (0 and 1) do not, unless you define __getstate__. If you pickle data for long-term storage or for old consumers, test with the protocol you actually use.
Introspection tools that read __dict__ will not see slot values. Debuggers, serializers, and helper functions written as vars(obj) will fail or return nothing useful. Check what your tooling does before you add slots to a class that already has users.
A decision flow
Practical checklist
Before you merge a change that adds __slots__, work through this list.
- Measure bytes per instance with
tracemallocon the Python version you deploy. - Estimate the instance count and multiply to see the total saving.
- Search the code base for
__dict__,vars(,setattr(,cached_property, andweakrefon the class. - Declare
__slots__on every subclass, and__slots__ = ()on mixins. - Add
__weakref__only if something needs weak references. - Run your test suite, including any serialization tests.
Summary of the decision
Use slots when you have a large number of small, uniform, stable objects and a measurement that shows a saving you care about. Avoid them for classes that are few, flexible, or extended by others. When you are unsure, leave them out. Adding __slots__ later is a small change, but removing it after other code depends on its restrictions can be harder.
Exercise
A service creates about 200 Settings objects at startup. Each has six attributes and is occasionally patched in tests with unittest.mock.patch.object. A teammate proposes adding __slots__ to save memory. What do you recommend, and why?
Show answer
Do not add slots. With only about 200 instances, the saving is tiny and unlikely to matter. Slots also remove flexibility the tests rely on, and patching an attribute on an instance can fail when the class has restricted storage. The costs are real and the benefit is not measurable here.
Exercise
A class Event declares __slots__ = ("kind", "time"). A subclass ClickEvent(Event) adds a position attribute but does not declare __slots__. Your program creates 5 million ClickEvent objects and memory use is higher than expected. What is the cause, and how do you fix it and check the fix?
Show answer
ClickEvent has no __slots__, so its instances get a __dict__ again, and the memory saving from Event is lost. Fix it by adding __slots__ = ("position",) to ClickEvent. Check with hasattr(ClickEvent(...), "__dict__"), which should be False, and compare bytes per instance with tracemalloc before and after.