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
withstatement: 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 withwith.@contextmanager: a decorator fromcontextlibthat 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.
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)with statement opens notes.txt and stores the file object in file. The file is closed automatically when the indented block ends.False.True.try block lets the program continue afterward.with block opens the file for reading. The name file now refers to this new file object.readline() reads one line, and strip() removes the line break. The output is Visit Yellowstone.with block at once, and the context manager closes the file on the way out.with statement catches the ValueError.Caught: Something went wrong.True.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.
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)guests.txt is created and opened inside a with block.guests.txt for reading as source and badges.txt for writing as target. A comma separates the two. Python closes them in the reverse order when the block ends.enumerate() numbers the lines starting from 1, while the loop reads the guest list one line at a time.strip() removes the line break and upper() makes the name uppercase. Each badge is written to the second file.with block opens the file that was just written.Badge 1: OLIVIA PARKER, Badge 2: LIAM JOHNSON, and Badge 3: EMMA WILSON. The argument end="" avoids an extra blank line.source and target still exist after the block, and both files were closed. The output is True True.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 returnsselfor 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 afterasbecomesNone. - The
aspart is optional: you can writewith 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.
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")Connection will behave like a context manager, because it will have the two special methods.with block starts.Connecting to Dallas data center.self means that the name after as will refer to this connection object.Disconnecting from Dallas data center.False means that any exception continues on its way. There is no exception in this example.send() is a normal method that the block can use while the connection is open.__enter__(), and stores the returned object in conn.Sending: Hello from Texas.Sending: Second message. When this line finishes, Python calls __exit__(), which prints the disconnect message.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.
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):
passGuard is a context manager that watches how its block ends.suppress.None, the block ended without an error.Normal run: finished normally.Quiet mode: caught ZeroDivisionError - division by zero.self.suppress. True swallows the exception, and False lets it continue.suppress=True. No name is needed after as, so it is left out.ZeroDivisionError. __exit__() reports it and returns True, so the exception is swallowed.Program continues.suppress=False."abc" is not a number, so int() raises a ValueError. __exit__() reports it, and the message is Strict mode: caught ValueError - invalid literal for int() with base 10: 'abc'. Because it returns False, the error continues.with statement catches the ValueError.ValueError escaped the with block.None.pass does nothing, and the output is Normal run: finished normally.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
yieldexactly once. - Code before
yieldruns on entry, and code after it runs on exit. - Use
tryandfinallyaround theyieldto guarantee the cleanup. - An exception in the
withblock is raised again at theyieldline 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.
@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)contextmanager comes from the contextlib module.@contextmanager turns the generator function below into a context manager.yield, which makes it a generator.yield is the setup. It runs when the with block starts.try block wraps the yield, so that the finally part is guaranteed to run.yield pauses the function and gives the destination in capital letters to the name after as. The with block runs while the function is paused here.Unpacking the car.Packing the car for Nashville, and then stores "NASHVILLE" in place.Driving to NASHVILLE. When the block ends, the cleanup runs and prints Unpacking the car.Packing the car for Denver. No as name is used here, because the value is not needed.yield line inside the generator, so the finally clause runs and prints Unpacking the car. The error then continues outward.RuntimeError.Trip interrupted: Flat tire.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 intotarget, such as anio.StringIObuffer.contextlib.closing(obj)callsobj.close()at the end for objects that have aclose()method but are not context managers.contextlib.ExitStack()manages a variable number of context managers.tempfile.TemporaryDirectory(),threading.Lock(), anddecimal.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.
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])io module provides StringIO, an object that behaves like a file but keeps its text in memory.os module provides os.remove(), which deletes a file.suppress and redirect_stdout are context managers from contextlib.suppress(FileNotFoundError) ignores that one kind of exception inside the block, and any other exception would still be raised.old_report.txt does not exist, so os.remove() raises a FileNotFoundError. The context manager swallows it.Cleanup finished.io.StringIO() creates an in-memory text buffer that can receive printed text.print() writes into the buffer and not onto the screen.getvalue() returns everything that was written into the buffer as one string.print() works normally again. The output is 2 lines captured.splitlines()[0] is the first captured line. The output is Hello from Seattle.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.
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)contextmanager will turn a generator into a context manager.settings is a dictionary with a theme and a font size.try block guarantees that the finally clause will run.yield pauses the function while the code of the with block runs.light."dark".dark.{'theme': 'dark', 'font_size': 18}. When the inner block ends, the font size is restored to 12.{'theme': 'light', 'font_size': 12}.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 returnsNonehere, 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.
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)time module provides perf_counter().Timer has no initializer, because it needs no setup values.with block starts.time.perf_counter() returns the current reading of a precise clock, in seconds. It is saved in self.start.as.timer refers to it.total, and then the timer stops.Sum: 499999500000.elapsed attribute is zero or more. The output is Timer recorded a time: True.Finished in under 5 seconds: True.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@contextmanagerand put the cleanup in afinallyclause. Keep thewithblock 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.
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)I visited the Lincoln Memorial, is stored as text.Washington, is stored as text.with statement opens diary.txt and guarantees that it is closed afterward.with block opens the same file for reading.strip().['Location: Washington', 'Entry: I visited the Lincoln Memorial'].Saved 2 lines for Washington.File closed: True.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.
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)contextmanager will turn the generator into a context manager.accounts is a dictionary with a balance for checking and for savings.safe_transfer() needs no parameters, because it protects whatever happens inside its block.copy() saves the balances as they are before the transfer starts.try block lets the function react to errors from the with block.yield pauses the function while the transfer code runs. If the block raises an exception, Python raises it again at this line.ValueError that came from the block.200 is converted to the number 200.0.ValueError, and the context manager rolls everything back.Moved $200.00.{'checking': 300.0, 'savings': 1400.0}. For an amount of 800, the balances would be back at {'checking': 500.0, 'savings': 1200.0}.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
tryandfinallyaroundyield: in a generator-based context manager, the cleanup after theyieldis skipped if the block raises an exception. Always wrap theyield. - Forgetting to return a value from
__enter__: the name afterasis thenNone. Returnselfor the resource. - Returning
Truefrom__exit__by accident: this silently suppresses every exception. ReturnFalseor nothing unless you really want to suppress an error. - Yielding more than once: a generator-based context manager must
yieldexactly once, otherwise Python raises aRuntimeError. - Using a resource after the block: after
with open(...)the file is closed, and reading from it raises aValueError. Do all the work inside the block. - Wrong signature for
__exit__: it must accept three arguments besidesself: the exception type, value, and traceback. - Opening files without
with: a plainopen()can leave the file open when an error occurs. Prefer thewithstatement. - 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
withstatement 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 afterasreceives. - If
__exit__()returns a true value, the exception is suppressed. Otherwise it continues. - The
@contextmanagerdecorator builds a context manager from a generator with exactly oneyield. Put the cleanup in afinallyclause. - One
withstatement can manage several resources, and they are closed in the reverse order. suppress(),redirect_stdout(),closing(), andExitStack()are ready-made helpers incontextlib.
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.