Academic Block

Python Context ManagersGet Certified

What Is a Context Manager?

Many things in a program must be set up before you use them and cleaned up afterward: a file has to be opened and closed, a network connection has to be connected and disconnected, and a lock has to be taken and released. If the cleanup step is skipped, for example because an error occurs in the middle, the program can leak resources, lose data, or even freeze. A context manager is an object that handles this setup and cleanup for you, and you use it with the with statement. The cleanup is guaranteed to run when the block ends, whether it ends normally, with a return, or with an exception.

  • The with statement: runs a block of code inside a managed “context”.
  • Setup and cleanup: the context manager prepares the resource before the block and releases it after the block.
  • __enter__ and __exit__: the two special methods that a class needs to work with with.
  • @contextmanager: a decorator from contextlib that turns a generator into a context manager.
  • Exception control: a context manager can let an exception pass or suppress it.
  • Built-in helpers: suppress(), redirect_stdout(), and many more.

The with Statement and Files

You have already used a context manager every time you wrote with open(...) as file:. The file object returned by open() is a context manager, so Python closes the file automatically when the indented block ends. This is safer than calling file.close() yourself, because the close happens even when an exception interrupts the block. The name after as receives the value that the context manager hands out, which for a file is the file object itself. After the block, the variable still exists, but the file behind it is closed.

Try It: A File That Always Closes

Click Test My Code. Pay attention to the three values of file.closed, especially the last one, which is printed after an error.

What this code does: It writes a line to a file inside a with block and prints file.closed inside and after the block. It then reads the file in a second with block, raises an error on purpose in the middle of that block, catches it outside, and shows that the file was closed anyway.
with open("notes.txt", "w") as file:
    file.write("Visit Yellowstone\n")
    print(file.closed)

print(file.closed)

try:
    with open("notes.txt") as file:
        print(file.readline().strip())
        raise ValueError("Something went wrong")
except ValueError as error:
    print("Caught:", error)

print(file.closed)

Using Several Context Managers at Once

Real tasks often need more than one resource at the same time, such as a file to read from and a second file to write to. Instead of nesting two with statements, you can list several context managers in one statement, separated by commas. Python enters them from left to right and, when the block ends, exits them in the opposite order, so the last resource that was opened is the first one to be closed. This keeps the code flat and easy to read, and every resource is still cleaned up safely.

Try It: Making Name Badges

Click Test My Code. Add a fourth guest to the file and run it again to see another badge.

What this code does: It creates a guest list file with three names. A single with statement then opens the guest list for reading and a badge file for writing, and the loop turns each guest into a numbered badge line in capital letters. The program prints the badges and confirms that both files are closed.
with open("guests.txt", "w") as file:
    file.write("Olivia Parker\nLiam Johnson\nEmma Wilson\n")

with open("guests.txt") as source, open("badges.txt", "w") as target:
    for number, line in enumerate(source, start=1):
        target.write(f"Badge {number}: {line.strip().upper()}\n")

with open("badges.txt") as file:
    print(file.read(), end="")

print(source.closed, target.closed)

How It Works: __enter__ and __exit__

Behind the with statement are two special methods. When the block starts, Python calls the object’s __enter__() method, and whatever it returns is assigned to the name after as. When the block ends, for any reason, Python calls __exit__(), where you put the cleanup code. Any class that has these two methods is a context manager, so you can write your own for connections, locks, temporary files, or anything else that needs a reliable cleanup. The __exit__ method receives three arguments that describe an exception, or None values when everything went well.

  • __enter__(self) prepares the resource and usually returns self or the resource.
  • __exit__(self, exc_type, exc_value, traceback) cleans up. The three arguments describe the exception that ended the block, if any.
  • If __enter__ returns nothing, the name after as becomes None.
  • The as part is optional: you can write with Connection("x"): when you do not need the value.

Try It: A Class-Based Context Manager

Click Test My Code. Look at the order of the messages: the setup comes first, the work in the middle, and the cleanup last.

What this code does: It defines a Connection class with __enter__ and __exit__ methods that print messages. A with statement connects to a server, sends two messages inside the block, and disconnects automatically. A final print() shows that the program continued normally.
class Connection:
    def __init__(self, server):
        self.server = server

    def __enter__(self):
        print(f"Connecting to {self.server}")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print(f"Disconnecting from {self.server}")
        return False

    def send(self, message):
        print(f"Sending: {message}")

with Connection("Dallas data center") as conn:
    conn.send("Hello from Texas")
    conn.send("Second message")
print("Done")

Handling and Suppressing Exceptions in __exit__

