Sub topic 10
Keeping Exceptions Picklable
This chapter assumes you can write a custom __init__ that calls super().__init__, and that you know Exception.args holds the constructor arguments. It covers a failure that shows up only when an exception crosses a process boundary: the exception can be pickled but cannot be unpickled.
Why exceptions get pickled
Pickling converts a Python object to bytes and back. Most code never pickles an exception, so the problem stays hidden until the code moves into a worker process. These tools pickle exceptions for you:
multiprocessing.Poolandconcurrent.futures.ProcessPoolExecutorsend a worker's exception back to the parent process.- Task queues such as Celery or RQ may serialize a failure so it can be stored or retried.
copy.copy()andcopy.deepcopy()use the same mechanism as pickle to duplicate objects.
A custom exception that fails to round-trip turns a clear application error into a confusing one. The parent process may see a TypeError from inside the unpickler, or a broken worker pool, and the original message is lost.
What pickle does with an exception
BaseException defines __reduce__, which tells pickle how to rebuild the object. For an exception it returns three things: the class, self.args, and the instance __dict__ (when the dict is not empty). On load, pickle calls cls(*args) and then copies the saved attributes back onto the new object.
The rule follows from this: cls(*self.args) must work. Dumping always succeeds, because it only reads attributes. The failure appears at load time, which is often in a different process from the one that raised the error.
The classic failure
The earlier chapter on carrying data defined InsufficientFundsError with two attributes and a formatted message passed to the base class. That pattern breaks pickling:
import pickle
class AppError(Exception):
"""Base class for errors raised by this application."""
class InsufficientFundsError(AppError):
"""Raised when a withdrawal exceeds the available balance."""
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"Cannot withdraw {amount}; balance is {balance}")
err = InsufficientFundsError(balance=50, amount=80)
print(err.args)
data = pickle.dumps(err) # works
try:
pickle.loads(data)
except TypeError as exc:
print("TypeError:", exc)err.args is ('Cannot withdraw 80; balance is 50',), a single string. On load, pickle calls InsufficientFundsError("Cannot withdraw 80; balance is 50"), which supplies one argument where __init__ needs two. The TypeError says that amount is missing.
Fix 1: pass the constructor arguments to the base class
The simplest repair keeps args identical to what __init__ receives. Move the message formatting into __str__:
import pickle
class AppError(Exception):
"""Base class for errors raised by this application."""
class InsufficientFundsError(AppError):
"""Raised when a withdrawal exceeds the available balance."""
def __init__(self, balance, amount):
super().__init__(balance, amount)
self.balance = balance
self.amount = amount
def __str__(self):
return f"Cannot withdraw {self.amount}; balance is {self.balance}"
err = InsufficientFundsError(balance=50, amount=80)
clone = pickle.loads(pickle.dumps(err))
print(type(clone).__name__)
print(clone.balance, clone.amount)
print(str(clone))Now args is (50, 80), so cls(*args) rebuilds the exception. The message is regenerated by __str__, so it also stays consistent if you later change the wording.
This also fixes the case where callers use keyword arguments. Keyword arguments are never stored in args. Without the explicit super().__init__(balance, amount) call, InsufficientFundsError(balance=50, amount=80) would have empty args, and unpickling would call cls().
Fix 2: define `__reduce__`
Sometimes you cannot make args match the constructor. Keyword-only parameters are the common case, along with __init__ signatures that compute values from their inputs.
import pickle
from functools import partial
class AppError(Exception):
"""Base class for errors raised by this application."""
class RetryError(AppError):
"""Raised when an operation still fails after several attempts."""
def __init__(self, message, *, attempts):
super().__init__(message)
self.attempts = attempts
def __reduce__(self):
return (partial(type(self), attempts=self.attempts), self.args)
err = RetryError("upstream unavailable", attempts=3)
clone = pickle.loads(pickle.dumps(err))
print(clone, clone.attempts)Here args is ("upstream unavailable",). Without __reduce__, unpickling would call RetryError("upstream unavailable") and fail because the keyword-only attempts is missing. The __reduce__ method returns a callable and the positional arguments to call it with. The partial object supplies the keyword argument, and pickle can serialize it as long as the exception class is importable.
Two details of a custom __reduce__:
- It replaces the default behavior, so the instance
__dict__is no longer restored. Anything not passed to the constructor is lost, including notes added withadd_note. To keep that state, return a third element, for example(callable, args, self.__dict__). - Subclasses inherit the method. If a subclass adds constructor parameters, it must override
__reduce__as well, or it will rebuild itself with the wrong arguments.
Prefer Fix 1 when you can use it. It needs no extra method, and a subclass keeps working as long as it forwards its arguments to super().__init__.
| Constructor style | `args` after init | Round-trips by default? | Remedy |
|---|---|---|---|
| `Exc(message)` | `(message,)` | Yes | None needed |
| `Exc(a, b)` with `super().__init__(a, b)` | `(a, b)` | Yes | None needed |
| `Exc(a, b)` with `super().__init__(text)` | `(text,)` | No | Pass `a, b` to super and add `__str__` |
| `Exc(a, b)` called with keywords, no `super().__init__` | `()` | No | Call `super().__init__(a, b)` |
| `Exc(msg, *, key)` | `(msg,)` | No | Define `__reduce__` |
Other things that break pickling
A matching __init__ is necessary but not sufficient. These problems also appear in practice:
- Local classes. Pickle stores the class by module and qualified name. An exception defined inside a function, or in a module the receiving process cannot import, fails to load.
- Unpicklable attributes. Everything in
__dict__is pickled with the exception. Locks, open files, sockets, database connections, and lambdas raise an error duringdumps. Store plain data instead, such as an ID, a status code, or a string. - Large attributes. Attaching a full HTTP response or a big dataset copies it across the process boundary. Keep the fields a caller needs, such as the status code and URL.
- Lost chain and traceback.
__cause__,__context__, and__traceback__are not part of the pickled state. The clone has no traceback and no chained cause.ProcessPoolExecutorworks around this by attaching the worker's formatted traceback as text, but you should not depend on the original objects surviving.
Seeing it work across processes
A ProcessPoolExecutor returns a worker's exception to the parent by pickling it. With the Fix 1 version of the class, the parent can catch the exact custom type:
from concurrent.futures import ProcessPoolExecutor
class AppError(Exception):
"""Base class for errors raised by this application."""
class InsufficientFundsError(AppError):
"""Raised when a withdrawal exceeds the available balance."""
def __init__(self, balance, amount):
super().__init__(balance, amount)
self.balance = balance
self.amount = amount
def __str__(self):
return f"Cannot withdraw {self.amount}; balance is {self.balance}"
def withdraw(amount):
raise InsufficientFundsError(balance=50, amount=amount)
if __name__ == "__main__":
with ProcessPoolExecutor() as pool:
future = pool.submit(withdraw, 80)
try:
future.result()
except InsufficientFundsError as exc:
print("caught in parent:", exc)If you switch the class back to the broken version from earlier in the chapter, the parent cannot rebuild the exception. Depending on the Python version, you get a TypeError or a BrokenProcessPool error instead of your own exception.
Testing the round trip
A short test catches this class of bug when you define the exception, before it reaches production. Pickle each custom exception and check the type, the data, and the message:
import pickle
import pytest
@pytest.mark.parametrize(
"exc",
[
InsufficientFundsError(balance=50, amount=80),
RetryError("upstream unavailable", attempts=3),
],
)
def test_exception_survives_pickle(exc):
clone = pickle.loads(pickle.dumps(exc))
assert type(clone) is type(exc)
assert str(clone) == str(exc)
assert clone.args == exc.args
assert vars(clone) == vars(exc)This test assumes both classes are imported from the module under test. Add every new exception class to the parameter list. Pickling goes through the same path as copy.copy(), so the test also covers copying.
Exercise
A teammate writes class QuotaError(AppError) with def __init__(self, user, limit): self.user = user; self.limit = limit; super().__init__(f"{user} exceeded {limit}"). pickle.dumps(QuotaError("ana", 10)) succeeds, but pickle.loads of the result raises TypeError. Explain why, and show the smallest change that fixes it while keeping the same message text.
Show answer
The call to super().__init__ stores only the formatted string in args, so args is ("ana exceeded 10",). Pickle rebuilds the exception with QuotaError("ana exceeded 10"), which supplies one argument where __init__ needs two (limit is missing). The fix is to pass the constructor arguments to the base class and move the text to __str__: super().__init__(user, limit) in __init__, and def __str__(self): return f"{self.user} exceeded {self.limit}". Now args is ("ana", 10), cls(*args) works, and the message is unchanged.