Sub topic 8
Weak references and opting back into __dict__
This chapter assumes you know how __slots__ removes the instance __dict__, how slot descriptors work, and how subclasses inherit slots. It covers two special names you can list in __slots__: __weakref__ and __dict__.
Why a slotted class has no weak references
A weak reference points to an object without keeping it alive. The weakref module uses it for caches, observer lists, and registries that should not prevent garbage collection.
A regular instance gets a hidden slot that holds its weak references. When you declare __slots__, CPython leaves that slot out, because it costs one pointer per instance. As a result, weakref.ref fails on a slotted instance:
import weakref
class Node:
__slots__ = ("value",)
def __init__(self, value):
self.value = value
n = Node(5)
try:
weakref.ref(n)
except TypeError as exc:
print("TypeError:", exc)The error reads cannot create weak reference to 'Node' object.
Adding __weakref__ as a slot
To restore weak-reference support, list "__weakref__" among the slot names. This reserves the per-instance pointer that weakref needs.
import weakref
class Node:
__slots__ = ("value", "__weakref__")
def __init__(self, value):
self.value = value
n = Node(5)
ref = weakref.ref(n)
print(ref() is n)
del n
print(ref())The first print shows True. After del n removes the only strong reference, CPython frees the object and the second print shows None.
You pay for one extra pointer per instance, and you keep the rest of the savings. Add __weakref__ only to classes that you actually need to reference weakly.
Adding __dict__ as a slot
You can also list "__dict__" in __slots__. The instances then get a normal dictionary for names that are not declared, while the declared names still use fast slots.
class Record:
__slots__ = ("id", "__dict__")
def __init__(self, id):
self.id = id
r = Record(1)
r.note = "extra"
print(r.id, r.note)
print(r.__dict__)The dictionary holds only note. The name id lives in its slot, so r.__dict__ prints {'note': 'extra'}.
This is a compromise. You keep a descriptor-backed slot for the hot attributes, but each instance also carries a dictionary, so you lose most of the memory benefit. It is mainly useful when you want declared fields to be fast and also want to allow ad hoc attributes.
Which names a class needs
The table shows what each choice gives you.
| `__slots__` contains | Weak references | New attributes |
|---|---|---|
| Only field names | No | No |
| Field names and `__weakref__` | Yes | No |
| Field names and `__dict__` | Yes, since 3.x classes with `__dict__` also get weakref support only if `__weakref__` is present | Yes |
| Field names, `__dict__`, and `__weakref__` | Yes | Yes |
Do not assume that adding __dict__ also adds weak-reference support. They are separate slots, and you should list both if you need both.
Interaction with inheritance
Both special slots can be declared only once along an inheritance chain. If a base class already provides __weakref__, a subclass that lists it again raises TypeError. A subclass that omits it still inherits the support.
class Base:
__slots__ = ("a", "__weakref__")
class Child(Base):
__slots__ = ("b",)
import weakref
c = Child()
print(weakref.ref(c)() is c)This prints True. Child has no __dict__ and gets weak-reference support from Base. If you subclass a regular class that already has a __dict__ and a weakref slot, you gain nothing by adding them again.
The diagram summarizes the decision.
Exercise
A class declares __slots__ = ("x",). You want to store its instances as keys in a weakref.WeakKeyDictionary, but you do not want instances to accept arbitrary new attributes. What change do you make, and why does it work?
Show answer
Change it to __slots__ = ("x", "__weakref__"). A WeakKeyDictionary creates weak references to its keys, which needs the per-instance weakref pointer that __weakref__ reserves. Leaving out __dict__ means new attributes are still rejected.
Exercise
A base class declares __slots__ = ("a",). A subclass declares __slots__ = ("b", "__dict__"). Does the subclass have a __dict__, and does the base?
Show answer
The subclass has a __dict__ because it lists it. The base does not, so Base().__dict__ raises AttributeError. Only subclass instances carry the dictionary.