← Python lessons

Python Context Managers: Write Your Own with @contextmanager

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

A Python context manager runs set-up code before a with block and clean-up code after it. Write your own with @contextmanager from contextlib.

You need functions, for loops and reading a text file with with open(). This lesson shows how to write a context manager and in what order its code runs.

What a with block does

You have used with to read a file. open() sets the file up, the indented block uses it, and with closes the file when the block ends.

with open("notes.txt", "w", encoding="utf-8") as fixture:    fixture.write("Buy milk\n")with open("notes.txt", "r", encoding="utf-8") as source:    print(source.closed)print(source.closed)

The first two lines only make a file to read: "w" creates notes.txt and write() puts one line in it. A file's closed attribute is True once the file is closed. It prints False inside the block and True after it. Every with block works like this: something is set up, the block runs, something is cleaned up.

Write a context manager with @contextmanager

A context manager is what comes after with: it does the set-up and the clean-up. To write one, import contextmanager from contextlib and put @contextmanager on the line above a def. @contextmanager is a decorator: it turns the function below it into a context manager.

Inside the function, a line with just yield splits it in two. The code above yield runs before the block, the code below it runs after.

from contextlib import contextmanager@contextmanagerdef loading():    print("Loading...")    yield    print("Done")with loading():    print("Reading the level map")print("Ready to play")

This prints Loading..., the block's line, Done, then Ready to play. At yield the function pauses, the with block runs, then the function carries on. yield has a wider use in generators; here it only marks where the block runs.

Do not mix up the code below yield and the code below the with block. The code below yield is the clean-up: it runs as soon as the indented block ends. The unindented print() after the block is not part of the context manager, so it runs after the clean-up.

Use a context manager when the same set-up and clean-up go around different code. You write the pair once, and the clean-up is never forgotten. Write the brackets in with loading():, as in any call.

Note: without @contextmanager above the def, the with line fails with TypeError: 'generator' object does not support the context manager protocol. If you see that error, add the decorator line.

Give a context manager a parameter

A context manager can take a parameter like any function. Put the argument in the brackets after with. Code on both sides of yield can use it.

from contextlib import contextmanager@contextmanagerdef boxed(width):    print("=" * width)    yield    print("=" * width)with boxed(10):    print("High score")with boxed(3):    print("Ada")

"=" * width repeats = as many times as width says. So each block gets a border as wide as its argument: 10 = signs around High score, then 3 around Ada.

Nest with blocks

One with block can sit inside another. The outer manager sets up first; the inner one cleans up first.

from contextlib import contextmanager@contextmanagerdef level():    print("Level start")    yield    print("Level end")@contextmanagerdef music():    print("Music on")    yield    print("Music off")with level():    with music():        print("Collect the coins")print("Back to the menu")

The order is Level start, Music on, the block, Music off, Level end, then Back to the menu.

A with block inside a for loop is entered once per pass. Its set-up and clean-up run around every item.

from contextlib import contextmanager@contextmanagerdef turn():    print("Start turn")    yield    print("End turn")for player in ["Ada", "Sam"]:    with turn():        print(player, "rolls the dice")

Start turn and End turn are printed twice, once around each player's line.

This lesson leaves out two things: handing a value to the block with as, and errors. If the block raises an error, the code after yield does not run. The lesson Python try finally: Cleanup Code That Always Runs shows how to make it run anyway.

See also: Python Decorators Explained, Python Generators and yield, Python Read File.

Your turn

Write a context manager oven() that prints Oven on before its block and Oven off after it. Use it so the program prints the lines below.

🎯 Goal — make it print exactly:
Oven on
Bake the bread
Oven off
Lunch is ready
from contextlib import contextmanager# write oven() with @contextmanager# then print Bake the bread inside a with oven(): block, and Lunch is ready after the block