ZetCode

Python __slots__ Method

Last modified November 18, 2026 Python 3.15

By default every instance of a Python class carries a dictionary that holds its attributes. Declaring __slots__ replaces that dictionary with a fixed layout listing the allowed attribute names. This saves memory when a program creates many instances and prevents accidental creation of new attributes. The trade-off is reduced flexibility: slots are inherited, weak references need their own slot, and a child class must declare its own slots to keep the optimization. This article walks through each of these behaviours.

A basic __slots__ declaration

The declaration lists the permitted attribute names as a tuple. Reading and writing those names works as usual, but there is no instance dictionary and an unknown name is rejected.

basic_slots.py
class Point:
    __slots__ = ("x", "y")

    def __init__(self, x, y):
        self.x = x
        self.y = y


p = Point(3, 4)
print("values:", p.x, p.y)
print("has dictionary:", hasattr(p, "__dict__"))
try:
    p.z = 5
except AttributeError as e:
    print(type(e).__name__, e)

The two declared attributes worked, while an attempt to add z raised AttributeError. A string such as __slots__ = "name" is treated as a single name, not a sequence of characters.

$ python basic_slots.py
values: 3 4
has dictionary: False
AttributeError 'Point' object has no attribute 'z' and no __dict__ for setting new attributes

Memory savings

The saving comes from removing the per-instance dictionary. Comparing the bare size of a slotted object with a regular object plus its dictionary shows the difference; exact byte counts vary across builds, so the example asserts a relationship rather than a fixed number.

memory.py
import sys


class RegularPoint:
    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


regular = RegularPoint(3, 4)
slot = SlotPoint(3, 4)
regular_total = sys.getsizeof(regular) + sys.getsizeof(regular.__dict__)
print("regular is larger:", regular_total > sys.getsizeof(slot))
print("slot uses no dict:", not hasattr(slot, "__dict__"))

The regular object needs storage for both itself and its dictionary, while the slotted object stores the two values inline. The gap is small for two attributes but grows with the number of instances.

$ python memory.py
regular is larger: True
slot uses no dict: True

Inheritance rules

Slots are inherited: a child adds only the names it declares. If the child omits __slots__, it receives a dictionary again and loses the memory advantage.

inheritance.py
class Base:
    __slots__ = ("a",)


class Child(Base):
    __slots__ = ("b",)

    def __init__(self, a, b):
        self.a = a
        self.b = b


class ChildWithoutSlots(Base):
    pass


child = Child(1, 2)
loose = ChildWithoutSlots()
loose.extra = 9
print("inherited slots:", child.a, child.b)
print("child has dict:", hasattr(child, "__dict__"))
print("no-slots child has dict:", hasattr(loose, "__dict__"))

Child can store both a and b without a dictionary. ChildWithoutSlots accepted an arbitrary new attribute because omitting the declaration reintroduced the default dictionary.

$ python inheritance.py
inherited slots: 1 2
child has dict: False
no-slots child has dict: True

Weak references

A slotted class does not normally support weak references. Adding the special name __weakref__ to the slots restores that ability without needing a full dictionary.

slots_weakref.py
import weakref


class NoWeakRef:
    __slots__ = ("data",)

    def __init__(self, data):
        self.data = data


class WithWeakRef:
    __slots__ = ("__weakref__", "data")

    def __init__(self, data):
        self.data = data


plain = NoWeakRef(1)
try:
    weakref.ref(plain)
except TypeError as e:
    print(type(e).__name__, e)

obj = WithWeakRef(42)
reference = weakref.ref(obj)
print("value through weakref:", reference().data)

The first class raised TypeError; the second returned the stored value through the weak reference. Include __weakref__ whenever a slotted object must be tracked by weakref or a weak container.

$ python slots_weakref.py
TypeError cannot create weak reference to 'NoWeakRef' object
value through weakref: 42

Properties with slots

Properties are class attributes, so they do not need slots. The backing field does: the internal name is declared and the property provides controlled access to it.

properties.py
class Temperature:
    __slots__ = ("_celsius",)

    def __init__(self, celsius):
        self._celsius = celsius

    @property
    def celsius(self):
        return self._celsius

    @property
    def fahrenheit(self):
        return self._celsius * 9 / 5 + 32


t = Temperature(25)
print(t.celsius, t.fahrenheit)
try:
    t.celsius = 30
except AttributeError as e:
    print(type(e).__name__, e)

Reading both properties worked and the instance still had no dictionary. Assignment to the read-only property failed; a setter could be added that writes to _celsius, which is a declared slot.

$ python properties.py
25 77.0
AttributeError property 'celsius' of 'Temperature' object has no setter

An optional dictionary escape hatch

Including __dict__ in the slots restores dynamic attributes while still keeping the named slots. This is useful when a library needs to attach metadata to an otherwise fixed object.

dynamic.py
class Flexible:
    __slots__ = ("x", "__dict__")

    def __init__(self, x):
        self.x = x


f = Flexible(1)
f.extra = "added later"
print("declared:", f.x)
print("dynamic:", f.extra)
print("has dict:", hasattr(f, "__dict__"))

Named attributes remain efficient, but the presence of the dictionary means the object no longer enjoys the full memory saving. This is a deliberate middle ground, not a free optimization.

$ python dynamic.py
declared: 1
dynamic: added later
has dict: True

Name collisions

A slot cannot share its name with a class variable. Python detects the clash while the class is being defined and raises ValueError, because the class attribute would shadow the slot descriptor.

collision.py
try:
    class Colliding:
        __slots__ = ("value",)
        value = 10
except ValueError as e:
    print(type(e).__name__, e)


class Single:
    __slots__ = "name"


s = Single()
s.name = "Ann"
print("single string:", s.name)

The collision was rejected at class-creation time. The second class shows the related gotcha that a bare string declares one slot named name, not one slot per character — writing a one-element tuple with a trailing comma is clearer.

$ python collision.py
ValueError 'value' in __slots__ conflicts with class variable
single string: Ann

Best practices

A few rules keep __slots__ predictable:

Source

__slots__ - Python documentation

Descriptor HowTo Guide - Python documentation

weakref - Python documentation

In this article we have used the __slots__ declaration. We have covered the basic fixed layout, memory savings, inheritance, weak references, properties, a dictionary escape hatch and name collisions. For related topics, see Python __dict__, Python __sizeof__ method, and Python properties.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.