Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Dataclass Slots vs Regular Dataclass

Compare Python dataclass with and without slots: memory usage, attribute access, inheritance constraints, when each approach is a better fit, and practical tradeoffs.

~6 min readPython
#dataclasses#slots#python#memory
A visual comparison of a Python dataclass instance with a dictionary versus a slots-based instance with fixed attribute slots, illustrating memory and access differences.

Regular Python dataclasses store instance fields in a per-instance __dict__, which makes attribute access flexible and allows dynamic assignment, but adds memory overhead. Adding slots=True to the @dataclass decorator replaces that dictionary with fixed slot descriptors. The tradeoff is central to choosing between a regular dataclass and a slots dataclass: slots reduce memory and can speed up attribute access, but they also remove the ability to add attributes dynamically and introduce constraints around inheritance and weak references.

This article explains the practical differences between the two forms and helps you decide which one fits your use case.

The Problem: Instance Dictionaries and Attribute Overhead

A regular dataclass instance stores its fields in an instance dictionary. Consider this simple definition:

python
from dataclasses import dataclass @dataclass class Point: x: float y: float

Each Point object has a __dict__ attribute that holds {'x': ..., 'y': ...}. This dictionary is flexible: you can add new attributes to an instance at runtime, and attribute access goes through the normal dictionary lookup path. The cost is that every instance carries a dict object, which consumes memory even for a small number of fields. For a large number of instances, this overhead becomes significant.

How Slots Change the Instance Layout

Setting slots=True on the dataclass decorator tells Python to use __slots__ under the hood. The class gets a fixed set of attribute descriptors, and instances no longer have a __dict__. The same point class with slots:

python
@dataclass(slots=True) class PointSlots: x: float y: float

Now PointSlots instances store x and y in direct slots, not in a dictionary. The memory footprint per instance is smaller because there is no dict object. Attribute access is also faster because it uses descriptor lookup rather than a hash table lookup.

Memory and Attribute Access: What Actually Changes

The most immediately visible difference is the absence of __dict__. You can verify this:

python
p = Point(1.0, 2.0) print(p.__dict__) # {'x': 1.0, 'y': 2.0} ps = PointSlots(1.0, 2.0) print(ps.__dict__) # AttributeError: 'PointSlots' object has no attribute '__dict__'

Because there is no __dict__, you cannot add new attributes to a slots instance:

python
ps.z = 3.0 # AttributeError: 'PointSlots' object has no attribute 'z'

This restriction is the core tradeoff. If you rely on dynamic attribute assignment, slots will break that pattern. For data-transfer objects or value objects where the field set is fixed, the restriction is usually acceptable.

Memory savings come from not allocating a dict for each instance. The exact amount depends on the number of fields and the Python version, but the mechanism is clear: a dict has a hash table structure that is much larger than a few pointers. For millions of instances, the difference can be substantial.

Inheritance and Weak References: Hidden Constraints

Slots introduce several constraints that are not obvious from a simple example. First, if a dataclass with slots is used as a base class, subclasses must also define slots, or they will get a __dict__ again. The base class slots do not automatically propagate to subclasses. For example:

python
@dataclass(slots=True) class Base: a: int @dataclass class Child(Base): b: int

Child instances will have a __dict__ because the subclass does not declare __slots__. To keep the memory benefit, you must set slots=True on every class in the inheritance chain.

Second, instances of a slots class cannot be made weak-referenceable unless you explicitly add __weakref__ to the slots. This matters if you use weak references for caching or in frameworks like weakref.WeakSet. Regular dataclasses support weak references by default because a normal class gets a __weakref__ descriptor when it does not define __slots__.

Performance Considerations: Mechanism, Not Magic

Slots improve memory and attribute access speed, but the gains are not uniform across all operations. The main reason for the speed improvement is that attribute lookup no longer involves hashing the attribute name and probing a dict. Instead, it uses a direct descriptor lookup. However, the dataclass-generated __init__ and __repr__ methods still perform normal Python operations, so the difference is most visible when you access attributes frequently or create a large number of instances.

There is also a subtle initialization cost. With slots, the generated __init__ assigns to slot descriptors directly. With a regular dataclass, it assigns to dict entries. The difference is usually small, but for object creation in a tight loop, slots can be slightly faster because it avoids dict insertion overhead.

Do not expect a dramatic speedup in typical application code. The primary benefit is memory reduction. If your program holds many instances in memory, slots can reduce the memory footprint noticeably. If you only create a few objects, the difference is negligible.

When to Use Slots vs Regular Dataclass

The decision depends on how you use the class.

Use slots=True when:

  • You have a fixed set of fields that does not change at runtime.
  • You create many instances and memory usage is a concern.
  • You want to prevent accidental attribute typos from silently adding new attributes.
  • You are building value objects, DTOs, or configuration records.

Use a regular dataclass when:

  • You need to add attributes dynamically, for example to attach metadata to an instance.
  • You rely on weak references without adding an explicit __weakref__ slot.
  • You have an inheritance hierarchy where not all subclasses are under your control.
  • You prefer the flexibility of __dict__ for introspection or serialization tricks.

There is no universal best choice. The regular dataclass is the safer default because it imposes no restrictions. Slots are an optimization that you opt into when the constraints are acceptable.

Edge Cases: Frozen, Order, and Field Defaults

slots=True composes with other dataclass features. A frozen dataclass with slots works as expected: frozen=True prevents assignment to fields, and slots prevent adding new attributes, so the instance's attribute set cannot change. Ordering and repr generation are unaffected.

One subtle issue appears with field defaults that are mutable. If you use a mutable default like field(default_factory=list), the dataclass machinery stores the factory in the class, and each instance gets its own list. This works with slots because the list is stored in a slot. The same rules apply as with regular dataclasses.

Another edge case is using __slots__ manually alongside @dataclass(slots=True). You should not define __slots__ yourself when using slots=True; the decorator does it for you. If you do, you risk conflicts and unexpected behavior. Let the dataclass decorator manage the slot definitions.

Compatibility with Python Versions

slots=True was added in Python 3.10. If you are using an older Python version, you cannot use this parameter directly. You can still achieve a similar effect by manually defining __slots__ in the class body, but then you lose some of the automatic dataclass behavior and must handle field descriptors carefully. For new code, target Python 3.10 or later if you want the clean slots=True syntax.

When you upgrade an existing codebase to use slots, run your test suite to catch any places that rely on __dict__ or dynamic attribute assignment. The error messages are usually clear, but the change can break code that uses vars(instance), instance.__dict__, or libraries that introspect object attributes.

Making the Choice in Practice

Start with a regular dataclass unless you have a concrete reason to switch. If you later observe high memory usage from many instances, profile your application to confirm that dataclass instances are a significant contributor. Then switch to slots=True and re-run the same profile. The change is minimal—just add the parameter—and the behavioral differences are limited to the restrictions described above.

For library authors, consider whether your public API exposes dataclass instances to consumers. If you switch to slots, consumers who relied on adding attributes or using weak references will break. In that case, document the change or keep the regular dataclass for backward compatibility.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.