Skip to content
Fullstack Launchpad

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.

By Published Updated 9 min readPython for Engineers Switching Languages

Context managers and exceptions

What does this code print?

python
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__. with calls __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 except catches it; if nothing does, the program stops.

Each row below is one section of the lesson, with a short example:

SectionExampleResult
withwith StringIO("Orbit") as stream:stream is closed on leaving the block
__enter__, __exit__the Session class aboveopen, inside, close
@contextmanagera function with one yieldcode before yield runs on entry, code after it on exit
@asynccontextmanagerasync with open_session("Orbit"):opens and closes a session, with an await inside
Exception hierarchyexcept OSError when opening a missing filecatches FileNotFoundError, a subclass
try, except, else, finallyshow_limit("Orbit")Not a number, then Checked
raise ... from errraise RuntimeError(...) from errthe traceback keeps both the cause and the new error
Custom exceptionsraise ProjectNotFoundError(...)the API returns 404

How some other languages compare

OperationJS / TSJavaGo
Clean up a resourceCall cleanup in finallytry with a resource that closes automaticallySchedule cleanup with defer
Handle an errorcatch and check the error's typecatch by exception typeReturn an error for the caller to check

with and resource cleanup

The parts of with StringIO("Orbit") as stream:

PartMeaning
withEnter the block through a context manager
StringIO("Orbit")Create an in-memory text stream containing "Orbit"
as streamBind stream to the value returned by the entry step
:Open the indented block
python
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.

PartMeaning
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, tbException type, exception object, and traceback. All three are None when the block exits without an exception
return FalseLet 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.

python
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

PartMeaning
@contextmanagerTurn a generator function into a function that creates a context manager
try:Open the part guarded by the cleanup step
yield streamPass the stream to as stream and pause the function
finally:Run cleanup when the block exits
python
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.

python
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

TypeWhere it sitsWhen it comes up
BaseExceptionRoot of the hierarchyBase class of every exception
ExceptionBranch under BaseExceptionCovers most application errors
KeyboardInterrupt, SystemExitUnder BaseException, outside ExceptionCtrl+C interruption or a request to exit
ValueErrorUnder ExceptionInvalid value, such as text with letters passed to int()
TypeErrorUnder ExceptionWrong type for an operation, such as adding a string and an integer
KeyErrorLookupError branch under ExceptionLooking up a missing dict key
FileNotFoundErrorOSError branch under ExceptionOpening 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.

python
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)

PartMeaning
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
python
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

PartMeaning
except ValueError as err:Catch ValueError and bind the exception object to err
raiseRaise an exception
RuntimeErrorNew exception type, used here to report that the program could not read its settings
from errSet err as the direct cause of the new exception
python
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:

text
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

PartMeaning
ProjectNotFoundErrorClass name after the class keyword
(Exception)Inherit from Exception
passGive 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.

python
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

  • with calls __enter__ on entry and __exit__ on exit after successful entry.
  • With @contextmanager, set up before yield and clean up in finally.
  • Catch an exception type the code can handle. Put success-only work in else.
  • raise ... from err shows 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