Sub topic 8
Controlling the message and args
This chapter assumes you can write a basic exception subclass, give it a custom __init__ that calls super().__init__, and use try/except/raise. It also assumes you have seen how an exception can carry attributes. Here you will learn what Python stores in args, how that value becomes the message, and how to keep both consistent when your exception takes its own constructor arguments.
What BaseException does with its arguments
Every exception inherits from BaseException. Two of its behaviors matter here:
BaseException.__new__stores the positional arguments of the constructor call in the tupleargs. This happens before your__init__runs.BaseException.__init__replacesargswith the positional arguments you pass to it.
str(exc) and repr(exc) are both derived from args:
for exc in (Exception(), Exception("boom"), Exception("boom", 42)):
print(repr(exc), "|", str(exc), "|", exc.args)The output is:
Exception() | | ()
Exception('boom') | boom | ('boom',)
Exception('boom', 42) | ('boom', 42) | ('boom', 42)The rules are:
| `len(args)` | `str(exc)` | `repr(exc)` |
|---|---|---|
| 0 | empty string | `Name()` |
| 1 | `str(args[0])` | `Name('...')` |
| 2 or more | `str(args)`, the tuple's text | `Name(a, b)` |
With two or more arguments, the "message" is the text of a tuple. That is rarely what you want to show a user, so you usually need to control it.
The common trap: a message that replaces args
The most common pattern stores attributes and passes a formatted message to the base class:
import copy
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)
print(exc.args)
try:
copy.copy(exc)
except TypeError as err:
print("copy failed:", err)The message looks right, but args is now ('Cannot withdraw 80; balance is 50',), which does not match the constructor signature (balance, amount). Copying and pickling rebuild an exception by calling type(exc)(*exc.args). That call passes one string to a constructor that needs two arguments, so it raises TypeError.
This matters in practice. Libraries such as multiprocessing and concurrent.futures pickle exceptions to send them between processes. A custom exception that cannot be rebuilt turns the original error into a confusing TypeError. The pickling chapter covers this in more detail. For now, treat it as one reason to keep args consistent with the constructor.
Fix 1: pass the constructor arguments and override `__str__`
The most reliable pattern is to give super().__init__ the same arguments your constructor received. Then args matches the signature and copying works. Define __str__ to produce the human-readable message:
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}"
exc = InsufficientFundsError(50, 80)
print(str(exc))
print(repr(exc))
print(exc.args)
clone = pickle.loads(pickle.dumps(exc))
print(clone.balance, clone.amount)
print(copy.copy(exc).amount)The output is:
Cannot withdraw 80; balance is 50
InsufficientFundsError(50, 80)
(50, 80)
50 80
80repr now shows the real constructor call, which is useful when you debug from a log. The message lives in one place, __str__, so you can change the wording without touching args.
One caution: __str__ must return a str. Returning a number or None raises TypeError when something prints the exception, and that failure can hide the error you were trying to report.
Fix 2: message first, extras as keyword-only attributes
Sometimes the caller already has the full message, and the extra data is optional context. In that case, make the message the first positional argument and give every extra a default:
import copy
class AppError(Exception):
"""Base class for errors raised by this application."""
class ValidationError(AppError):
"""Raised when user input fails validation."""
def __init__(self, message, *, field=None):
super().__init__(message)
self.field = field
err = ValidationError("must not be empty", field="email")
print(err)
print(err.args)
print(copy.copy(err).field)This works with copying because args is ('must not be empty',), so ValidationError('must not be empty') is a valid call. Python then restores the instance __dict__, which holds field. Every extra argument needs a default for this to work. If field were a required keyword-only argument, the rebuild call would fail again.
Choose between the two fixes this way:
- Use Fix 1 when the exception's data is required and the message can be built from it. The caller cannot write an inconsistent message, because the message is generated.
- Use Fix 2 when callers supply their own message and the extra data is optional.
Skipping `super().__init__` loses information
If your __init__ never calls super().__init__, args comes only from __new__, which sees positional arguments only:
class AppError(Exception):
"""Base class for errors raised by this application."""
class Sloppy(AppError):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
print(repr(Sloppy(50, 80)))
print(repr(Sloppy(balance=50, amount=80)))
print(repr(str(Sloppy(balance=50, amount=80))))The output is:
Sloppy(50, 80)
Sloppy()
''The same class produces different args depending on whether the caller used positional or keyword arguments. With keyword arguments the message is empty, so the traceback shows only Sloppy. This is the main reason to always call super().__init__.
A default message
To give an exception a sensible message when the caller supplies none, put the default in __init__. Do not rely on an empty args:
class AppError(Exception):
"""Base class for errors raised by this application."""
class ConfigError(AppError):
"""Raised when configuration is missing or invalid."""
default_message = "configuration is missing or invalid"
def __init__(self, message=None):
super().__init__(message or self.default_message)
print(ConfigError())
print(ConfigError("missing 'database_url'"))The class attribute default_message lets subclasses override the default without rewriting __init__. Both calls pass exactly one argument to the base class, so args stays valid for copying.
Reading the message back
Avoid code such as exc.args[0] in handlers. It breaks when args is empty and when a subclass changes what it passes to super().__init__. Instead:
- Use
str(exc)when you need the text. - Use the named attributes (
exc.amount) when you need the data. - Do not parse the message to recover data. Messages change, and attributes do not.
Summary of the patterns
| Pattern | `args` | `str(exc)` | Copy and pickle |
|---|---|---|---|
| No `super().__init__` call | positional arguments only | often empty | breaks for keyword calls |
| `super().__init__(message)` with a different constructor signature | `(message,)` | the message | `TypeError` |
| `super().__init__(*ctor_args)` plus `__str__` | matches the signature | your `__str__` | works |
| Message first, optional keyword extras with defaults | `(message,)` | the message | works |
Exercise
A teammate writes class RateLimitError(AppError) with def __init__(self, limit, window): super().__init__(f"{limit} requests per {window}s exceeded"); self.limit = limit; self.window = window. Calling copy.copy(RateLimitError(100, 60)) raises TypeError. Explain why, and rewrite the class so copying works and str(exc) still gives the same text.
Show answer
The base class receives one string, so args is ("100 requests per 60s exceeded",). copy.copy rebuilds the exception with RateLimitError(*args), which supplies one argument to a constructor that needs two. The fix is to pass the constructor arguments to the base class and move the text into __str__: def __init__(self, limit, window): super().__init__(limit, window); self.limit = limit; self.window = window and def __str__(self): return f"{self.limit} requests per {self.window}s exceeded". Now args == (100, 60), the rebuild call is valid, and str(exc) is unchanged.
Exercise
What are args, str(exc) and repr(exc) for Exception("disk", "full"), and why is str(exc) a poor user-facing message?
Show answer
args is ('disk', 'full'), repr(exc) is Exception('disk', 'full'), and str(exc) is ('disk', 'full'). With two or more arguments, str returns the text of the whole args tuple, including the parentheses and quotes, instead of a sentence. Pass a single formatted string, or override __str__, to control the message.