The __exit__ method is more than a cleanup hook: it also decides what happens to an exception that occurred inside the block. If the block ended normally, the three arguments are all None. If an exception occurred, they hold its type, its value, and its traceback, so the method can inspect it, log it, or react to it. The return value of __exit__ then controls the outcome: returning a true value suppresses the exception, so the program continues after the with block, while returning a false value, or nothing at all, lets the exception continue to the caller. Suppress only the errors that you really intend to ignore.

Try It: Quiet Mode and Strict Mode

Click Test My Code. Change suppress=True to suppress=False in the first block and watch the program stop with an error.

What this code does: It defines a Guard context manager that reports how its block ended and returns a value that decides whether exceptions are suppressed. In quiet mode, a division by zero is swallowed and the program continues. In strict mode, a ValueError escapes and is caught outside. A normal run shows the path without any error.
class Guard:
    def __init__(self, label, suppress):
        self.label = label
        self.suppress = suppress

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type is None:
            print(f"{self.label}: finished normally")
        else:
            print(f"{self.label}: caught {exc_type.__name__} - {exc_value}")
        return self.suppress

with Guard("Quiet mode", suppress=True):
    print(10 / 0)
print("Program continues")

try:
    with Guard("Strict mode", suppress=False):
        int("abc")
except ValueError:
    print("ValueError escaped the with block")

with Guard("Normal run", suppress=False):
    pass

Writing Context Managers with contextlib.contextmanager

Writing a whole class with two special methods is a lot of work for a small task. The contextlib module offers a shortcut: the @contextmanager decorator turns a simple generator function into a context manager. Everything before the yield is the setup, the value after yield is what the name after as receives, and everything after the yield is the cleanup. Wrap the yield in try and finally, so that the cleanup runs even when the block raises an exception. This style is shorter, and most Python programmers use it for custom context managers.

  • Import it with from contextlib import contextmanager.
  • The function must yield exactly once.
  • Code before yield runs on entry, and code after it runs on exit.
  • Use try and finally around the yield to guarantee the cleanup.
  • An exception in the with block is raised again at the yield line inside the generator.

Try It: A Road Trip Context Manager

Click Test My Code. Notice that the cleanup message appears in both trips, even in the one that is interrupted.

What this code does: It uses the @contextmanager decorator to build a context manager from a generator. The setup packs the car, the yield hands the destination in capital letters to the block, and the finally clause always unpacks. The first trip completes normally, and the second one is interrupted by an error.
from contextlib import contextmanager

@contextmanager
def road_trip(destination):
    print(f"Packing the car for {destination}")
    try:
        yield destination.upper()
    finally:
        print("Unpacking the car")

with road_trip("Nashville") as place:
    print(f"Driving to {place}")

try:
    with road_trip("Denver"):
        raise RuntimeError("Flat tire")
except RuntimeError as error:
    print("Trip interrupted:", error)

Useful Built-in Context Managers

Python and its standard library already contain many ready-made context managers, so you often do not need to write your own. Files are the best known, but the contextlib module adds several handy ones. suppress() ignores the exceptions that you name, which is cleaner than an empty except block, and redirect_stdout() sends everything that print() writes into another object, which is useful for testing and capturing output. Other modules offer context managers as well, for example tempfile.TemporaryDirectory() for a folder that deletes itself and threading.Lock() for protecting shared data.

  • contextlib.suppress(ErrorType) ignores the named exceptions inside the block.
  • contextlib.redirect_stdout(target) sends printed text into target, such as an io.StringIO buffer.
  • contextlib.closing(obj) calls obj.close() at the end for objects that have a close() method but are not context managers.
  • contextlib.ExitStack() manages a variable number of context managers.
  • tempfile.TemporaryDirectory(), threading.Lock(), and decimal.localcontext() are examples from other modules.

Try It: suppress() and redirect_stdout()

Click Test My Code. Replace FileNotFoundError with ValueError and see what happens to the first block.

What this code does: It uses suppress() to delete a file that may not exist, without an error when it is missing. It then uses redirect_stdout() to capture the text of two print() calls in a buffer, and prints how many lines were captured and what the first one said.
import io
import os
from contextlib import suppress, redirect_stdout

with suppress(FileNotFoundError):
    os.remove("old_report.txt")
print("Cleanup finished")

buffer = io.StringIO()
with redirect_stdout(buffer):
    print("Hello from Seattle")
    print("This text is captured")

captured = buffer.getvalue()
print(len(captured.splitlines()), "lines captured")
print(captured.splitlines()[0])

Practical Pattern: Temporarily Changing a Setting

