
Photo by Daniil Komov on Pexels
We’ve all been there: you open a file, connect to a database, or spin up a network socket, and you write a massive try...finally block just to make sure you clean up after yourself. It’s verbose, it’s ugly, and if you forget the finally block, your server cries tears of leaked memory. Luckily, Python’s context managers let you automate the boring stuff with a single with statement, making your code look like it was written by someone who actually sleeps at night.
Welcome back to the Old Lane 17 workshop. Today, we are banishing indentation hell and writing cleaner, safer Python code.
The Problem: The try...finally Hangover
Picture this: you are writing a script to process a crucial text file. You need to open it, write some data, and—no matter what—ensure the file handle is closed, even if your code spontaneously combusted halfway through.
The amateur hour approach looks like this:
python# Please don't write code like this in production, we have feelings.
file = open("old_lane_secrets.txt", "w")
try:
file.write("Old Lane 17 rules.")
# Imagine a wild ZeroDivisionError appears here out of nowhere
result = 1 / 0
finally:
file.close()
print("Phew, file closed safely.")
Sure, this works. But it is noisy. It requires mental gymnastics, manual cleanup calls, and adds an extra level of indentation for every single resource you manage. If you have three resources to open, your code starts drifting off the right side of your 27-inch monitor.
The Clean Fix: Enter the with Statement
Python has a built-in superhero for this exact scenario: the context manager. Behind the scenes, it handles the setup and teardown phases so you don’t have to remember to do it while running on your third cup of cold coffee.
Here is how that exact same file operation should look:
python# Clean, readable, and practically crash-proof.
with open("old_lane_secrets.txt", "w") as file:
file.write("Old Lane 17 rules.")
# Even if an exception happens here, Python guarantees file.close() is called.
When execution leaves the with block—whether gracefully or via an exception—the context manager automatically triggers the cleanup method. No finally required.
Building Your Own Custom Context Manager
What happens when you aren’t opening a file, but instead managing a database connection, a performance timer, or a temporary directory change? You build your own using Python’s contextlib module.
Stop writing complex classes with __enter__ and __exit__ methods unless you genuinely need them. Use the contextmanager decorator instead:
pythonimport time
from contextlib import contextmanager
@contextmanager
def measure_time(task_name):
start_time = time.time()
print(f"[-] Starting: {task_name}")
try:
yield # This is where your actual code block runs
finally:
elapsed = time.time() - start_time
print(f"[+] Finished {task_name} in {elapsed:.4f} seconds")
# Let's use our custom context manager in the wild
with measure_time("Over-engineering our database query"):
time.sleep(1.5) # Simulating hard work
Why this is a win:
- Zero Leaks: Resources are always released, preventing memory leaks and locked files.
- Readability: Your business logic stays front-and-center, unpolluted by boilerplate error handling.
- Reusability: Wrap once, use everywhere across your entire codebase.
Now go forth, delete those redundant finally blocks, and may your terminal output be forever green.
Published by the Old Lane Developer Desk.
Disclaimer: This article was generated and formatted with the assistance of Artificial Intelligence.


