Sub topic 8
Weak References and Opting Back into __dict__
This chapter assumes you can define slotted classes and know what __slots__ removes from an instance. You should also know that a regular instance stores attributes in __dict__. Here you will see two things a slotted class gives up without saying so: weak references and the ability to add arbitrary attributes. You will also learn how to ask for each back by naming it in __slots__.
Why slots take away weak references
A weak reference points to an object without keeping it alive. When the last strong reference disappears, the object is freed and the weak reference starts returning None. Caches, observer lists, and parent links in trees use this to avoid memory leaks.
For a weak reference to work, CPython needs a place on the object to record which weak references point to it. In a regular class, that place is a hidden slot named __weakref__, which Python adds automatically along with __dict__. When you declare __slots__, Python adds only the slots you list. No __weakref__ slot is created, so the object has nowhere to record its weak references.
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 output is TypeError: cannot create weak reference to 'Node' object. The error does not mention slots, so it can be confusing the first time you meet it. A common trigger is putting slotted objects into a weakref.WeakValueDictionary, weakref.WeakSet, or weakref.finalize. Each of these creates weak references internally.
Adding __weakref__ to the slots
You can opt back in by listing the name "__weakref__" in __slots__.
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)This prints True. The __weakref__ entry is not an ordinary attribute you assign to. It is a reserved name that tells the class builder to reserve one pointer-sized field for the weak-reference bookkeeping. You never read or write it yourself. The weakref module does that.
The cost is one extra pointer per instance, typically 8 bytes on a 64-bit build. That is small next to a per-instance __dict__, and you pay it only for classes that need weak references.
Here is a typical use, a cache that does not keep its values alive:
import weakref
class Node:
__slots__ = ("value", "__weakref__")
def __init__(self, value):
self.value = value
cache = weakref.WeakValueDictionary()
n = Node(5)
cache["a"] = n
print(len(cache))
del n
print(len(cache))On CPython this prints 1 and then 0. After del n the reference count reaches zero, the node is freed immediately, and the cache entry disappears. Other implementations, such as PyPy, free objects later, so the second number may differ there. Code that depends on the exact moment of removal is relying on a CPython detail.
Which built-in types cannot be weakly referenced
Adding __weakref__ works only for classes you define. Some built-in types, such as int, str, tuple, and dict, do not support weak references at all. weakref.ref(1) raises TypeError. A plain subclass of dict or set does support them, because a subclass without __slots__ gets __weakref__ automatically.
Opting back into __dict__
The same trick works for __dict__. If you list "__dict__" in __slots__, instances get a dictionary for attributes that are not named in the slots.
class Flexible:
__slots__ = ("x", "y", "__dict__")
def __init__(self, x, y):
self.x = x
self.y = y
f = Flexible(1, 2)
f.z = 3
print(f.x, f.y)
print(f.__dict__)
print(hasattr(f, "__dict__"))The output is:
1 2
{'z': 3}
TrueNotice that x and y are not in f.__dict__. Attribute lookup finds a slot descriptor on the class first, so those two values live in the fixed slots. Only the extra attribute z goes into the dictionary. The result is a hybrid: the core fields are stored compactly and extra attributes are still allowed.
This hybrid costs a pointer to the dictionary in every instance. CPython typically allocates the dictionary itself only when the first extra attribute is stored. You should not count on that detail when estimating memory. Measure it, as described in the earlier chapter on measuring memory differences.
Why you might want this
There are three common reasons:
- Third-party code or tests attach attributes to your objects, such as a flag or a mock. A strict slotted class would raise
AttributeError. - A few attributes are present on every instance and are read in hot loops, while many others are rare. You can put the first group in slots and let the rest fall into the dictionary.
- A feature in the standard library needs a
__dict__. The most common example isfunctools.cached_property.
The cached_property trap
cached_property computes a value once and stores it in the instance's __dict__, under the same name as the property. With a fully slotted class there is no __dict__, so it fails the first time you access the property.
from functools import cached_property
class Circle:
__slots__ = ("r",)
def __init__(self, r):
self.r = r
@cached_property
def area(self):
return 3.14159 * self.r ** 2
try:
Circle(2).area
except TypeError as exc:
print("TypeError:", exc)The message is No '__dict__' attribute on 'Circle' instance to cache 'area' property. Adding "__dict__" to the slots fixes it:
from functools import cached_property
class Circle:
__slots__ = ("r", "__dict__")
def __init__(self, r):
self.r = r
@cached_property
def area(self):
return 3.14159 * self.r ** 2
c = Circle(2)
print(c.area)
print(c.__dict__)This prints 12.56636 and then {'area': 12.56636}. The cached value lands in the dictionary while r stays in its slot. If you want to keep instances fully dictionary-free, use a plain @property and accept recomputation, or store the result in an explicit slot that you manage yourself.
All the combinations
The table shows what instances support for each way of declaring the class. "New attributes" means assigning a name that is not listed in the slots.
| Declaration | Has `__dict__` | Weak references | New attributes |
|---|---|---|---|
| No `__slots__` | Yes | Yes | Yes |
| `__slots__ = ("x",)` | No | No | No |
| `__slots__ = ("x", "__weakref__")` | No | Yes | No |
| `__slots__ = ("x", "__dict__")` | Yes | No | Yes |
| `__slots__ = ("x", "__dict__", "__weakref__")` | Yes | Yes | Yes |
The last row behaves almost like an ordinary class. The difference is that x is still stored in a slot and not in the dictionary. At that point you have most of the cost of a regular class and only some of the speed. Ask whether __slots__ is still giving you anything.
Interaction with inheritance
Both hidden slots are inherited. This leads to a rule and two errors.
The rule: if a base class already provides __dict__ or __weakref__, every subclass has it too. A subclass cannot remove it. This is why a subclass of a slotted class that has no __slots__ of its own gets a __dict__ again, as you saw in the inheritance chapter. It also gets a __weakref__ if the base did not already have one.
The errors: you cannot declare a hidden slot that the class already has through a base. Python raises TypeError at class creation.
class Base:
__slots__ = ("a", "__weakref__")
try:
class Child(Base):
__slots__ = ("b", "__weakref__")
except TypeError as exc:
print("TypeError:", exc)The message is __weakref__ slot disallowed: either we already got one, or __itemsize__ != 0. The same check applies to "__dict__" when a base class already has one. The fix is to declare each hidden slot once, at the first class in the hierarchy that needs it. Subclasses then inherit it and list only their own new names.
A practical pattern for a library base class that many users will subclass is to put "__weakref__" in the base. Subclasses can then be weakly referenced without any extra work. Leave "__dict__" out, so that each subclass decides on its own whether it wants dynamic attributes.
Common mistakes
- Assuming slots never affect weak references. A class works fine until the day someone puts it into a
WeakSet. If a class might be used that way, add__weakref__up front. - Adding
__dict__"just in case". This removes the main restriction slots provide and adds a pointer to every instance. If you find yourself adding it routinely, drop__slots__and keep the class simple. - Expecting a hidden slot to appear in a subclass. Listing
"__weakref__"or"__dict__"again in a subclass that already inherits it raisesTypeError. - Reading
__weakref__directly. It is a mechanism, not data. Useweakref.ref(obj)and call the result to get the object back. - Checking
hasattr(obj, "__dict__")to decide whether a class is slotted. A slotted class with"__dict__"in its slots passes that check. The more reliable check is to look at the class's own__slots__, and walk the base classes if you need the full picture.
Exercise
The class below fails when you run the code at the bottom. Explain why, then change only the __slots__ line so that the code prints True and the object can still not accept new attributes.
import weakref
class Token:
_slots = ("text",)
def init_(self, text):
self.text = text
t = Token("abc")
r = weakref.ref(t)
print(r() is t)
Show answer
A class with __slots__ has no __weakref__ slot unless you list one, so weakref.ref(t) raises TypeError: cannot create weak reference to 'Token' object. Change the line to __slots__ = ("text", "__weakref__"). Weak references now work, and because "__dict__" is still absent, t.other = 1 still raises AttributeError.
Exercise
Predict the output of this program, and say where each of a and b is stored.
class Mixed:
_slots = ("a", "dict")
m = Mixed()
m.a = 1
m.b = 2
print(m.dict_)
print(m.a, m.b)
Show answer
It prints {'b': 2} and then 1 2. The attribute a is named in __slots__, so it is stored in the fixed slot and found through the class's member descriptor, and it does not appear in m.__dict__. The attribute b is not a slot, so it goes into the per-instance dictionary that the "__dict__" entry enabled.
Exercise
A base class has __slots__ = ("id", "__dict__"). A teammate writes a subclass with __slots__ = ("name", "__dict__") so that it "also has a dict". What happens, and what should the subclass declare instead?
Show answer
Creating the subclass raises TypeError (the message says the __dict__ slot is disallowed because the class already has one). The subclass already inherits __dict__ from the base, so it should declare only its own new names: __slots__ = ("name",).