Sub topic 4
Naming and documenting exceptions
This chapter assumes you can write a basic class that subclasses Exception, and that you are comfortable with try, except, and raise. It covers how to name your exception classes, where to put them, and how to document them so other developers can use them without reading your source.
Why names and docs matter more for exceptions
An exception name is often the only thing a person sees when something breaks. It appears in a traceback, in a log line, and in an except clause in someone else's code. The name has to say what went wrong. The docstring has to say when it happens and what a caller can do about it.
Exceptions are also part of your public interface. Callers write except YourError: against the names you choose, and renaming one later breaks their code. Choose names with the same care you give to function names.
Naming conventions
PEP 8 gives the main rules for exception names:
- Use CapWords, like every other class:
ConfigError, notconfig_error. - End the name with
Errorif the exception represents an error. Most custom exceptions do. - Use
Warningas the suffix for classes meant for thewarningsmodule, such asDeprecatedConfigWarning. - Exceptions that are not errors, such as
StopIterationandKeyboardInterrupt, do not take the suffix. Custom exceptions that act as control-flow signals can follow that pattern, but they are rare.
Beyond the suffix, the name should describe the problem, not the place where it occurs.
| Weak name | Better name | Why |
|---|---|---|
| `BankException` | `InsufficientFundsError` | Names the problem, not the module |
| `Error1` | `InvalidPortError` | A number tells the reader nothing |
| `BadThing` | `ConfigError` | CapWords and the `Error` suffix tell the reader this is an exception |
| `FailedToParseTheConfigurationFileError` | `ConfigParseError` | Specific but short |
| `ValueError` (reused) | `InvalidPortError` | A new name lets callers catch only your case |
A base class named after the package
For a package with several exceptions, give the package one base class and name it after the package. A package called shop gets ShopError. Every other exception in the package inherits from it, so a caller can catch everything your package raises with one clause. The next chapters cover hierarchy design in detail. For now, the point is that the base class name should identify the package at a glance.
Do not shadow built-in names
Python already has TimeoutError, ConnectionError, PermissionError, FileNotFoundError, and many more. If you define your own class with one of these names, you create two different classes with the same name. Code that catches one will not catch the other.
import builtins
class TimeoutError(Exception):
"""Our own timeout, which hides the built-in name in this module."""
try:
raise builtins.TimeoutError("socket timed out")
except TimeoutError:
print("caught by our class")
except Exception as exc:
print("built-in TimeoutError slipped past:", type(exc) is builtins.TimeoutError)This prints built-in TimeoutError slipped past: True. Your except TimeoutError looks correct, and it silently misses the error you meant to handle. Pick a different name, such as RequestTimeoutError, or catch the built-in on purpose and say so in a comment.
Where the name shows up
Python prints the class name in tracebacks. For classes defined in a module other than __main__ or builtins, it prints the module path too.
class ConfigError(Exception):
"""Raised when configuration is missing or invalid."""
print(ConfigError.__module__)
print(ConfigError.__qualname__)
print(repr(ConfigError("missing 'database_url'")))Run as a script, this prints __main__, then ConfigError, then ConfigError("missing 'database_url'"). If the same class lived in myapp/errors.py, a traceback would show myapp.errors.ConfigError: missing 'database_url'. The module path helps people find the definition, so keep your exceptions in a stable, predictable module. Two things follow from this:
- Put exceptions in one module per package, usually
errors.pyorexceptions.py. Callers then know where to import from. - Do not move a class between modules after release without leaving a re-export behind. Pickled exceptions and logged names depend on the module path.
Define __all__ in that module so from myapp.errors import * and documentation tools expose only the exceptions you intend:
__all__ = ["ShopError", "OutOfStockError", "PaymentDeclinedError"]Documenting an exception class
An exception class needs a docstring. The class body can be only a docstring, with no pass, because a docstring is a valid statement.
A good docstring answers three questions:
- When is this raised? Start with a one-line summary such as "Raised when ...".
- What data does it carry? List the attributes if there are any.
- What should the caller do? Add this when the answer is not obvious.
class ShopError(Exception):
"""Base class for all errors raised by the shop package."""
class OutOfStockError(ShopError):
"""Raised when an item is requested but no units remain.
Attributes:
sku: The stock-keeping unit that was requested.
requested: How many units the caller asked for.
available: How many units were actually in stock.
Callers can usually recover by reducing the quantity or
offering the customer a back-order.
"""
def __init__(self, sku, requested, available):
super().__init__(sku, requested, available)
self.sku = sku
self.requested = requested
self.available = available
def __str__(self):
return (
f"{self.sku}: requested {self.requested}, "
f"only {self.available} in stock"
)The class docstring is not printed in a traceback. Only the message from str(exc) appears there. The docstring is for people reading the code, using help(), or browsing generated documentation. Keep the two jobs separate: the message describes this particular failure, and the docstring describes the whole category of failure.
Document raises in functions, too
Callers learn what a function can raise from its docstring. Add a Raises section for each custom exception that the function raises or lets through on purpose.
def reserve(stock, sku, quantity):
"""Remove units from stock and return the new count.
Args:
stock: A dict mapping SKU strings to unit counts.
sku: The item to reserve.
quantity: Number of units to reserve.
Returns:
The number of units left after the reservation.
Raises:
OutOfStockError: If fewer than ``quantity`` units are available.
"""
available = stock.get(sku, 0)
if quantity > available:
raise OutOfStockError(sku, quantity, available)
stock[sku] = available - quantity
return stock[sku]
try:
reserve({"pen": 2}, "pen", 5)
except ShopError as exc:
print(exc)This prints pen: requested 5, only 2 in stock.
List only what the function documents as its contract. If a KeyError from a bug could also escape, that does not belong in Raises.
Checking conventions automatically
Naming rules are easy to forget. A small check in your test suite keeps them in force. This script finds every exception class defined in the current module and reports any that break the conventions.
import inspect
class ShopError(Exception):
"""Base class for all errors raised by the shop package."""
class OutOfStockError(ShopError):
"""Raised when an item is requested but no units remain."""
class BadStuff(ShopError):
pass
def convention_problems(namespace, module_name):
problems = []
for name, obj in namespace.items():
if not inspect.isclass(obj) or not issubclass(obj, BaseException):
continue
if obj.__module__ != module_name:
continue
if not name.endswith(("Error", "Warning")):
problems.append(f"{name}: name should end in Error or Warning")
if not obj.__doc__:
problems.append(f"{name}: missing docstring")
return problems
for problem in convention_problems(globals(), __name__):
print(problem)This prints two lines for BadStuff: one for the name and one for the missing docstring. The check reads obj.__doc__ directly. inspect.getdoc would inherit a parent's docstring, and that would hide a missing one. In a real project, call convention_problems(vars(myapp.errors), "myapp.errors") from a test and assert that the result is an empty list.
Common naming mistakes
- Ending in
Exceptioninstead ofError. It works, but it breaks PEP 8 and mixes styles with the standard library. - Naming by location, such as
DatabaseModuleError. When the module is renamed, the name becomes misleading. Name the problem instead. - Names so generic that they carry no information, like
MyErrororCustomError. Reserve a generic name for the package base class only, and prefix it with the package name. - Repeating the package name in every class, such as
ShopOutOfStockError. The module path already tells the reader where the class lives. - Writing a docstring that repeats the name ("Out of stock error."). Say when it is raised.
Exercise
A teammate defines class ConnectionError(Exception) in myapp/errors.py and writes except ConnectionError: in another module that imports it with from myapp.errors import ConnectionError. The code calls a socket library that raises the built-in ConnectionError. Does the handler catch it, and what would you change?
Show answer
No. The imported class is a different class from the built-in, and it does not inherit from it, so the handler misses the library's error. Rename the custom class to something specific, such as UpstreamConnectionError. If you need to cover the built-in as well, catch both explicitly with except (UpstreamConnectionError, builtins.ConnectionError):, or wrap the built-in in your own exception with raise ... from.
Exercise
Write the class definition and docstring for an exception named for a user who tries to log in with an expired token. It should inherit from a package base class AuthError, carry a user_id attribute, and follow the naming and documentation conventions in this chapter.
Show answer
class ExpiredTokenError(AuthError): """Raised when a login token is past its expiry time. Attributes: userid: The ID of the user whose token expired. Callers should ask the user to sign in again. """ def init(self, userid): super()._init(userid) self.userid = userid def _str(self): return f"token expired for user {self.userid}"