Sub topic 10
Pickling and Copying Slotted Objects
This chapter assumes you know how __slots__ removes the per-instance __dict__, and that you have used pickle and copy on ordinary classes. A slotted object has no __dict__ to serialize. This chapter explains what pickle and copy do instead, where that fails, and how to take control with __getstate__ and __setstate__.
What pickle needs from an object
To pickle an instance, pickle asks the object for a reduction through obj.__reduce_ex__(protocol). The reduction is a tuple with three parts that matter here:
- a callable that rebuilds an empty object (for modern protocols this is
copyreg.__newobj__, which callscls.__new__(cls)), - the arguments for that callable,
- a state value that is applied to the new object afterwards.
For an ordinary instance the state is its __dict__. For a slotted instance there is no dict, so the state has to describe the slot values. copy.copy and copy.deepcopy use the same __reduce_ex__ machinery, so whatever works for pickling also works for copying.
Slotted objects pickle with protocol 2 and later
Python 3 uses protocol 4 or higher by default, so a plain slotted class pickles without extra code.
import pickle
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
print("__init__ called")
self.x = x
self.y = y
p = Point(1, 2)
data = pickle.dumps(p)
q = pickle.loads(data)
print(q.x, q.y)
print(q is p)
print(hasattr(q, "__dict__"))The output shows __init__ called once, for the original Point(1, 2). Loading does not call __init__. The result is a new object whose slots were filled from the saved state, and it still has no __dict__.
You can see the state directly by calling __reduce_ex__ yourself:
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
func, args, state = p.__reduce_ex__(2)[:3]
print(func.__name__)
print(args)
print(state)The state prints as (None, {'x': 1, 'y': 2}). It is a two-item tuple. The first item is the instance __dict__, which is None here because the class has none. The second item is a dictionary that maps each slot name to its value. When unpickling a two-item tuple state, pickle fills the dict from the first item (if it is not empty) and calls setattr for every entry in the second.
Unset slots are skipped
A slot that was never assigned raises AttributeError when read. Pickle respects that. It leaves unset slots out of the saved state, so they stay unset after loading.
class Point:
__slots__ = ("x", "y")
p = Point.__new__(Point)
p.x = 1
print(p.__reduce_ex__(2)[2])
import pickle
q = pickle.loads(pickle.dumps(p))
print(q.x)
print(hasattr(q, "y"))The state is (None, {'x': 1}), q.x is 1, and hasattr(q, "y") is False. This matters when you design classes with optional slots. A round trip preserves the "not set" condition. It does not fill it with None.
Subclasses that have both a dict and slots
When a subclass does not declare __slots__, it regains a __dict__ (see the inheritance chapter). Its state then carries both parts.
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
class Loose(Point):
pass
obj = Loose(1, 2)
obj.note = "hi"
print(obj.__reduce_ex__(2)[2])The state is ({'note': 'hi'}, {'x': 1, 'y': 2}). Slot values from every class in the inheritance chain are collected into the second dictionary, so a base class's slots are saved along with the subclass's.
Old protocols
Protocols 0 and 1 are the legacy formats. They do not use __newobj__, and before Python 3.11 they could not describe slot state. Pickling a slotted object with them raised a TypeError saying the class defines __slots__ without defining __getstate__. Newer versions give every object a default object.__getstate__, which changes this behavior. The result still depends on your Python version, so check what your interpreter does:
import pickle
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
for protocol in (0, 1, 2):
try:
pickle.dumps(p, protocol=protocol)
print(protocol, "ok")
except TypeError as exc:
print(protocol, "TypeError:", exc)Copying slotted objects
copy.copy and copy.deepcopy ask for __reduce_ex__(4), so they work on slotted classes with no extra code. Shallow copies share the values stored in the slots. Deep copies duplicate them.
import copy
class Box:
__slots__ = ("items",)
def __init__(self, items):
self.items = items
a = Box([1, 2])
shallow = copy.copy(a)
deep = copy.deepcopy(a)
print(shallow.items is a.items)
print(deep.items is a.items)
print(deep.items == a.items)This prints True, False, True. Like unpickling, copying does not call __init__. If __init__ registers the object somewhere, opens a resource, or increments a counter, the copy skips that work. The same is true of pickle, and it is the usual source of surprises with both.
Taking control with `__getstate__` and `__setstate__`
Write your own __getstate__ when some slots should not be saved. Typical cases are caches, open file handles, locks, and values you can recompute. Write a matching __setstate__ to restore the object.
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]
restored = pickle.loads(pickle.dumps(r))
print(restored.title)
print(restored._cache)The restored object has the title and a fresh, empty cache. The saved bytes never contain the old cache.
The default behavior also has a cost. Because it saves every set slot, a slotted class that holds a large derived value pickles that value too. A custom __getstate__ is the place to drop it.
Version-dependent behavior
| Situation | Behavior |
|---|---|
| Protocol 2 or higher, no custom hooks | Works. State is `(dict_or_None, slots_dict)`. |
| Protocol 0 or 1 | Depends on Python version. Older versions raise `TypeError`. |
| Python 3.11 and later | `object.__getstate__` exists, so you can call it or extend it from your own `__getstate__`. |
| Unset slot | Omitted from state and still unset after loading. |
| `__init__` | Not called when loading or copying. |
On Python 3.11 and later, a custom __getstate__ can start from the default and adjust it:
import pickle
class Session:
__slots__ = ("user", "token", "_lock")
def __init__(self, user, token):
self.user = user
self.token = token
self._lock = object()
def __getstate__(self):
dict_state, slot_state = super().__getstate__()
slot_state = {k: v for k, v in slot_state.items() if k != "_lock"}
return dict_state, slot_state
def __setstate__(self, state):
dict_state, slot_state = state
for name, value in slot_state.items():
setattr(self, name, value)
self._lock = object()
s = pickle.loads(pickle.dumps(Session("ana", "abc")))
print(s.user, s.token, type(s._lock).__name__)This relies on object.__getstate__ returning a (None, slots_dict) tuple for a slotted class with no dict, as shown earlier. It requires Python 3.11 or later. On older versions, build the dictionary yourself from __slots__.
Slotted dataclasses
A dataclass created with slots=True pickles and copies the same way as a hand-written slotted class. Frozen dataclasses need extra care, because their __setattr__ raises an error and the default loader uses setattr. For frozen=True, slots=True, the dataclass decorator generates __getstate__ and __setstate__ that assign through object.__setattr__, so pickling works with no work from you.
import copy
import pickle
from dataclasses import dataclass
@dataclass(frozen=True, slots=True)
class Point:
x: int
y: int = 0
p = Point(1, 2)
print(pickle.loads(pickle.dumps(p)) == p)
print(copy.deepcopy(p) == p)Both lines print True. Because slots=True is a Python 3.10 feature, this example needs 3.10 or later.
Common errors
- Custom
__getstate__without__setstate__. Loading fails because there is no__dict__to update. - Expecting
__init__to run. Neither pickle norcopycalls it, so any setup done only there is missing on the copy. Restore that setup in__setstate__. - Assuming unset slots become
None. They stay unset, and reading them still raisesAttributeError. - Pickling with protocol 0 or 1. Behavior depends on the Python version. Use the default protocol.
- Unpicklable slot values. Slots holding locks, sockets, or open files fail at the pickling step. Exclude them in
__getstate__and rebuild them in__setstate__.
Exercise
A slotted class has the slots ("name", "_conn"), where _conn holds an open network connection created in __init__. Pickling an instance fails because the connection cannot be pickled. Write the two methods that fix this so that unpickled objects have the same name and _conn set to None.
Show answer
Save only the name, and restore _conn as None:
def _getstate(self):
return {"name": self.name}
def setstate(self, state):
self.name = state["name"]
self.conn = None
Both methods are needed. Without __setstate__, a dict state would be applied to a __dict__ that the slotted class does not have.
Exercise
You run copy.copy(obj) on a slotted object whose __init__ prints a message. The message does not appear for the copy. Why, and where should work that every copy needs be placed?
Show answer
copy.copy rebuilds the object through __reduce_ex__, which calls cls.__new__(cls) and then fills in the saved state. It never calls __init__. Put setup that every copy needs into __setstate__ (or define __copy__ and __deepcopy__), because those hooks run during copying and unpickling.