Python __slots__ Explained: Memory Savings, Speed and 6 Traps, Tested
Python slots replace the per-object attribute dictionary with a fixed set of fields. Older articles promise big memory and speed wins, but CPython has changed. We measured a million objects on Python 3.13: memory dropped by up to 41 percent, attribute speed did not change at all, and six traps can break your code if you add slots without thinking.
- Python slots (
__slots__) store attributes in fixed positions instead of a per-instance dictionary. - One million two-attribute objects used 96.4 MB normally and 56.4 MB with slots, a 41 percent saving, on Python 3.13.6.
- Reading and writing attributes took the same time with or without slots (about 12 ns), and creating slotted objects was actually slower in our run.
- Slots block new attributes, weak references and
cached_property, and a subclass without its own__slots__silently gets a dictionary back.
Every normal Python object can grow new attributes at any time, because its attributes live in a dictionary. That flexibility costs memory, and when you create millions of small objects (points, records, graph nodes, parsed rows) the cost adds up. Python slots trade flexibility for a fixed layout: you declare the attribute names up front, and Python reserves exactly that much space.
Many tutorials still quote numbers from Python 3.6-era benchmarks. We re-measured everything on Python 3.13.6 using tracemalloc for memory and timeit for speed (best of five runs), and the results are more nuanced.
What __slots__ does
Without slots, each instance carries space for a __dict__ that maps attribute names to values. With __slots__, the class creates a descriptor for each listed name, and each instance stores values in a small fixed array. We confirmed it: a slotted object had no __dict__ attribute at all, and S.x on the class printed <member 'x' of 'S' objects>, which is that descriptor.
The syntax
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
__slots__ is a class attribute containing the allowed attribute names, usually a tuple of strings. Nothing else about the class changes: methods, properties and class methods work as before.
Memory, measured
| Objects | Normal class | With __slots__ | Saving |
|---|---|---|---|
| 1,000,000 objects, 2 attributes set to None | 96.4 MB | 56.4 MB | 41% |
| 1,000,000 objects, 2 integer attributes | 128.4 MB | 88.4 MB | 31% |
| 200,000 objects, 10 attributes | 33.6 MB | 24.0 MB | 29% |
Slots saved about 40 bytes per object in every test. The percentage depends on what else you store: with integer attributes, the integer objects themselves (which slots do not shrink) take a share of the total, so the relative saving falls to 31 percent. For workloads with millions of small objects, saving tens of megabytes is still worthwhile. Beware of claims of 50 to 70 percent; those came from older Python versions with larger per-instance dictionaries.
Speed, measured
| Operation | Normal | Slots |
|---|---|---|
Read obj.x |
12.0 ns | 11.9 ns |
Write obj.x = 5 |
12.8 ns | 12.6 ns |
| Create an instance | 85.1 ns | 123.5 ns |
Attribute access was identical within measurement noise. Creating slotted instances was slower in our run, which surprised us; we repeated it with the same result, though the exact gap may differ on other machines and versions. The practical conclusion is clear: do not add slots for speed. Add them for memory, or to stop accidental new attributes.
Why the gains shrank in modern Python
Recent CPython versions store the attributes of ordinary objects inline and only build a real dictionary when code asks for __dict__. Our test showed this directly: after we simply read p.__dict__ once, writing an attribute on that normal object slowed from 12.8 ns to 28.4 ns, because a full dictionary now existed. Slots still avoid the space that layout needs, but normal objects are far cheaper than they used to be, so the gap is smaller than older benchmarks suggest.
Slots with dataclasses
from dataclasses import dataclass
@dataclass(slots=True)
class D:
x: int
y: int
# 1,000,000 instances: 88.4 MB, the same as the hand-written slotted class
Since Python 3.10, @dataclass(slots=True) generates __slots__ from the field list, so you get the memory saving without repeating names. It is the easiest way to use slots for data-holding classes; see our Python dataclasses guide for the rest of the dataclass options.
Trap 1: you cannot add new attributes
s = SlotPoint(1, 2)
s.z = 3
# AttributeError: 'SlotPoint' object has no attribute 'z'
# and no __dict__ for setting new attributes
This is a feature when it catches typos like self.vlaue = 1, and a problem when libraries or tests attach extra attributes to your objects (some mocking and serialisation tools do). The normal class happily accepted p.z = 3.
Trap 2: inheritance can silently undo slots
class Child(SlotPoint):
pass
c = Child(1, 2); c.z = 9
hasattr(c, "__dict__"), c.__dict__ # True {'z': 9}
class Child2(SlotPoint):
__slots__ = ("z",)
hasattr(Child2(1, 2), "__dict__") # False
A subclass that does not declare its own __slots__ gets a normal dictionary again, and the memory saving disappears without any warning. Every class in the hierarchy needs __slots__, listing only the new names (repeating the parent’s names wastes space). Inheritance rules in general are covered in our classes and objects guide.
Trap 3: weak references stop working
weakref.ref(SlotPoint(1, 2))
# TypeError: cannot create weak reference to 'SlotPoint' object
class W:
__slots__ = ("x", "__weakref__")
weakref.ref(W()) # works
Caches, observer patterns and some frameworks rely on weak references. Add "__weakref__" to the slots if you need them.
Trap 4: class-level defaults clash with slots
class Bad:
__slots__ = ("x",)
x = 5
# ValueError: 'x' in __slots__ conflicts with class variable
You cannot give a slot a default by assigning it in the class body, because the slot descriptor and the class variable would use the same name. Set defaults in __init__ instead, or use a dataclass with slots=True, which handles field defaults for you.
Trap 5: functools.cached_property fails
class CP:
__slots__ = ("x",)
@cached_property
def big(self): return 1
CP().big
# TypeError: No '__dict__' attribute on 'CP' instance to cache 'big' property.
cached_property stores its result in the instance dictionary, which slotted objects do not have. Use a plain property with a dedicated slot for the cached value, or functools.lru_cache on a method, as described in our functools guide.
Trap 6: vars() and __dict__-based tools break
vars(p) # {'x': 5, 'y': 2, 'z': 3}
vars(s) # TypeError: vars() argument must have __dict__ attribute
class Both:
__slots__ = ("x", "__dict__") # escape hatch
b = Both(); b.x = 1; b.y = 2
b.__dict__ # {'y': 2}
Code that serialises objects with vars(obj) or obj.__dict__ fails on slotted classes. Pickling still worked in our test (pickle.loads(pickle.dumps(s)).x returned the right value), but custom JSON encoders often need updating. Adding "__dict__" to the slots restores dynamic attributes for names outside the list, at the cost of most of the saving.
When to use __slots__
- Use them for classes with millions of instances and a fixed set of fields: points, tokens, tree nodes, records from a large file.
- Use them when you want to forbid accidental attributes on value objects.
- Prefer
@dataclass(slots=True)for new data classes; it is less error-prone than writing slots by hand. - Skip them for classes with only a few hundred instances, for classes used with frameworks that add attributes, and when you need
cached_property. - Measure first. Use
tracemallocon your real data; for many programs a different data structure, such as tuples, NumPy arrays or columns in a dataframe, saves far more.
Type checkers understand slotted classes normally, so type hints need no changes.
Measuring the saving on your own classes
import tracemalloc
def mem(cls, n=1_000_000):
tracemalloc.start()
objs = [cls(None, None) for _ in range(n)]
current, _ = tracemalloc.get_traced_memory()
tracemalloc.stop()
return current / 1e6
mem(Point), mem(SlotPoint) # 96.4 MB vs 56.4 MB in our run
This is the exact helper behind our memory table. tracemalloc counts every allocation Python makes while the objects are created, so it includes the objects, their attribute storage and the list holding them. Keep a reference to the objects (here the objs list) until you read the number, or they are freed before you measure. sys.getsizeof is not a good substitute: it reports only the shallow size of one object, and in our run it returned 48 bytes for both a normal and a slotted instance, hiding the difference completely. Asking for p.__dict__ to measure it also creates the dictionary you were trying to measure, which is the same effect that slowed attribute writes in the speed test.
Run the measurement with realistic attribute values from your application, because large strings or nested objects can make the per-object overhead that slots remove a small fraction of the total.
Final thoughts
Python slots still deliver real memory savings, about 40 bytes per object and up to 41 percent in our tests, but on modern Python they do not make attribute access faster, and creating objects was slower in our run. Use them when you have many instances with fixed fields, declare them in every class of the hierarchy, add __weakref__ if needed, and avoid cached_property. For most new code, @dataclass(slots=True) gives you the benefit with the least effort.
Frequently asked questions
What does __slots__ do in Python?
It declares a fixed list of attribute names for a class. Instances store those values in a compact array instead of a per-object dictionary, which saves memory and blocks other attributes.
How much memory does __slots__ save?
In our Python 3.13 tests, about 40 bytes per object: one million small objects went from 96.4 MB to 56.4 MB. The percentage depends on what the attributes hold.
Does __slots__ make Python faster?
Not on modern Python in our tests. Attribute reads and writes took the same time, about 12 nanoseconds, and creating slotted objects was slower.
Do subclasses inherit __slots__?
They inherit the parent slots, but a subclass without its own slots declaration gets an instance dictionary again. Declare slots in every subclass, listing only the new names.
Can I use __slots__ with dataclasses?
Yes. Since Python 3.10, pass slots=True to the dataclass decorator and it generates the slots from the fields for you.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.