Sub topic 11
Adding context with add_note (Python 3.11+)
This chapter assumes you can define a custom exception by subclassing Exception, raise and catch it, and use raise ... from for chaining. It also assumes you run Python 3.11 or newer. Earlier chapters covered carrying data in attributes and controlling the message. Here you will add human-readable context to an exception after it has been created, usually while it travels up the call stack.
The problem: context that arrives late
An exception is often raised in a low-level function that knows little about the bigger picture. The function that parses a port number knows the bad value. It does not know which file, which line, or which request it was working on. The caller knows that.
Before Python 3.11 you had three options, and each has a cost:
- Catch the exception and raise a new one with a longer message. This hides the original type unless you chain, and it adds a second traceback block.
- Mutate
exc.argsby hand. This is fragile and breaks code that readsargs. - Log the context separately. The log line and the traceback can then end up far apart.
Python 3.11 added a better option, defined in PEP 678: exception notes. A note is a string attached to an exception object. The interpreter prints notes after the exception message when it shows a traceback.
How add_note works
Every exception has a method add_note(note). It appends the string to a list stored in the attribute __notes__. The list does not exist until the first call.
try:
raise ValueError("bad value")
except ValueError as exc:
exc.add_note("while reading row 3")
exc.add_note("file: data.csv")
print(exc.__notes__)
print(str(exc))
print(exc.args)Output:
['while reading row 3', 'file: data.csv']
bad value
('bad value',)Three facts follow from this output:
- Notes are kept in order, oldest first.
str(exc)does not change. Notes are separate from the message.exc.argsdoes not change either, so adding a note never breaks code that depends onargs.
If you pass something that is not a string, add_note raises TypeError. Convert values with an f-string first.
What a traceback looks like
When an exception with notes goes uncaught, the traceback prints the message and then each note on its own line:
Traceback (most recent call last):
File "app.py", line 12, in load_ports
ports.append(parse_port(raw))
File "app.py", line 6, in parse_port
raise ConfigError(f"invalid port: {raw!r}") from exc
ConfigError: invalid port: 'http'
line 3 of ports.txtThe traceback module and logging.exception() use the same formatting, so notes also appear in log output. A custom sys.excepthook that formats the exception by hand will not show notes unless it reads __notes__ or calls the traceback module.
Adding a note and re-raising
The most common pattern has three steps: catch the exception, add a note, and re-raise with a bare raise. The bare raise re-raises the same object with its original traceback, so nothing is lost.
class AppError(Exception):
"""Base class for errors raised by this application."""
class ConfigError(AppError):
"""Raised when configuration is missing or invalid."""
def parse_port(raw):
try:
return int(raw)
except ValueError as exc:
raise ConfigError(f"invalid port: {raw!r}") from exc
def load_ports(rows):
ports = []
for line_no, raw in enumerate(rows, start=1):
try:
ports.append(parse_port(raw))
except ConfigError as exc:
exc.add_note(f"line {line_no} of ports.txt")
raise
return ports
try:
load_ports(["80", "443", "http"])
except ConfigError as exc:
print(exc)
print(exc.__notes__)Output:
invalid port: 'http'
['line 3 of ports.txt']parse_port stays simple. It reports only what it knows. load_ports adds the line number because it is the function that knows it. The exception type is still ConfigError, so any handler written for ConfigError or AppError keeps working.
Notes, attributes, and chaining compared
You now have four ways to attach information to a failure. They answer different questions.
| Tool | Who reads it | Best for | Set when |
|---|---|---|---|
| Message (`str(exc)`) | People and tests | A one-line summary of what went wrong | At `raise` time |
| Attributes (`exc.balance`) | Code | Structured data a handler acts on | At `raise` time, in `__init__` |
| `raise ... from exc` | People and code | Linking to the lower-level error that caused this one | When translating errors |
| Notes (`add_note`) | People | Where or while-doing-what context from a caller | Any time before the exception is handled |
The rule of thumb: if a handler needs the information to make a decision, make it an attribute. If a person reading a traceback needs it, make it a note. Do not write code that parses note text. Notes are free-form strings and have no stable format.
Chaining and notes work together. In the example above, parse_port chains the ValueError as the cause, and load_ports adds a note to the ConfigError. The traceback shows both the cause block and the note.
Writing good notes
Notes are most useful when each one answers a question the raising code could not. Keep these habits:
- State a fact, not a conclusion.
"line 3 of ports.txt"is better than"something is wrong here". - Keep each note to one line. The traceback prints notes as given, so a multi-line note breaks the layout.
- Add context at the layer that owns it. The code that iterates over rows adds the row number. The code that opens the file adds the path. Do not pass the path down five calls just to put it in a message.
- Leave out secrets. Notes are printed and logged like messages. Do not add passwords, tokens, or whole request bodies.
- Do not repeat the message. A note that restates
str(exc)only adds noise.
Notes accumulate
Notes belong to the exception object, and add_note never removes anything. If the same exception passes through several except blocks that each add a note, they all stay. That is the point of the pattern, but it has two consequences.
First, adding a note in a loop that handles the same exception object repeatedly will produce duplicates. Add the note once, where the exception is first caught.
Second, if you catch an exception and raise a new one, the notes stay on the old object. They are not copied. Chaining with from exc keeps the old object reachable through __cause__, and the traceback prints its notes in the cause block. If you want a note on the new exception, add it to the new one.
def read_settings(path):
try:
with open(path, encoding="utf-8") as handle:
return handle.read()
except OSError as exc:
exc.add_note(f"while reading settings from {path}")
raise ConfigError("cannot read settings") from excHere the note sits on the OSError, next to the low-level details, and the ConfigError stays a clean application-level message.
Reading notes in code
Because __notes__ may not exist, read it defensively:
def describe(exc):
lines = [f"{type(exc).__name__}: {exc}"]
lines.extend(getattr(exc, "__notes__", []))
return "\n".join(lines)
try:
load_ports(["http"])
except ConfigError as exc:
print(describe(exc))Output:
ConfigError: invalid port: 'http'
line 1 of ports.txtFor most programs you do not need this. The traceback module already formats notes, for example with traceback.format_exception(exc). Write your own formatting only when you build something like an error report.
Version support
add_note exists only on Python 3.11 and later. On Python 3.10 and earlier, calling it raises AttributeError. If your package supports older versions, you have two reasonable choices:
- Set
requires-python = ">=3.11"and use notes freely. - Keep supporting older versions and guard the call with
sys.version_info >= (3, 11). On older versions, fold the context into the message at raise time instead.
Do not assign exc.__notes__ by hand to imitate the feature. Older interpreters will not print it, so the context is lost exactly where you wanted it.
Testing notes
Notes are plain data on the exception object, so you can assert on them directly. Check __notes__ rather than relying on the match argument of pytest.raises, which compares against the message. This test uses the ConfigError and load_ports definitions from earlier in the chapter.
import pytest
def test_load_ports_adds_line_note():
with pytest.raises(ConfigError, match="invalid port") as info:
load_ports(["80", "http"])
assert info.value.__notes__ == ["line 2 of ports.txt"]
assert isinstance(info.value.__cause__, ValueError)The test checks the type and message, the note, and the preserved cause. Together they confirm the whole error story, not only that something failed.
Common mistakes
- Using a note when a handler needs the data. If a caller must read the line number to decide what to do, put it in an attribute.
- Adding a note, then raising a different exception. The note stays on the old object, and the new one has none.
- Passing a non-string.
exc.add_note(3)raisesTypeError. Useexc.add_note(str(3))or an f-string. - Using
raise excinstead of a bareraise. Both re-raise the same object, but a bareraiseis the idiom and keeps the intent clear. - Adding notes to exceptions you do not re-raise. If you swallow the exception right after adding a note, no one sees the note.
Summary
add_note attaches a string to an exception without touching its message or args. Use it at the layer that knows the surrounding context, then re-raise with a bare raise. Prefer attributes for data that code reads, chaining for cause links, and notes for the extra detail a person needs when reading the traceback.
Exercise
A function import_users(rows) calls parse_user(row), which raises ValidationError (a subclass of your AppError). Write the loop in import_users so that the exception reaching the caller is still the same ValidationError, but its traceback includes the note row 7 for the seventh row (rows are numbered from 1). Why should the row number be a note rather than part of the message built inside parse_user?
Show answer
Use enumerate and a bare raise:
for rowno, row in enumerate(rows, start=1):
try:
users.append(parseuser(row))
except ValidationError as exc:
exc.addnote(f"row {rowno}")
raise
parse_user only sees one row and has no idea of its position in the input, so it cannot build that text. The loop owns the row number, so it adds it as a note. The exception type, message, and args stay unchanged, and handlers written for ValidationError or AppError still work.
Exercise
What does this code print, and why? try: raise KeyError("missing") except KeyError as exc: exc.addnote("first") exc.addnote("second") print(len(exc.args), len(exc._notes_))
Show answer
It prints 1 2. add_note appends to __notes__ and leaves args alone, so args still holds the single original argument "missing", while __notes__ holds the two notes in the order they were added.