One of the best uses for context managers is to change something for a short time and be sure to put it back. You could change the theme of an app, the working folder of a program, or the number of decimal places of a calculation. Without a context manager, a forgotten reset, or an exception that jumps over it, would leave the change in place and cause strange bugs later. With a context manager, the old value is saved at the start and restored in a finally clause, so the program always returns to its previous state. Because each context manager restores only what it changed, they can be nested safely.

Try It: A Temporary Theme and Font Size

Click Test My Code. Follow the dictionary through the nested blocks and see how each change is undone in reverse order.

What this code does: It stores app settings in a dictionary and defines a context manager that changes one setting and restores the old value afterward. It switches the theme to dark, changes the font size inside that block, prints the settings at each level, and finally shows that everything is back to normal.
from contextlib import contextmanager

settings = {"theme": "light", "font_size": 12}

@contextmanager
def temporary(key, value):
    old_value = settings[key]
    settings[key] = value
    try:
        yield
    finally:
        settings[key] = old_value

print(settings["theme"])
with temporary("theme", "dark"):
    print(settings["theme"])
    with temporary("font_size", 18):
        print(settings)
print(settings)

Practical Pattern: Timing a Block of Code

Another popular use of a context manager is a timer. The __enter__ method records the start time, and the __exit__ method calculates how long the block took. You can then wrap any piece of code in a with Timer(): block to measure it, without cluttering the code that does the real work. Because the elapsed time depends on your computer, programs usually print it rounded or compare it with a limit. Here the example checks the time without printing the exact value, so that the output is the same every time.

  • time.perf_counter() is a high-resolution clock that is best suited for measuring short durations.
  • A timer class stores the start time in __enter__ and the elapsed time in __exit__.
  • The __exit__ method returns None here, which counts as false, so exceptions are not suppressed.
  • The timer object stays available after the block, so you can read its result.

Try It: A Timer That Measures a Calculation

Click Test My Code. Increase the range to 10_000_000 and run it again to see that the program still finishes.

What this code does: It defines a Timer class whose __enter__ method records the start time and whose __exit__ method stores the elapsed time. A with block adds up the first million numbers. The program prints the sum and two checks on the elapsed time, so that the output does not depend on the speed of your computer.
import time

class Timer:
    def __enter__(self):
        self.start = time.perf_counter()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.elapsed = time.perf_counter() - self.start

with Timer() as timer:
    total = sum(range(1_000_000))

print("Sum:", total)
print("Timer recorded a time:", timer.elapsed >= 0)
print("Finished in under 5 seconds:", timer.elapsed < 5)
Tip: Whenever you acquire something that must be released, such as a file, a connection, a lock, or a temporary change, reach for a context manager. For a quick custom one, write a generator with @contextmanager and put the cleanup in a finally clause. Keep the with block as short as possible, so that the resource is held for no longer than necessary.

Using Context Managers with User Input

Context managers are especially valuable in programs that react to user input, because the input can lead to errors that the programmer did not predict. A program might save a diary entry to a file, or move money between two accounts, and the cleanup or the undo step must happen no matter what the user typed. Wrapping the risky part in a context manager keeps the main code short and puts the safety logic in one place. Remember that input() returns text, so convert numbers with int() or float() before you use them in calculations.

Try It: A Travel Diary

The Program Input box is already filled with two lines: I visited the Lincoln Memorial and Washington. Click Run Code straight away, then write your own entry.

What this code does: It asks for a sentence and a city, and saves them in a file inside a with block. It then reads the file back in a second with block, collecting the lines in a list, and prints the list, a summary, and a check that the file was closed.
entry = input("Write one sentence about your day: ")
city = input("Which city are you in? ")

with open("diary.txt", "w") as file:
    file.write(f"Location: {city}\n")
    file.write(f"Entry: {entry}\n")

with open("diary.txt") as file:
    lines = [line.strip() for line in file]

print(lines)
print(f"Saved {len(lines)} lines for {city}")
print("File closed:", file.closed)

Try It: A Safe Money Transfer

The Program Input box is filled with 200. Click Run Code, then try 800, which is more than the checking account holds, and watch the transfer being cancelled.

What this code does: It stores two account balances in a dictionary and defines a context manager that saves a backup first. If a ValueError occurs inside the block, the context manager restores the backup, prints a message, and suppresses the error. The program moves the amount the user typed from checking to savings, and prints the final balances.
from contextlib import contextmanager

accounts = {"checking": 500.0, "savings": 1200.0}

@contextmanager
def safe_transfer():
    backup = accounts.copy()
    try:
        yield
    except ValueError as error:
        accounts.update(backup)
        print("Transfer cancelled:", error)

