LevelJar Sign in

Python course / Advanced

Context managers

Put anything inside a with block that is guaranteed to be tidied up afterwards. Cleanup that only runs when nothing goes wrong is the bug you meet during an outage.

  • __enter__ and __exit__
  • contextlib
  • suppressing
  • ExitStack
  • temporary changes
  • all or nothing

Start this module

Runs in your browser. Start straight away; create an account when you want your progress kept.

a block that always tidies up
from contextlib import contextmanager


@contextmanager
def announced(name):
    print("start", name)
    try:
        yield {"name": name}
    finally:
        print("finish", name)


with announced("delivery") as job:
    print("working on", job["name"])

try:
    with announced("unpacking"):
        raise ValueError("a crate was empty")
except ValueError as failure:
    print("handled:", failure)
start delivery
working on delivery
finish delivery
start unpacking
finish unpacking
handled: a crate was empty

What you will learn

The lessons in this module

  • What with actually does
  • What as names, and what __exit__ is told
  • Swallowing exceptions, on purpose or by accident
  • Context managers from generators
  • The standard library's context managers
  • Several at once, and ExitStack
  • Changing something temporarily
  • A timer you can put around anything
  • Used once, used again, used inside itself
  • All or nothing
  • Capstone: a batch that survives its failures
  • Module review: stock in batches

Ready when you are

Start this module

Previous: Decorators. Next: Dataclasses and the data model. All modules are on the course page.