Sub topic 10
Pickling and Copying Slotted Objects
This chapter assumes you know how __slots__ removes the instance __dict__ (earlier chapters), and that you have used pickle and copy at a basic level. The question here is how Python saves and duplicates an object when there is no __dict__ to read its state from.
The default case works
On Python 3, pickling a slotted object with the default protocol works without any extra code. copy.copy and copy.deepcopy work too.
import copy
import pickle
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
q = pickle.loads(pickle.dumps(p))
print(q.x, q.y)
r = copy.copy(p)
print(r.x, r.y, r is p)
s = copy.deepcopy(p)
print(s.x, s.y)The printed values are 1 2, then 1 2 False, then 1 2. The copies are new objects with the same slot values.
What the saved state looks like
Pickle and copy both ask the object for a reduction through __reduce_ex__. For a regular instance, the state is the __dict__. For a slotted instance, the state is a pair: the first item is the __dict__ state, or None if there is none, and the second is a dictionary of slot names and values.
p = Point(1, 2)
print(p.__reduce_ex__(2)[2])This prints (None, {'x': 1, 'y': 2}). When the object is loaded, Python creates an empty instance without calling __init__, then sets each slot with setattr. Python finds the slot names by walking the class hierarchy, so slots declared in parent classes are saved as well.
Unset slots are skipped
A slot that was never assigned has no value, so it is left out of the state. After loading, it is still unset.
import pickle
class Point:
__slots__ = ("x", "y")
p = Point()
p.x = 1
q = pickle.loads(pickle.dumps(p))
print(q.x, hasattr(q, "y"))This prints 1 False. Nothing breaks, but code that expects every slot to exist after loading will raise AttributeError.
Old protocols fail
Pickle protocols 0 and 1 cannot save a slotted class unless it defines its own __getstate__. Python 3 defaults to protocol 4 or higher, so you will meet this only when you ask for an old protocol, for example to stay compatible with very old readers.
import pickle
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
try:
pickle.dumps(Point(1, 2), protocol=1)
except TypeError as exc:
print("TypeError raised for protocol 1")Controlling the state yourself
You can define __getstate__ and __setstate__ to leave out values that should not be saved, such as a cache. Both methods work on slotted classes.
import pickle
class Report:
__slots__ = ("title", "_cache")
def __init__(self, title):
self.title = title
self._cache = {}
def __getstate__(self):
return {"title": self.title}
def __setstate__(self, state):
self.title = state["title"]
self._cache = {}
r = Report("Q3")
r._cache["rows"] = [1, 2, 3]
loaded = pickle.loads(pickle.dumps(r))
print(loaded.title, loaded._cache)This prints Q3 {}. The cache is not saved, and __setstate__ creates a fresh one. Because copy uses the same hooks, copy.copy(r) also gets an empty cache.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError` mentioning `__slots__` and `__getstate__` | Protocol 0 or 1 | Use protocol 2 or higher, or define `__getstate__` |
| `AttributeError` on a slot after loading | The slot was unset when saved | Assign every slot in `__init__`, or set defaults in `__setstate__` |
| `PicklingError` that a class cannot be found | Class defined inside a function or not importable | Define the class at module level |
| Weak references missing after a copy | `__weakref__` is never copied | Create new weak references to the copy |
The last row is expected. A weak reference points at one specific object, so the copy starts with none.
Exercise
A slotted class has __slots__ = ("a", "b"). You create an instance, assign only a, and pickle it with the default protocol. After loading, what does hasattr(loaded, "b") return, and why?
Show answer
It returns False. A slot that was never assigned has no value, so it is omitted from the saved state. Loading creates an empty instance and sets only the saved slots, which leaves b unset.
Exercise
Why can pickle.dumps(obj, protocol=1) fail for a slotted class even though pickle.dumps(obj) works?
Show answer
Protocols 0 and 1 look for the state in the instance __dict__, which a slotted class lacks, so they raise TypeError unless the class defines __getstate__. The default protocol (2 or higher) knows how to collect slot values.