amount = float(input("Amount to move from checking to savings: "))
with safe_transfer():
    accounts["checking"] -= amount
    accounts["savings"] += amount
    if accounts["checking"] < 0:
        raise ValueError("Insufficient funds")
    print(f"Moved ${amount:,.2f}")

print(accounts)

Common Mistakes with Context Managers

Context managers are simple to use, but a few details trip up many students when they write their own. Most mistakes either skip the cleanup in some situations, or accidentally hide errors that you wanted to see. The list below covers the most frequent problems, and it is worth a quick read whenever a resource seems to stay open, or when an exception seems to disappear without a trace.

  • No try and finally around yield: in a generator-based context manager, the cleanup after the yield is skipped if the block raises an exception. Always wrap the yield.
  • Forgetting to return a value from __enter__: the name after as is then None. Return self or the resource.
  • Returning True from __exit__ by accident: this silently suppresses every exception. Return False or nothing unless you really want to suppress an error.
  • Yielding more than once: a generator-based context manager must yield exactly once, otherwise Python raises a RuntimeError.
  • Using a resource after the block: after with open(...) the file is closed, and reading from it raises a ValueError. Do all the work inside the block.
  • Wrong signature for __exit__: it must accept three arguments besides self: the exception type, value, and traceback.
  • Opening files without with: a plain open() can leave the file open when an error occurs. Prefer the with statement.
  • Suppressing too broadly: suppress(Exception) hides real bugs. Name the specific exceptions that you expect.

Key Takeaways

Context managers make cleanup automatic, and they are one of the features that make Python code short, safe, and readable. The points below summarize what you learned, and they prepare you for the next lesson on type hints, where you will learn to describe the kinds of values your code expects. Remember them whenever your program opens, locks, connects, or temporarily changes something.

  • The with statement runs setup before a block and guarantees cleanup after it, even when an exception occurs.
  • A class becomes a context manager by defining __enter__(), which prepares the resource, and __exit__(), which cleans up.
  • The value returned by __enter__() is what the name after as receives.
  • If __exit__() returns a true value, the exception is suppressed. Otherwise it continues.
  • The @contextmanager decorator builds a context manager from a generator with exactly one yield. Put the cleanup in a finally clause.
  • One with statement can manage several resources, and they are closed in the reverse order.
  • suppress(), redirect_stdout(), closing(), and ExitStack() are ready-made helpers in contextlib.

Frequently Asked Questions

These are the questions that students ask most often when they learn about context managers in Python. The answers are brief and practical, and each idea appears in one of the examples above. If something is still unclear, try writing a very small context manager that only prints a message on entry and on exit, and then raise an error inside the block to watch what happens.

What is a context manager in Python?

A context manager is an object that sets up a resource before a block of code and cleans it up afterward. You use it with the with statement. Files, locks, and database connections are common examples, and the cleanup runs even if an exception occurs inside the block.

Why should I use the with statement in Python?

The with statement guarantees that cleanup code runs when the block ends, whether it ends normally or because of an error. This prevents resource leaks such as files that stay open, and it is shorter and safer than writing try and finally by hand.

What do __enter__ and __exit__ do in Python?

The __enter__ method runs when the with block starts, and its return value is assigned to the name after as. The __exit__ method runs when the block ends. It receives the exception type, value, and traceback, which are all None when no error occurred, and it performs the cleanup.

How do I create a context manager with contextlib.contextmanager?

Import contextmanager from contextlib and decorate a generator function with it. Put the setup code before a single yield, put the cleanup in a finally clause after the yield, and yield the value that the as name should receive. The function then works with the with statement.

What happens if __exit__ returns True?

Returning True from __exit__ tells Python that the exception has been handled, so it is suppressed and the program continues after the with block. Returning False or None lets the exception continue to propagate. Suppress only the errors that you really intend to ignore.

Can I use multiple context managers in one with statement?

Yes. List them separated by commas, for example with open(“a.txt”) as source, open(“b.txt”, “w”) as target:. They are entered from left to right and exited in the reverse order. For a variable number of context managers, use contextlib.ExitStack.

What is contextlib.suppress used for?

The suppress function is a context manager that ignores the exceptions that you name inside its block, for example with suppress(FileNotFoundError): followed by os.remove(“old.txt”). It is shorter and clearer than a try and except block that does nothing.

What is the difference between try/finally and a context manager?

Both make sure that cleanup code runs. A try and finally block repeats the cleanup code at every place where you need it, while a context manager packages the setup and cleanup once, so you can reuse it with a short with statement. Context managers are therefore cleaner and less error-prone.

Ready for the next step?Learn how to describe the types of your variables, parameters, and return values.
Next: Type Hints & Annotations →