Skip to content
dreamcode
dreamcode
Map
Context managers
Lesson 53 of 77
+15 XP on finish
PYTHON ADVANCEDChapter 9 · Python Advanced

Context managers

A context manager sets something up and guarantees it gets cleaned up, even if an error happens halfway through. with open(...) as f: closes the file for you. Write your own with a class that has __enter__ and __exit__, or more simply with @contextmanager from contextlib around a generator: the code before yield is setup, and the code after it is cleanup.

Worked example

How it reads

  • Everything before yield runs when the with block starts
  • The yielded value becomes the name after as
  • finally makes sure the cleanup runs even if the block raises
Cloud tip: Reach for a context manager whenever something must be undone: closing files, releasing locks, restoring settings.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Write a context manager indented() with @contextmanager that prints { before the block and } after it, then use it so the program prints {, hello and } on three lines.

Press Run to check your work.