Python __slots__: Leaner Objects, Fixed Attributes
What you’ll learn
Section titled “What you’ll learn”- What
__slots__changes about an instance, and how it is implemented with descriptors. - How to measure the memory difference honestly, and why
sys.getsizeof()can mislead. - The inheritance, weak reference and multiple inheritance rules that trip people up.
- How
@dataclass(slots=True)generates slots for you. - When slots pay off and when they only add friction.
Summary
Section titled “Summary”__slots__ is a class attribute that lists the instance attributes a class allows. Python then reserves a fixed storage location for each name and, unless told otherwise, gives instances no __dict__ and no __weakref__. The result is smaller instances, slightly faster attribute access and an AttributeError for misspelled attribute names. The feature dates back to Python 2.2 and is current in Python 3.14; @dataclass(slots=True) (Python 3.10) is the easiest way to use it today.
The problem it solves
Section titled “The problem it solves”An ordinary instance keeps its attributes in a per-instance namespace dictionary. That is flexible, but it costs memory for every object and it accepts any attribute name, including typos. In the OrdersPortal app, an OrderLine with a misspelled quantity silently grows a fourth attribute while qty keeps its old value.
The samples on this page are plain scripts: save each as a .py file and run it with python3 file.py. They were run on CPython 3.14.6 (64-bit Linux) and the output shown is from that run.
class OrderLineV1: def __init__(self, sku, qty, unit_price): self.sku = sku self.qty = qty self.unit_price = unit_price
line = OrderLineV1("SKU-1", 2, 9.99)line.quantity = 3 # typo: silently creates a new attributeprint(line.qty, line.__dict__)
class OrderLine: __slots__ = ("sku", "qty", "unit_price")
def __init__(self, sku, qty, unit_price): self.sku = sku self.qty = qty self.unit_price = unit_price
line = OrderLine("SKU-1", 2, 9.99)try: line.quantity = 3except AttributeError as exc: print("AttributeError:", exc)print(hasattr(line, "__dict__"), OrderLine.qty)Output:
2 {'sku': 'SKU-1', 'qty': 2, 'unit_price': 9.99, 'quantity': 3}AttributeError: 'OrderLine' object has no attribute 'quantity' and no __dict__ for setting new attributesFalse <member 'qty' of 'OrderLine' objects>With __slots__, the typo fails immediately, the instance has no __dict__, and OrderLine.qty turns out to be a member descriptor: the class-level object that reads and writes the slot.
How it works
Section titled “How it works”__slots__ can be a string, a tuple, a list or any non-string iterable of names. When the class is created, type.__new__ reserves one pointer-sized field per name in the instance layout and adds a member descriptor for each name to the class. Because data descriptors on the class take precedence in attribute lookup, line.qty goes straight to the reserved field.
Memory: measure, do not guess
Section titled “Memory: measure, do not guess”The numbers below are CPython implementation details. They depend on the version, the build and the platform, and they changed in Python 3.11, which made ordinary instances smaller by creating their namespace dictionaries lazily.
import sysimport tracemalloc
class PlainLine: def __init__(self, sku, qty, unit_price): self.sku, self.qty, self.unit_price = sku, qty, unit_price
class SlottedLine: __slots__ = ("sku", "qty", "unit_price")
def __init__(self, sku, qty, unit_price): self.sku, self.qty, self.unit_price = sku, qty, unit_price
def measure(cls, n=100_000): tracemalloc.start() lines = [cls("SKU-1", 1, 9.99) for _ in range(n)] current, _ = tracemalloc.get_traced_memory() tracemalloc.stop() return current / n
print(sys.version.split()[0])print("getsizeof plain: ", sys.getsizeof(PlainLine("a", 1, 1.0)))print("getsizeof slotted:", sys.getsizeof(SlottedLine("a", 1, 1.0)))print(f"traced bytes/instance plain: {measure(PlainLine):.0f}")print(f"traced bytes/instance slotted: {measure(SlottedLine):.0f}")p = PlainLine("a", 1, 1.0)p.__dict__ # materialize the dictprint("getsizeof plain after __dict__ access:", sys.getsizeof(p), "+ dict", sys.getsizeof(p.__dict__))Output (CPython 3.14.6, 64-bit Linux):
3.14.6getsizeof plain: 48getsizeof slotted: 56traced bytes/instance plain: 104traced bytes/instance slotted: 64getsizeof plain after __dict__ access: 48 + dict 96Three lessons hide in that output:
sys.getsizeof()is not the full story. It reports 48 bytes for the plain instance, buttracemalloc, which records actual allocations, shows about 96 bytes per plain instance versus 56 for the slotted one (subtract the 8-byte list slot from each traced figure).- Touching
__dict__costs more. Readingp.__dict__makes CPython create a real dictionary, which adds another 96 bytes to that instance. - The saving is per object, not per attribute value. The strings, numbers and decimals your attributes point to cost the same either way.
Attribute reads are also somewhat faster with slots. The descriptor how-to guide in the Python docs measured 35% faster reads on Python 3.10; treat that as indicative and benchmark your own code if speed is the reason.
The rules
Section titled “The rules”Run against Python 3.14, each rule below produces the error shown:
import weakref
class OrderLine: __slots__ = ("sku", "qty")
# 1. A subclass without __slots__ gets a __dict__ again.class DiscountedLine(OrderLine): pass
d = DiscountedLine()d.anything = 1print("subclass has __dict__:", hasattr(d, "__dict__"))
# 2. A subclass that declares only its *new* names stays dict-free.class GiftLine(OrderLine): __slots__ = ("message",)
print("GiftLine slots:", GiftLine.__slots__, hasattr(GiftLine(), "__dict__"))
# 3. A class attribute cannot double as a default for a slot.try: class Bad: __slots__ = ("qty",) qty = 1except ValueError as exc: print("ValueError:", exc)
# 4. No weak references unless you ask for them.try: weakref.ref(OrderLine())except TypeError as exc: print("TypeError:", exc)
class CachedLine: __slots__ = ("sku", "__weakref__")
print("weakref ok:", weakref.ref(CachedLine()) is not None)
# 5. Two bases with non-empty slot layouts cannot be combined.class Priced: __slots__ = ("price",)
try: class PricedLine(OrderLine, Priced): passexcept TypeError as exc: print("TypeError:", exc)
# 6. Unset slots raise AttributeError on read.try: OrderLine().skuexcept AttributeError as exc: print("AttributeError:", exc)
# 7. A dict gives per-slot docstrings.class Shipment: __slots__ = {"carrier": "Carrier code, e.g. 'DHL'", "tracking": "Tracking number"}
import inspectprint(inspect.getdoc(Shipment.carrier))Output:
subclass has __dict__: TrueGiftLine slots: ('message',) FalseValueError: 'qty' in __slots__ conflicts with class variableTypeError: cannot create weak reference to 'OrderLine' objectweakref ok: TrueTypeError: multiple bases have instance lay-out conflictAttributeError: 'OrderLine' object has no attribute 'sku'Carrier code, e.g. 'DHL'- Every class in the hierarchy must cooperate. A subclass without
__slots__gets a__dict__and__weakref__again. A subclass that wants to stay dict-free declares only its new names; parent slots are inherited. - No class-attribute defaults. A class attribute with the same name would replace the slot’s descriptor, so Python raises
ValueError. Set defaults in__init__, or let a dataclass generate them. - No weak references by default. Add
"__weakref__"to__slots__if caches or observers useweakref. Add"__dict__"only if you really need dynamic attributes, which gives back most of the memory saving. - One slotted layout per class. Multiple inheritance works only if at most one base has non-empty slots; mixins should declare
__slots__ = (). - Unset slots are missing, not
None. Reading a slot before assigning it raisesAttributeError. - A dict documents the slots. With
__slots__ = {"carrier": "..."}, the values become docstrings thathelp()andinspect.getdoc()show.
The language reference adds two more: a non-empty __slots__ is not allowed on subclasses of variable-length built-ins such as int, bytes and tuple, and assigning to obj.__class__ only works between classes with the same slots. Slotted instances pickle normally with the default protocol.
Realistic example
Section titled “Realistic example”OrdersPortal’s nightly reconciliation loads every order line from a CSV export, 200,000 rows here, into immutable records. @dataclass(frozen=True, slots=True) writes __slots__ from the field list, so the class stays declarative. The script measures the same load with and without slots.
import csvimport ioimport tracemallocfrom dataclasses import dataclassfrom decimal import Decimal
@dataclass(frozen=True)class PlainOrderLine: order_id: str sku: str qty: int unit_price: Decimal
@dataclass(frozen=True, slots=True)class OrderLine: order_id: str sku: str qty: int unit_price: Decimal
@property def subtotal(self) -> Decimal: return self.qty * self.unit_price
# A synthetic nightly export: 200,000 order lines.EXPORT = "order_id,sku,qty,unit_price\n" + "".join( f"ORD-{i // 3:05d},SKU-{i % 50},{i % 4 + 1},{(i % 7) + 0.99:.2f}\n" for i in range(200_000))
def load(cls): tracemalloc.start() lines = [ cls(r["order_id"], r["sku"], int(r["qty"]), Decimal(r["unit_price"])) for r in csv.DictReader(io.StringIO(EXPORT)) ] current, _ = tracemalloc.get_traced_memory() tracemalloc.stop() return lines, current / 1e6
plain, plain_mb = load(PlainOrderLine)lines, slotted_mb = load(OrderLine)
print(lines[0])print("revenue:", sum(line.subtotal for line in lines))print("slots:", OrderLine.__slots__, "| has __dict__:", hasattr(lines[0], "__dict__"))print(f"plain dataclass: {plain_mb:.1f} MB")print(f"slotted dataclass: {slotted_mb:.1f} MB")try: lines[0].qty = 5except AttributeError as exc: print(type(exc).__name__ + ":", exc)Output (memory figures are CPython 3.14.6 implementation details):
OrderLine(order_id='ORD-00000', sku='SKU-0', qty=1, unit_price=Decimal('0.99'))revenue: 1994980.00slots: ('order_id', 'sku', 'qty', 'unit_price') | has __dict__: Falseplain dataclass: 65.8 MBslotted dataclass: 57.8 MBFrozenInstanceError: cannot assign to field 'qty'The slotted version uses about 8 MB less, roughly 12% here, because most of the memory goes to the strings and Decimal objects each line points to. That is typical: slots trim the per-object overhead, so the benefit is largest for many small objects whose attribute values are shared or small, such as integers, flags and interned codes. If memory is the real constraint, also look at the data itself (deduplicating SKU strings, storing cents as int, or a columnar format) before blaming the object layout.
Note that slots=True returns a new class: the decorator cannot add slots to an existing class, so it builds a replacement. The dataclass documentation warns that passing keyword arguments to a base class’s __init_subclass__ fails with slots=True.
Common mistakes
Section titled “Common mistakes”- Adding slots to one class in a hierarchy. If any class in the MRO lacks
__slots__(other thanobject), instances still get a__dict__and the saving disappears. - Repeating parent slot names in the child. The language reference says the parent’s slot becomes inaccessible and the program’s meaning is undefined. List only new names.
- Using
functools.cached_property. It stores its result in the instance__dict__, so on a slotted class it raisesTypeError: No '__dict__' attribute ... to cache. Use a normal slot plus a property, orfunctools.lru_cacheon a method with care. - Forgetting
__weakref__. Libraries that keep weak references to your objects fail withcannot create weak reference. - Using
__slots__to discover fields. Dataclasses may omit inherited fields from the generated__slots__; usedataclasses.fields(). - Expecting a big win from a few objects. A configuration object or a service instance gains nothing measurable.
When to use it and when not to
Section titled “When to use it and when not to”| Situation | __slots__? |
Why |
|---|---|---|
| Hundreds of thousands of small records (order lines, events, ticks) | Yes | Per-instance overhead dominates |
| Value objects where typos should fail | Yes, often with @dataclass(slots=True, frozen=True) |
Fixed attribute set is a feature |
Classes used with cached_property, monkey-patching or dynamic attributes |
No | They need __dict__ |
| Mixins and abstract bases | __slots__ = () |
Lets slotted subclasses stay dict-free |
| A handful of long-lived service objects | No | No measurable benefit |
| Records that only travel between functions | Consider NamedTuple |
Already compact and immutable |
Compatibility
Section titled “Compatibility”__slots__ exists in every Python 3 release. @dataclass(slots=True) arrived in Python 3.10 and weakref_slot=True in 3.11; since 3.11 dataclasses also skip field names already slotted in a base class. Python 3.11 made ordinary instances lazily create their namespace dictionaries, which narrowed the memory gap that older articles report. All size numbers are CPython-specific; PyPy and other implementations lay out objects differently.
Interview questions
Section titled “Interview questions”1. What exactly does __slots__ remove, and how are slot attributes accessed?
It removes the per-instance __dict__ and __weakref__ (unless listed or provided by a base). Each name becomes a member descriptor on the class that reads and writes a fixed field in the instance.
2. Why does class Bad: __slots__ = ("qty",); qty = 1 fail?
The slot is implemented as a class-level descriptor named qty; a class attribute of the same name would overwrite it, so type.__new__ raises ValueError. Defaults belong in __init__ or a dataclass field default.
3. Two mixins each define __slots__ = ("created_at",) and __slots__ = ("updated_at",). What happens when a class inherits from both?
TypeError: multiple bases have instance lay-out conflict. Only one base may contribute non-empty slots. Give mixins __slots__ = () and declare the storage in the concrete class, or move the fields into one base.
4. Senior scenario: an OrdersPortal worker holding 5 million order events in memory is close to its container limit. A teammate proposes adding __slots__ everywhere. How do you approach it?
Measure first with tracemalloc snapshots grouped by line to see whether instance overhead or attribute values dominate. If per-object overhead is significant, convert the hot event classes to @dataclass(slots=True, frozen=True), make shared bases and mixins use empty slots, add __weakref__ where caches need it, and check for cached_property or dynamic attributes that would break. If strings and decimals dominate, slots will not fix it; intern or deduplicate repeated values, store money as integer cents, or process the stream in batches instead of holding it all. Verify with the same measurement in CI so a later subclass without slots does not silently undo the work.
Key takeaways
Section titled “Key takeaways”__slots__fixes an instance’s attribute names and drops its__dict__and__weakref__.- Savings are per object and implementation-specific; measure with
tracemalloc, notsys.getsizeof()alone. - Every class in the hierarchy needs
__slots__; mixins use__slots__ = (). - No class-attribute defaults, no
cached_property, and add__weakref__explicitly if needed. @dataclass(slots=True)(Python 3.10+) is the simplest way to apply slots to record classes.
Related pages
Section titled “Related pages”- dataclasses:
slots=True,frozen=Trueand generated methods. - Descriptors: the member descriptors that implement slots.
- Memory management: reference counting, garbage collection and measuring memory.
- Weak references: why
__weakref__matters. - namedtuple: another compact, immutable record type.
- Magic methods: special methods you can still define on slotted classes.