Sub topic 10
Keeping exceptions picklable
This chapter assumes you can write a custom exception with its own __init__, as in the previous chapters. It also assumes you know that super().__init__() sets the exception's args.
Why pickling matters
Python's pickle module turns an object into bytes and back. Exceptions are pickled more often than you might expect:
multiprocessingandconcurrent.futures.ProcessPoolExecutorsend a worker's exception to the parent process.copy.copy()andcopy.deepcopy()use the same machinery.- Task queues and test runners that run tests in parallel serialize errors to report them.
If your exception cannot be rebuilt, the failure appears in the parent process, far from the code that raised it. The error is usually a confusing TypeError.
How an exception is rebuilt
BaseException defines __reduce__, which tells pickle how to recreate the object. By default it returns the class, the args tuple, and the instance __dict__. On loading, Python calls cls(*args) and then restores the __dict__.
The rule to remember is that args must contain whatever __init__ needs as arguments.
The common bug
The attribute pattern from earlier chapters passes only a message to the base class:
import pickle
class AppError(Exception):
"""Base class for errors raised by this application."""
class BrokenFundsError(AppError):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"Cannot withdraw {amount}; balance is {balance}")
err = BrokenFundsError(50, 80)
print(err.args)
try:
pickle.loads(pickle.dumps(err))
except TypeError as exc:
print("TypeError:", exc)Here args is a one-item tuple holding the message. Dumping succeeds. Loading calls BrokenFundsError("Cannot withdraw ..."), which is missing amount, so it raises TypeError.
Fix 1: pass the constructor arguments to super
Give super().__init__ the same values that __init__ received, and build the message in __str__:
import copy
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(50, 80)
clone = pickle.loads(pickle.dumps(err))
print(clone.amount, clone.balance)
print(clone)
print(copy.deepcopy(err))Now args is (50, 80), so cls(*args) rebuilds the exception. The message comes from __str__, so it is not lost.
The cost is that err.args no longer holds the readable message. Code that prints err.args[0] will see a number. Prefer str(err) in your own code and logging.
Fix 2: override `__reduce__`
Sometimes args cannot match the constructor. A common case is keyword-only parameters, because cls(*args) cannot pass them. Define __reduce__ to return the class and the arguments to use:
class RateLimitError(AppError):
"""Raised when a client exceeds its request quota."""
def __init__(self, *, limit, window):
super().__init__(f"{limit} requests per {window}s exceeded")
self.limit = limit
self.window = window
def __reduce__(self):
return (_rebuild_rate_limit, (self.limit, self.window))
def _rebuild_rate_limit(limit, window):
return RateLimitError(limit=limit, window=window)The rebuild function must be defined at module level so pickle can find it by name. This approach keeps the readable message in args but adds code to maintain. Use Fix 1 when you can.
Exercise
Exercise
A custom exception defines __init__(self, code, detail) and calls super().__init__(f"{code}: {detail}"). Pickling works, but unpickling raises TypeError. Why does it fail, and what is the smallest change that fixes it?
Show answer
args holds only the formatted message, so unpickling calls cls(message) and detail is missing. Change the call to super().__init__(code, detail) and add a __str__ method that returns f"{self.code}: {self.detail}", after storing code and detail as attributes.