Skip to contentSkip to navigation

Module 14 · Lesson 02

Context Managers and the with Statement

Guarantee clean-up with the with statement: how __enter__ and __exit__ work, what happens on an error, writing managers as classes or with contextlib.contextmanager, and the ready-made ones in contextlib.

  • About 9 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • with and a file
  • Enter and exit, step by step
  • Write one with contextmanager
  • Watch the clean-up run

Set up, then always clean up

A with block runs your code between a set-up step and a clean-up step that is guaranteed to happen.

  • with

    with open(...) as f: closes the file when the block ends, even after an error.

  • __enter__

    Runs at the start. What it returns is the name after as.

  • __exit__

    Runs at the end, every time, and is told about any error.

  • contextmanager

    A generator with one yield, plus @contextmanager, makes a manager.

Clean-up everywhere

Anything you must hand back afterwards is a good fit for a with block.

  • ConnectionsClose the network connection when the download ends, or when it fails.
  • Lockswith lock: lets one thread at a time into a block, and always lets go.
  • Temporary folderstempfile.TemporaryDirectory() deletes its folder when the block ends.
  • Database savesKeep the changes if the block worked, undo them if it failed.

Reading a with line

This line opens a file for writing, inside a managed block. Tap each part to see its job.

Part 1 of 6

Tap any part of the code below, or press Next.1 of 6 explored

with:Starts a managed block. Clean-up is promised when the block ends.

Blocks that clean up after themselves

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6with and a file

The file is open inside the block and closed straight after it.

Your turn: Write a second line to the diary, then read both back.

Python
with open("diary.txt", "w") as f:
    f.write("Dear diary\n")
    print("inside, closed?", f.closed)
print("after, closed?", f.closed)

with open("diary.txt") as f:
    print(f.read())
Output
Press Run to see what it prints.

Watch set-up and clean-up run

Press Step to run one line at a time. Watch the names box change.

Ready. Press Step to run the first line.

  1. from contextlib import contextmanager
  2. @contextmanager
  3. def visit(place):
  4. print("arrive at", place)
  5. yield place.upper()
  6. print("leave", place)
  7. with visit("park") as p:
  8. print("enjoying the", p)
  9. print("home")

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.What kind of object is f?

with open("a.txt", "w") as f:
    pass
print(type(f).__name__)

0 of 6 answered

Common with misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

What with guarantees

You met with when reading files:

Try it 1: edit me, then Run
with open("notes.txt", "w") as f:
    f.write("hello")
# the file is closed here, even if write() had failed
Output
Press Run to see what it prints.

The promise is simple: when the indented block ends, for any reason (it finished normally, it hit return or break, or an exception was raised), the clean-up runs. Without with you would need try and finally:

Try it 2: edit me, then Run
f = open("notes.txt", "w")
try:
    f.write("hello")
finally:
    f.close()
Output
Press Run to see what it prints.

with is the shorter and safer form of that pattern. The object after with is a context manager: any object that knows how to set up and how to clean up.

The protocol: enter and exit

A context manager is an 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_value, traceback) runs when the block ends, every time.
Try it 3: edit me, then Run
class Section:
    def __init__(self, title):
        self.title = title

    def __enter__(self):
        print(f"== {self.title} ==")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print(f"== end of {self.title} ==")
        return False

with Section("Report") as s:
    print("inside", s.title)
Output
Press Run to see what it prints.

This prints the opening line, then inside Report, then the closing line. __enter__ often returns self, but it can return anything useful: open() returns the file object, and a database connection might return a cursor.

When the block raises

If an exception escapes the block, Python still calls __exit__, and passes it details of the problem: the exception's class, the exception object and a traceback. If the block finished normally, all three are None.

The value __exit__ returns decides what happens next:

  • False or None (the normal case): the exception carries on travelling up to the caller, after the clean-up has run.
  • True: the exception is suppressed, as if it never happened, and the program continues after the with block.

Suppressing is rarely what you want. A manager that returns True hides every error, including bugs you would need to see. Return False unless the manager exists specifically to handle one kind of error, and then check exc_type first.

Try it 4: edit me, then Run
class Ignore:
    def __init__(self, error_type):
        self.error_type = error_type
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_value, traceback):
        return exc_type is not None and issubclass(exc_type, self.error_type)
Output
Press Run to see what it prints.

The generator shortcut: contextmanager

Writing a class is clear but long. The contextlib module turns a generator function into a context manager with a decorator:

Try it 5: edit me, then Run
from contextlib import contextmanager

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

with section("Report") as name:
    print("inside", name)
Output
Press Run to see what it prints.

Everything before yield is the setup, like __enter__. The yielded value goes to the as name. Everything after yield is the clean-up, like __exit__. If the block raises, the exception reappears at the yield line inside the generator. That is why the clean-up belongs in a finally: without it, an error in the block skips the clean-up entirely, which defeats the point of a context manager. The decorator and the yield come from the decorators and generators lessons, used together.

Ready-made managers

You do not have to write everything yourself. Some useful ones:

  • open(...) closes the file.
  • contextlib.suppress(FileNotFoundError) ignores exactly the listed exception types, a clear, deliberate version of "it is fine if this fails".
  • contextlib.redirect_stdout(buffer) temporarily sends print output somewhere else, handy in tests.
  • Locks from threading, database connections and many library objects support with.
