Sub topic 8
Controlling the message and args
This chapter assumes you can write a custom exception with a __init__ that calls super().__init__, and that you know how try, except, and raise work. Here you will see how an exception's args tuple relates to its message, and why that relationship matters.
How args and str work
Every exception has an args tuple. It holds the positional arguments given when the exception was created. str(exc) is built from args like this:
| Contents of `args` | Result of `str(exc)` |
|---|---|
| Empty tuple | Empty string |
| One item | `str()` of that item |
| Several items | `str()` of the whole tuple |
print(exc) and the final line of a traceback both use this text.
print(repr(str(ValueError())))
print(str(ValueError("bad value")))
print(str(ValueError("bad value", 42)))The output is an empty string, then bad value, then ('bad value', 42). The third line is why passing several loose values to an exception without a __str__ produces an awkward message.
The common mistake: a message in args
Chapter code often stores data as attributes and passes a formatted message to the base class:
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}")
exc = InsufficientFundsError(50, 80)
print(exc.args)
print(exc)
try:
pickle.loads(pickle.dumps(exc))
except TypeError as err:
print("unpickling failed:", type(err).__name__)The message looks right, but args is ("Cannot withdraw 80; balance is 50",), which is one string. Python rebuilds an exception by calling the class with *args. That happens when you unpickle it, and copy.copy does the same. The rebuild call is InsufficientFundsError("Cannot withdraw ..."), and __init__ needs two arguments, so it raises TypeError.
This matters in practice. Libraries such as multiprocessing and concurrent.futures.ProcessPoolExecutor pickle exceptions to send them between processes. A badly shaped exception can turn a clear error into a confusing TypeError.
The fix: keep args matched to __init__
Pass the same values to super().__init__ that your own __init__ receives. Then put the readable text in __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}"
exc = InsufficientFundsError(50, 80)
print(exc.args)
print(exc)
clone = pickle.loads(pickle.dumps(exc))
print(clone.amount - clone.balance)Now args is (50, 80), so a rebuild calls InsufficientFundsError(50, 80) and succeeds. __str__ still gives the user a sentence.
Choosing between the two designs
- Message only. If your exception takes one string and nothing else,
class ConfigError(AppError): passis enough.argsis(message,)and rebuilding works. - Data plus message. If callers need the values, store them as attributes. Pass the same values to
super().__init__and write__str__. - Optional message. To let callers override the text, accept
message=Noneand build a default in__str__when it is missing. Includemessagein thesuper().__init__call as well.
Do not read exc.args[0] in handlers to get data. Use named attributes, because args exists to support str, pickling, and copying.
Checking your design
A quick test shows whether an exception is safe. It builds the exception, copies it, and compares the results:
import copy
original = InsufficientFundsError(50, 80)
duplicate = copy.copy(original)
assert duplicate.args == original.args
assert str(duplicate) == str(original)
assert duplicate.amount == 80If the assertions pass, the exception survives copying and pickling.
Exercise
A custom exception defines __init__(self, code, detail) and calls super().__init__(f"{code}: {detail}"). It prints a good message, but pickle.loads(pickle.dumps(exc)) raises TypeError. Why does this happen, and what is the smallest change that fixes it?
Show answer
args is ("<code>: <detail>",), one string, but unpickling calls the class with *args, and __init__ needs two arguments. Change the call to super().__init__(code, detail), store self.code and self.detail, and add a __str__ that returns f"{self.code}: {self.detail}".