Python Context Managers and Exceptions #3.2
A context manager cleans up resources when a with block ends, even after an exception. When raising a new exception, raise from preserves the original cause.
On this page (11)
Context managers and exceptions
What does this code print?
class Session:
def __enter__(self):
print("open")
def __exit__(self, exc_type, exc, tb):
print("close")
with Session():
print("inside")
int("Orbit")
# prints:
# open
# inside
# close
# error: ValueError: invalid literal for int() with base 10: 'Orbit'
int("Orbit") fails, yet close is still printed before the error escapes. The lesson has two halves, both in that snippet:
- A context manager is an object with
__enter__and__exit__.withcalls__enter__on entry and always calls__exit__on exit, even when the block raises. - An exception is an object that signals an error. It travels back up through the callers until an
exceptcatches it; if nothing does, the program stops.
Each row below is one section of the lesson, with a short example:
| Section | Example | Result |
|---|---|---|
with | with StringIO("Orbit") as stream: | stream is closed on leaving the block |
__enter__, __exit__ | the Session class above | open, inside, close |
@contextmanager | a function with one yield | code before yield runs on entry, code after it on exit |
@asynccontextmanager | async with open_session("Orbit"): | opens and closes a session, with an await inside |
| Exception hierarchy | except OSError when opening a missing file | catches FileNotFoundError, a subclass |
try, except, else, finally | show_limit("Orbit") | Not a number, then Checked |
raise ... from err | raise RuntimeError(...) from err | the traceback keeps both the cause and the new error |
| Custom exceptions | raise ProjectNotFoundError(...) | the API returns 404 |
How some other languages compare
| Operation | JS / TS | Java | Go |
|---|---|---|---|
| Clean up a resource | Call cleanup in finally | try with a resource that closes automatically | Schedule cleanup with defer |
| Handle an error | catch and check the error's type | catch by exception type | Return an error for the caller to check |
with and resource cleanup
The parts of with StringIO("Orbit") as stream:
| Part | Meaning |
|---|---|
with | Enter the block through a context manager |
StringIO("Orbit") | Create an in-memory text stream containing "Orbit" |
as stream | Bind stream to the value returned by the entry step |
: | Open the indented block |
from io import StringIO
with StringIO("Orbit") as stream:
print(stream.read())
# prints: Orbit
print(stream.closed)
# prints: True
After the block, the name stream is still bound. The stream is closed, so stream.closed is True. A file opened with open() also closes when its with block ends.
Write a context manager as a class
These two dunder methods let a class work with with. The example uses OrbitStream to close a text stream on exit.
| Part | Meaning |
|---|---|
class OrbitStream: | Define a class whose objects can be used with with |
__enter__(self) | Run on entry. Bind its return value to the name after as |
__exit__ | Run on exit once __enter__ has returned successfully |
exc_type, exc, tb | Exception type, exception object, and traceback. All three are None when the block exits without an exception |
return False | Let the exception, if any, keep propagating |
In this example, int() tries to convert text to an integer. The text "Orbit" raises a ValueError. Cleanup prints True before Python reports the error.
from io import StringIO
class OrbitStream:
def __enter__(self):
self.stream = StringIO("Orbit")
return self.stream
def __exit__(self, exc_type, exc, tb):
self.stream.close()
print(self.stream.closed)
# prints: True
return False
with OrbitStream() as stream:
int(stream.read())
# error: ValueError: invalid literal for int() with base 10: 'Orbit'
Write a context manager with yield
The parts of open_text(text) with @contextmanager
| Part | Meaning |
|---|---|
@contextmanager | Turn a generator function into a function that creates a context manager |
try: | Open the part guarded by the cleanup step |
yield stream | Pass the stream to as stream and pause the function |
finally: | Run cleanup when the block exits |
from contextlib import contextmanager
from io import StringIO
@contextmanager
def open_text(text):
stream = StringIO(text)
try:
yield stream
finally:
stream.close()
with open_text("Orbit") as stream:
print(stream.read())
# prints: Orbit
print(stream.closed)
# prints: True
Asynchronous context managers
Define the function with async def, put yield in its body, and wrap it with @asynccontextmanager. Use async with when setup or cleanup needs to wait for an asynchronous operation, such as closing a database session. asyncio.run(main()) runs an async function from ordinary code.
import asyncio
from contextlib import asynccontextmanager
@asynccontextmanager
async def open_session(name):
print(f"Opening session {name}")
try:
yield name
finally:
await asyncio.sleep(0) # stands in for an operation that must be awaited
print(f"Closing session {name}")
async def main():
async with open_session("Orbit") as session:
print(f"Using session {session}")
asyncio.run(main())
# prints:
# Opening session Orbit
# Using session Orbit
# Closing session Orbit
The exception hierarchy
| Type | Where it sits | When it comes up |
|---|---|---|
BaseException | Root of the hierarchy | Base class of every exception |
Exception | Branch under BaseException | Covers most application errors |
KeyboardInterrupt, SystemExit | Under BaseException, outside Exception | Ctrl+C interruption or a request to exit |
ValueError | Under Exception | Invalid value, such as text with letters passed to int() |
TypeError | Under Exception | Wrong type for an operation, such as adding a string and an integer |
KeyError | LookupError branch under Exception | Looking up a missing dict key |
FileNotFoundError | OSError branch under Exception | Opening a missing file for reading |
The example opens a file that does not exist. type(err).__name__ gets the class name of the error. issubclass(A, B) tells whether A is a subclass of B.
try:
open("missing-orbit.txt")
except OSError as err:
print(type(err).__name__)
# prints: FileNotFoundError
print(issubclass(KeyError, LookupError))
# prints: True
print(issubclass(KeyboardInterrupt, Exception))
# prints: False
try, except, else, finally
The parts of the conversion in show_limit(raw)
| Part | Meaning |
|---|---|
try: | Run limit = int(raw) |
except ValueError: | Handle a ValueError from the conversion |
else: | Print limit when the try block runs to completion |
finally: | Print Checked when leaving the try statement |
def show_limit(raw):
try:
limit = int(raw)
except ValueError:
print("Not a number")
else:
print(limit)
finally:
print("Checked")
show_limit("3")
# prints:
# 3
# Checked
show_limit("Orbit")
# prints:
# Not a number
# Checked
With "3", else prints 3. With "Orbit", except prints Not a number. Both calls print Checked at the end. An early exit from try, such as return, also skips else. The finally block still runs when an exception goes uncaught.
Keep the cause with raise from
The parts of raising a new error while reading configuration
| Part | Meaning |
|---|---|
except ValueError as err: | Catch ValueError and bind the exception object to err |
raise | Raise an exception |
RuntimeError | New exception type, used here to report that the program could not read its settings |
from err | Set err as the direct cause of the new exception |
raw_limit = "Orbit"
try:
limit = int(raw_limit)
except ValueError as err:
raise RuntimeError("Invalid retry limit") from err
# error: RuntimeError: Invalid retry limit
The traceback shows the original exception first, followed by the new one. These are the key lines from the run:
ValueError: invalid literal for int() with base 10: 'Orbit'
The above exception was the direct cause of the following exception:
RuntimeError: Invalid retry limit
Map an exception to an HTTP error
The parts of the ProjectNotFoundError declaration
| Part | Meaning |
|---|---|
ProjectNotFoundError | Class name after the class keyword |
(Exception) | Inherit from Exception |
pass | Give the class a valid body when it needs no extra behaviour |
get_project() looks up a project. project_response() maps the outcome to an HTTP status at the API boundary. The example calls the functions directly with project 1, named "Orbit", and project 2, which is missing.
class ProjectNotFoundError(Exception):
pass
def get_project(project_id):
if project_id == 1:
return {"name": "Orbit"}
raise ProjectNotFoundError("Project not found")
def project_response(project_id):
try:
return 200, get_project(project_id)
except ProjectNotFoundError as err:
return 404, {"detail": str(err)}
status, body = project_response(1)
print(status)
# prints: 200
print(body["name"])
# prints: Orbit
status, body = project_response(2)
print(status)
# prints: 404
print(body["detail"])
# prints: Project not found
Key takeaways
withcalls__enter__on entry and__exit__on exit after successful entry.- With
@contextmanager, set up beforeyieldand clean up infinally. - Catch an exception type the code can handle. Put success-only work in
else. raise ... from errshows both the original cause and the new error in the traceback.- Use a custom exception to report an application error. Map it to an HTTP status at the API boundary.
Sources
- The execution rules for
withand the clauses oftry. Python Language Reference (opens in a new tab) - In-memory text streams and writing context managers. Python io (opens in a new tab), Python contextlib (opens in a new tab)
- Exception hierarchy, chaining and custom exceptions. Python Built-in Exceptions (opens in a new tab), Python Errors and Exceptions (opens in a new tab)
- Mapping application errors to responses at the API boundary. FastAPI Handling Errors (opens in a new tab), HTTP 404 (opens in a new tab)
- Error handling and cleanup in other languages. MDN try...catch (opens in a new tab), Java Catch Blocks (opens in a new tab), Java Try-with-resources (opens in a new tab), Go defer (opens in a new tab), Effective Go (opens in a new tab)
- Every Python example in this lesson was run on Python 3.11.9.
