Sub topic 4
How slots work: member descriptors on the class
This chapter explains the mechanism behind __slots__. It assumes you know the descriptor protocol at a basic level (__get__, __set__, __delete__) and the difference between instance and class attributes. You should also have read the earlier chapters on __dict__ storage and on declaring __slots__.
Slots are ordinary class attributes
When you write __slots__ = ("x", "y"), Python does not put anything special on each instance. During class creation, type.__new__ does three things:
- It reserves a fixed amount of space in every instance, one pointer-sized cell per slot.
- It skips creating the per-instance
__dict__. - It adds one object to the class namespace for each slot name. This object is a
member_descriptor.
A member descriptor knows which class it belongs to and where its cell sits inside the instance. Reading p.x calls the descriptor, which fetches the value from that cell.
class Point:
__slots__ = ("x", "y")
descriptor = Point.__dict__["x"]
print(type(descriptor).__name__) # member_descriptor
print(descriptor) # <member 'x' of 'Point' objects>
print(descriptor.__name__) # x
print(descriptor.__objclass__) # <class '__main__.Point'>
print(Point.x is descriptor) # TrueThe last line shows a general descriptor rule. When you read a descriptor through the class (Point.x), __get__ receives None as the instance and returns the descriptor itself. That is why Point.x prints <member 'x' of 'Point' objects> instead of a value.
Calling the descriptor by hand
The descriptor is a real object with the standard three methods. You can call them directly, which shows what the p.x syntax does behind the scenes.
class Point:
__slots__ = ("x", "y")
descriptor = Point.__dict__["x"]
p = Point()
descriptor.__set__(p, 10)
print(p.x) # 10
print(descriptor.__get__(p, Point)) # 10
descriptor.__delete__(p)
try:
p.x
except AttributeError:
print("x is unset again")Three behaviors follow from this:
- Assignment (
p.x = 10) calls__set__, which stores the object in the cell. - Deletion (
del p.x) calls__delete__, which empties the cell. The slot is then in the same state as a slot that was never assigned. - Reading an empty cell makes
__get__raiseAttributeError. There is no default value and noNoneplaceholder. An empty cell is not the same as a cell holdingNone.
The descriptor also checks the type of the instance it receives. It only works on instances of the class that defined it, or of its subclasses.
class Point:
__slots__ = ("x", "y")
try:
Point.__dict__["x"].__get__("text")
except TypeError:
print("TypeError: descriptor does not apply to str objects")Ordinary code does not hit this check, because p.x always passes p to the descriptor. You see it when you borrow a descriptor and apply it to the wrong object.
Why the descriptor wins over `__dict__`
Attribute lookup on an instance follows a fixed order. The order depends on the kind of object found on the class:
| Found on the class | Behavior |
|---|---|
| Data descriptor (defines `__set__` or `__delete__`) | Its `__get__` is called. The instance `__dict__` is never consulted. |
| Nothing | The instance `__dict__` is checked, if one exists. |
| Non-data descriptor or plain class attribute | Used only if the instance `__dict__` has no entry of that name. |
A member_descriptor is a data descriptor, so it takes priority over any instance dictionary. You can see this by giving a slotted class a __dict__ slot as well. Chapter 8 covers that option properly. Here it only serves as an experiment.
class Hybrid:
__slots__ = ("x", "__dict__")
h = Hybrid()
h.__dict__["x"] = 99
print(h.__dict__) # {'x': 99}
try:
h.x
except AttributeError:
print("the slot wins, and it is empty")
h.x = 1 # goes through the descriptor, not the dict
print(h.x, h.__dict__) # 1 {'x': 99}The dictionary holds 'x': 99 the whole time. The value is invisible through normal attribute access, because the class-level data descriptor intercepts both reads and writes of x. The same rule applies to property, which is also a data descriptor.
The following diagram shows the read path for p.x on an instance whose class has a slot named x.
Where the values actually live
The cells are part of the instance's C-level memory block. They are not Python objects you can reach by name. The only way to read or write a cell is through the descriptor. That is why a slotted instance has no __dict__ to inspect, and why vars(p) raises TypeError for a class that has only slots.
Two practical consequences follow:
- Because each slot name has a fixed offset, there is no hash lookup in a per-instance dictionary. The class-level lookup for the descriptor still happens, and CPython caches it. Do not expect a large speed difference from this, and measure before claiming one.
- Because the layout is decided when the class is created, you cannot add a slot later. Assigning
Point.z = ...after creation adds an ordinary class attribute, not a cell.
Slot names and name mangling
Slot names go through the same private-name mangling as other class-body names. A slot named with two leading underscores is stored under the mangled name:
class Account:
__slots__ = ("__balance",)
print([name for name in vars(Account) if "balance" in name])
# ['_Account__balance']Code inside Account can still write self.__balance, because the compiler mangles that reference the same way. Code outside the class has to use _Account__balance.
Two further details about the __slots__ value itself:
- A single string is treated as one slot name, so
__slots__ = "x"creates a slot calledx. It does not create slots from the characters. - Any iterable of strings works. A dictionary also works (Python 3.8 and later), and its values are used as docstrings for the descriptors. The class does not keep the original object. It keeps whatever you assigned, so a one-shot iterator would be consumed during class creation, and a later read of
__slots__would show an exhausted iterator.
Why a slot and a class variable cannot share a name
Each slot name needs its own entry in the class namespace, because that entry holds the descriptor. If the class body already defines that name, for example x = 0, the two would collide. type.__new__ detects this and raises ValueError instead of silently replacing one with the other. The next chapter covers the practical fixes, including how to provide defaults. The mechanism to remember is that the conflict comes from two objects wanting the same class-dict key.
The same reasoning explains the usual way to combine slots with validation. Store the data in a slot with a different name, and expose it through a property:
class Temperature:
__slots__ = ("_celsius",)
def __init__(self, celsius):
self.celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("below absolute zero")
self._celsius = value
t = Temperature(20)
print(t.celsius) # 20The class dictionary now holds two data descriptors: a property named celsius and a member_descriptor named _celsius. They have different names, so they do not conflict.
Listing the values that are set
Since there is no __dict__, you need your own code to see an instance's state. The helper below walks the class hierarchy and collects every member descriptor that has a value. It relies on types.MemberDescriptorType.
from types import MemberDescriptorType
def slot_values(obj):
values = {}
for klass in type(obj).__mro__:
for name, attr in vars(klass).items():
if type(attr) is MemberDescriptorType:
try:
values[name] = getattr(obj, name)
except AttributeError:
pass # slot declared but not set
return values
class Base:
__slots__ = ("a",)
class Child(Base):
__slots__ = ("b", "c")
child = Child()
child.a = 1
child.b = 2
print(slot_values(child)) # {'b': 2, 'a': 1}The helper skips c, which was never assigned. It also ignores the __dict__ and __weakref__ entries. Those are a different descriptor type (getset_descriptor), so the type(attr) is MemberDescriptorType test excludes them. Because it uses vars(klass), it reports mangled names such as _Account__balance exactly as stored.
Summary of the mechanism
| Aspect | Instance `__dict__` | Slot (member descriptor) |
|---|---|---|
| Where the value lives | In a per-instance dictionary | In a fixed cell inside the instance |
| What the class holds | Nothing for that name | A `member_descriptor` under the slot name |
| Read of an unset name | `AttributeError` (key missing) | `AttributeError` (cell empty) |
| `del obj.x` | Removes the key | Empties the cell |
| `Class.x` | `AttributeError`, unless a class attribute exists | The descriptor object |
| Precedence | Lower than class data descriptors | It is a data descriptor, so it wins |
Exercise
Given class P: __slots__ = ("x",), what do P.x, p.x right after p = P(), and p.x after p.x = None; del p.x produce?
Show answer
P.x returns the member descriptor itself, printed as <member 'x' of 'P' objects>. The read of p.x on a fresh instance raises AttributeError, because the cell is empty. After p.x = None, the cell holds None. The del p.x then calls the descriptor's __delete__, which empties the cell, so the final read raises AttributeError again. An empty cell and a cell holding None are different states.
Exercise
A class declares __slots__ = ("x", "__dict__"), and you run h = Hybrid(); h.__dict__["x"] = 5; print(h.x). What happens, and why?
Show answer
It raises AttributeError. The class holds a member_descriptor named x, which is a data descriptor, so attribute lookup calls it before looking at the instance dictionary. The slot cell is empty, so the descriptor raises AttributeError. Lookup does not fall back to the dictionary entry, which stays unreachable through h.x until the slot is assigned.