
Python context managers clean up your messy file operations automatically so your code never crashes from open leaks. If you ever forgot to close a file after writing to it, your program kept holding onto that file in secret memory. A context manager fixes this by setting up your work and sweeping the floor clean the second you finish.
When you open a resource in Python, you must shut it down when done. The easiest way to handle this safety step every single time is using the built-in with statement keyword. It runs setup steps before your code starts and handles cleanup steps right after, even if your code hits a big error along the way.
What Is a Python Context Manager?
Imagine you borrow a wrench from a busy workshop. You need to use the tool, but you also need to return it to the rack when you finish. If you drop it on the floor and walk away, the next person gets stuck. A context manager is like a helpful friend standing next to you who puts the tool right back on the wall the moment you stop using it.
In Python code, resources mean things like text files, network links, or database connections. Your computer only gives your script a fixed number of these handles at one time. If your program opens 500 files and forgets to close them, your operating system will run out of space and crash your script.
Here is what old, unsafe code looks like when opening a basic file:
file = open("notes.txt", "w")
file.write("Hello world")
# If the program breaks right here, the file stays open forever!
file.close()
If an error happens on the line where you write text, the program stops right away. It never reaches the file.close() line. That file handle stays stuck open in your system memory. You can read about how memory leaks ruin long scripts in our detailed guide on Python Generators: How to Save Memory With Lazy Loops.

How Do You Use the With Statement in Python?
You write context managers in Python by placing the keyword with before your resource call. Python handles the open action, gives you a variable name to work with, and guarantees the close action will run later.
Look at how clean the exact same file action becomes when you use the with block:
with open("notes.txt", "w") as file:
file.write("Hello world")
# The file closes right here automatically!
Notice how the code is indented under the with line. That indented zone is your safe work room. The moment your code steps out of that indented block, Python closes the file. It does not matter if your code finishes smooth or explodes with an error. The cleanup happens no matter what.
Last week I ran a script that updated 2,000 customer invoice files in a loop. My laptop ran out of battery right in the middle of the job. Because every file open line used a context manager, not a single file got locked or damaged when the power snapped off.
You can also read more practical python tutorials on our main page at anchor text about the topic to pick up clean coding habits fast.
How to Build Your Own Context Manager With Classes
Python lets you build custom context managers for your own custom tools. You do this by creating a standard Python class and adding two magic methods: __enter__ and __exit__.
The __enter__ method sets up your code block. It runs the exact moment Python hits the with line. Anything this method returns gets stored in the variable after the as keyword. The __exit__ method runs when your code leaves the block.
Here is a full working example of a custom timer manager that measures how long your code takes to run:
import time
class SpeedTest:
def __enter__(self):
self.start_time = time.time()
print("Starting timer...")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.end_time = time.time()
passed = self.end_time - self.start_time
print(f"Done! It took {passed:.2f} seconds.")
with SpeedTest():
total = 0
for number in range(10000000):
total += number
Look at the three parameters inside __exit__: exc_type, exc_val, and exc_tb. These three holds hold error information if something breaks inside your block. If no error happens, all three hold None.
If you want your manager to swallow errors and keep the script running, you can make __exit__ return True. If it returns False or nothing at all, Python raises the error as normal after doing the cleanup work.
How to Make Context Managers Using Contextlib
Writing a full class with special enter and exit methods can feel like too much work for a tiny job. Python gives you a faster tool called contextlib that turns simple generator functions into context managers.
To use this trick, import contextmanager from the contextlib module. Put the decorator above a function that uses a single yield statement. Everything before the yield runs at startup. Everything after the yield runs at cleanup.
Here is how to write a tool that changes into a folder, does work, and moves back to the starting folder:
import os
from contextlib import contextmanager
@contextmanager
def change_folder(destination):
saved_path = os.getcwd()
os.chdir(destination)
try:
yield
finally:
os.chdir(saved_path)
with change_folder("downloads"):
# We are inside downloads now!
print("Current folder:", os.getcwd())
# Now we are back in our original folder automatically!
print("Back home:", os.getcwd())
The try...finally structure inside the function is very important here. If an error strikes while your code works inside the downloads folder, the finally block ensures your script still jumps back to your starting folder without getting lost.
This generator style saves you from writing extra class boiler code. If you want to check how generators pass data around with yield statements, take a look at our full breakdown in Python Generators: How to Save Memory With Lazy Loops.
What Are Other Real World Uses for Context Managers?
Opening files is just the beginning for context managers. Software engineers use them daily to handle network sockets, database locks, database transactions, and user session tokens.
Here are four common places where context managers save your code from hard crashes:
- Database Connections: Automatically commit transaction changes if everything works, or roll back changes if an error pops up mid-way.
- Thread Locks: Lock a piece of shared data so two processes do not edit it at the exact same millisecond, then unlock it when done.
- Temporary Files: Create a temporary scrap file to test code and delete the file off your hard drive instantly when the block ends.
- Mocking Tests: Replace real API connections with fake sample data during unit testing and restore real connections right after.
You can also nest multiple context managers together on a single line in modern Python. If you need to copy lines from an old input file directly into a fresh output file, you do not need double indented blocks.
You can chain them with a simple comma like this:
with open("source.txt", "r") as source, open("copy.txt", "w") as destination:
for line in source:
destination.write(line)
This single line opens both files together cleanly. It closes both files safely the moment the loop finishes reading every line. You can explore more basic data management tips on our index page over at anchor text about the topic.
Tips to Improve Your Python Code Today
Adding context managers into your daily coding routine makes your scripts safe, easy to read, and professional. You will never have to search your code for missing close lines again.
Here are three practical tips you can use in your projects right now:
1. Always use with for files. Make it an automatic habit. Never call open() by itself without with sitting right in front of it. This simple habit cuts file corruptions down to zero.
2. Use contextlib.suppress for quiet cleanups. If you want to ignore a specific error like a missing file during a cleanup task, use from contextlib import suppress. Writing with suppress(FileNotFoundError): os.remove("temp.txt") keeps your script clean without messy try-except blocks.
3. Wrap setup and teardown code in custom managers. If you notice your code always does step A before an action and step B right after, bundle those two steps into a `@contextmanager` function today.
What custom tasks in your current Python project could use an automatic cleanup manager? Try writing a small `@contextmanager` decorator for your database calls today and see how many messy lines of code disappear from your scripts!