LearnPy Hub
AdvancedAdvancedLesson 22 of 32

Context Managers

Watch the ideawith: set up, use, clean up
with open("data.txt") as f:
    text = f.read()
enter: open
your block
exit: close

Entering the with block runs the setup: here, opening the file.

1Level 1 · BasicsBasics

You've already met with open(...) as f:. The with statement uses a context manager: an object that sets something up at the start of a block and always cleans it up at the end, even if an error happens. In this lesson you'll learn how that works and how to write your own.

The problem with

Many resources must be released when you're done: files must be closed, database connections returned, locks released, temporary settings restored. Doing it by hand is easy to forget, and an exception can skip your clean-up line:

f = open("data.txt", "w")
f.write(compute())   # if this raises an error...
f.close()            # ...this never runs

The with version closes the file no matter what:

with open("data.txt", "w") as f:
    f.write(compute())

How it works

A context manager is any object with two special methods:

  • __enter__(self) runs when the block starts. Whatever it returns is assigned to the name after as.
  • __exit__(self, exc_type, exc, tb) runs when the block ends, normally or because of an exception. If it returns True, the exception is swallowed; otherwise it carries on as usual.

The easy way: contextlib.contextmanager

Instead of writing a class, write a generator with a single yield. Code before the yield is the set-up; code after it, inside finally, is the clean-up:

from contextlib import contextmanager

@contextmanager
def section(title):
    print("==", title)
    try:
        yield
    finally:
        print("== end of", title)

Handy ready-made ones

  • contextlib.suppress(FileNotFoundError) ignores one specific error.
  • contextlib.redirect_stdout(buffer) captures printed output.
  • Several managers in one with: with open("a") as a, open("b") as b:
Key points: with guarantees clean-up; a context manager has __enter__ and __exit__; __exit__ runs even after an exception; @contextmanager with a single yield is the quick way to write one.

See it in actionEnter, run, exit

__enter__ runs at the start of the with block and __exit__ at the end. Follow the output.

Step-by-step

Try it yourselfExample 1: Clean-up happens even after an error

The file is closed even though the block raised an exception.

example_1.py
Output appears here
Fill in the blanks

Close it for me

Fill the blanks so the file is closed automatically and the program prints True.

blanks.py
 open("cm.txt", "w")  f:
    f.write("hi")
print(f.closed)

Example 2: Writing a context manager class

__enter__ runs at the start and __exit__ at the end, with details of any error.

example_2.py
Output appears here
Fill in the blanks

Enter and exit

Fill the blanks so the class works with with and prints start, work, stop.

blanks.py
class Step:
    def (self):
        print("start")
        return self
    def (self, *exc):
        print("stop")

with Step():
    print("work")
Your turn

Count the blocks

Write a class Counter whose __enter__ adds 1 to self.n. Use the same counter in two with blocks, then print 2.

my_code.py

Example 3: A timer with @contextmanager

Everything before yield is set-up; the finally part is clean-up.

example_3.py
Output appears here
Fix the bug

Missing yield

This context manager should print begin, inside, end, but it crashes. Fix it.

buggy.py

Example 4: suppress and redirect_stdout

Two ready-made context managers from contextlib.

example_4.py
Output appears here
Your turn

Ignore a missing key

Use contextlib.suppress so looking up a missing key doesn't crash. The program should print still running.

my_code.py

2Level 2 · IntermediateSeveral resources and ready-made managers

Several in one with

with open("in.txt") as src, open("out.txt", "w") as dst: opens both and closes both, even if something goes wrong in between.

Temporary changes

A context manager is perfect for "change something, then put it back": switch to another folder, change a setting, start a timer. The finally part restores things.

Ready-made ones

tempfile.TemporaryDirectory() gives a folder that deletes itself; decimal.localcontext() changes precision temporarily; contextlib.suppress(FileNotFoundError) ignores one error type.

See it in actionEnter and exit around the block

Watch __enter__ run before the block and __exit__ after it, even with the error.

Step-by-step

Example 5: Copy, temp folders and temporary settings

The temp folder disappears and the decimal precision goes back to normal.

example_5.py
Output appears here

3Level 3 · AdvancedExitStack, suppress and transactions

What __exit__ receives

__exit__(self, exc_type, exc, tb) gets the error (or three Nones). Returning True swallows the error; returning nothing lets it continue. A transaction manager uses this: commit if no error, roll back if there was one.

ExitStack

When you don't know in advance how many files to open, contextlib.ExitStack lets you add managers in a loop and closes all of them at the end.

suppress

with contextlib.suppress(FileNotFoundError): ignores one expected error type for a block, a tidy replacement for an empty try/except. (The Async Basics lesson shows async with, the asynchronous twin of with.)

Example 6: A transaction that rolls back on error

The second transfer fails halfway, so both balances go back.

example_6.py
Output appears here

Example 7: ExitStack and suppress

ExitStack closes however many files were opened; suppress quietly skips the expected FileNotFoundError.

example_7.py
Output appears here
Good practiceIn a @contextmanager function, put the clean-up after yield inside finally:. Otherwise an exception in the with block skips your clean-up, which is the very thing context managers exist to prevent.
Exercise · predict the output

What does this print?

class M:
    def __enter__(self):
        print("in", end=" ")
        return 5
    def __exit__(self, *args):
        print("out")
with M() as x:
    print(x, end=" ")
Quick quiz · 5 questions
1. What is the main job of a context manager?
2. Which two methods make an object a context manager?
3. Does __exit__ run if the with block raises an exception?
4. In with open("a.txt") as f, what is f?
5. How many yield statements does a @contextmanager function normally have?
Ready to practice context managers?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python Context Managers · LearnPy Hub