Sub topic 11
Adding context with add_note (Python 3.11+)
This chapter assumes you can define a custom exception, raise it, and catch it with try and except. It also assumes you know raise ... from. Everything here needs Python 3.11 or newer.
The problem: context you only learn later
Sometimes the code that raises an exception does not know everything a reader will want to see. An inner function knows a value was invalid. Only the caller knows which file, record, or request it was working on.
Before 3.11 you had two poor choices. You could catch the exception and raise a new one with a longer message, which adds a second traceback. Or you could edit exc.args, which is fragile. add_note is the third option: attach extra text to the exception you already have, then let it keep propagating.
How add_note works
Every BaseException has an add_note(note) method. It appends a string to a list stored in the __notes__ attribute. When Python prints a traceback, it shows each note on its own line after the exception message.
class AppError(Exception):
"""Base class for errors raised by this application."""
class ConfigError(AppError):
"""Raised when configuration is missing or invalid."""
def load_port(raw):
try:
return int(raw)
except ValueError as exc:
raise ConfigError(f"invalid port: {raw!r}") from exc
def load_server(settings):
try:
return load_port(settings["port"])
except ConfigError as exc:
exc.add_note(f"while loading server {settings['name']!r}")
raise
try:
load_server({"name": "web-1", "port": "abc"})
except ConfigError as exc:
print(exc)
print(exc.__notes__)The output is:
invalid port: 'abc'
["while loading server 'web-1'"]The message still reads invalid port: 'abc'. The note is stored separately, so str(exc) does not change. In an uncaught traceback, the note appears on the line after the exception message.
The bare raise at the end of load_server re-raises the same exception object, which keeps its traceback and its notes. If you wrote raise ConfigError(...) instead, you would create a new exception and lose the notes.
Where notes fit
Notes versus other tools
| Need | Tool | Effect |
|---|---|---|
| Say what low-level error caused this one | `raise ... from exc` | Creates a new exception and links the old one as `__cause__` |
| Give callers data to act on | Attributes set in `__init__` | Structured, safe to read in code |
| Add situational text for a human reader | `add_note` | Same exception, extra lines in the traceback |
Use attributes for anything a program will read. Use notes for text that only a person will read. Code that parses __notes__ is a sign the data should have been an attribute.
Details and limits
add_noteaccepts only a string. Passing anything else raisesTypeError.- Notes are kept in order, oldest first.
__notes__does not exist until the first call, so read it withgetattr(exc, "__notes__", []).- Notes do not survive every path.
copyandpicklehandle__notes__through the exception's state in recent versions, but do not rely on it across processes. Put anything essential in attributes andargs.
A practical pattern
A loop that processes many items is a good place for notes. The failure inside tells you what went wrong, and the loop adds which item it was.
def process_all(records):
for index, record in enumerate(records):
try:
validate(record)
except AppError as exc:
exc.add_note(f"record #{index}: {record!r}")
raiseYou get one traceback pointing at the real failure, with the item identity attached. No wrapper exception is needed.
Exercise
A function catches a ConfigError, calls exc.add_note("while loading server 'web-1'"), and then runs raise ConfigError(str(exc)). Will the note appear in the traceback of the final exception, and how would you fix it?
Show answer
No. The last line creates a new exception object, and the note lives on the old one. Replace it with a bare raise to re-raise the same object, so the note and the original traceback are kept.
Exercise
You want to record the user ID that triggered an error. A program elsewhere will need to look up that user. Should you use add_note or an attribute?
Show answer
Use an attribute, set in __init__. Notes are free-form text for people to read. Code that needs the value should read a named attribute, not parse __notes__.