Try it 6: edit me, then Run
import contextlib, os

with contextlib.suppress(FileNotFoundError):
    os.remove("old-cache.tmp")    # fine if it was never there
Output
Press Run to see what it prints.

Several managers at once

One with can hold several managers, separated by commas. They are entered left to right and exited in the reverse order, like closing nested boxes from the inside out:

Try it 7: edit me, then Run
with open("in.txt") as source, open("out.txt", "w") as target:
    target.write(source.read().upper())
Output
Press Run to see what it prints.

Long lists of managers can be wrapped in brackets across several lines.

Choosing a style

Use a class when the manager has state or methods the block uses, such as a timer you can ask for its elapsed time, or when you want explicit control over exceptions in __exit__. Use @contextmanager for short setup and clean-up pairs: it reads top to bottom and needs only a try, a yield and a finally. In both styles the rule is the same: whatever happens in the block, the clean-up runs.

Syntax

The general shape of the statements in this lesson.

syntax.py
with manager as value:       # value = manager.__enter__()
    ...                       # manager.__exit__(...) always runs

class Manager:
    def __enter__(self):
        return self           # what "as" receives
    def __exit__(self, exc_type, exc_value, tb):
        return False          # False: let errors through

from contextlib import contextmanager, suppress

@contextmanager
def manager():
    # setup
    try:
        yield value           # the block runs here
    finally:
        pass                  # clean-up, even on errors

with suppress(KeyError):      # ignore exactly KeyError
    ...

with a() as x, b() as y:      # enter a, b; exit b, a
    ...
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

An undo-able change to a shopping basket

Beginner

Write a context manager class Transaction for a dictionary of stock. Changes made inside the block are kept if the block finishes, and undone if it raises. Show one successful order and one that fails halfway.

Python
class Transaction:
    def __init__(self, data):
        self.data = data

    def __enter__(self):
        self.backup = dict(self.data)
        return self.data

    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type is not None:
            self.data.clear()
            self.data.update(self.backup)
            print("rolled back:", exc_value)
        return False

stock = {"mug": 5, "lamp": 2}

with Transaction(stock) as s:
    s["mug"] -= 2
print("after order 1:", stock)

try:
    with Transaction(stock) as s:
        s["mug"] -= 1
        if s["lamp"] < 3:
            raise ValueError("not enough lamps")
        s["lamp"] -= 3
except ValueError:
    print("order 2 refused")
print("after order 2:", stock)
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

__enter__ saves a copy and hands the real dictionary to the block. When the block raises, __exit__ restores the copy, so the mug taken before the failure comes back. Returning False lets the ValueError carry on to the caller, which reports that the order was refused.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

No finally in a contextmanager

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
from contextlib import contextmanager

@contextmanager
def connected():
    print('connect')
    yield
    print('disconnect')

try:
    with connected():
        raise ValueError('bad query')
except ValueError:
    print('error handled')
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints connect and error handled, but never disconnect

Write this instead

from contextlib import contextmanager

@contextmanager
def connected():
    print('connect')
    try:
        yield
    finally:
        print('disconnect')

try:
    with connected():
        raise ValueError('bad query')
except ValueError:
    print('error handled')

Why it happens

The error is raised again at the yield, so the lines after it are skipped.

In the real world

Where this shows up in software people use every day.

  1. Capturing output in a test

    Software testing

    A team tests a command-line report function that prints its results. Their test needs to check exactly what was printed, and must also prove that a temporary working folder is always removed afterwards. Two context managers from the standard library and one of their own handle it.

    Why Python fits

    redirect_stdout sends the report's prints into a StringIO buffer for the length of the block, so the test can inspect them. The home-made scratch_folder manager creates a temporary folder and removes it in finally. Both are entered on one with line and exited in reverse order, and the checks after the block run on normal output again.

    Python
    import contextlib, io, os, shutil, tempfile
    
    def print_report(rows):
        for name, total in rows:
            print(f"{name:<6}{total:>6}")
    
    @contextlib.contextmanager
    def scratch_folder():
        path = tempfile.mkdtemp()
        try:
            yield path
        finally:
            shutil.rmtree(path)
    
    buffer = io.StringIO()
    with scratch_folder() as folder, contextlib.redirect_stdout(buffer):
        print_report([("north", 120), ("south", 95)])
        with open(os.path.join(folder, "report.txt"), "w") as f:
            f.write("saved")
    
    printed = buffer.getvalue().splitlines()
    print("captured lines:", printed)
    print("first line correct:", printed[0] == "north    120")
    print("folder removed:", not os.path.exists(folder))
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Do I still need try and except inside a with block?

Yes, if you want to handle the error. The with statement guarantees clean-up, not recovery. An exception still travels to the caller unless something catches it.

Can a with block return a value from a function?

Yes. return inside a with block works normally, and the manager's clean-up runs before the function actually returns.

Is a context manager reusable?

It depends. Many class-based managers can be entered again, but a manager made with @contextmanager is a generator, so it can be used for only one with block. Call the function again for a new one.

What does the as part do if __enter__ returns None?

The name simply becomes None. You can also leave out as entirely when the block does not need the value, as in with suppress(KeyError):.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/2 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 19 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.