Programming languages · Intermediate · 24 min
Clean up files, locks and connections with Python context managers
By Padding · Updated 18 Nov 2026
Debian (python:3.15-slim) · Python 3.15.2 · pytest 9.2
You will have a small Python 3.15 utilities module of context managers (a timer, a change-directory helper, safe file removal, multi-file reading, an async connection and an atomic file write) with pytest tests that prove clean-up happens when code fails.
On this page
Every program borrows things from the operating system: open files, temporary folders, network connections, locks, the current working directory. Each one has to be given back. The trouble is the error halfway through. A close() on the last line of a function never runs if line three raises, and the leak builds up quietly until a long-running service hits its open-file limit or fills a disk with forgotten temp folders.
A context manager is an object that pairs a set-up with a guaranteed clean-up, and the with statement is how you use one. In this tutorial you first watch a short script leak a file handle and a temp folder, then fix it, then write your own context managers and collect them in a module called ctxutils.py. You finish with pytest tests that make each helper fail on purpose and check that the clean-up still happened.
Step 1 · Set up a project and watch a script leak
Create a throwaway project and add pytest as a development dependency. The version range allows patch releases of pytest 9.2 and nothing newer:
mkdir -p ~/ctxdemo
cd ~/ctxdemo
uv init --no-package
uv add --dev "pytest>=9.2,<9.3"Now write a script with a typical bug. export_report makes a temp folder, opens a CSV file inside it and writes one line per row. The second row has text where a number should be, so formatting it raises ValueError before the function reaches close() or removes the folder:
cat > leaky.py <<'PY'
import glob
import os
import shutil
import tempfile
PATTERN = os.path.join(tempfile.gettempdir(), "ctxdemo-report-*")
def export_report(rows):
workdir = tempfile.mkdtemp(prefix="ctxdemo-report-")
out = open(os.path.join(workdir, "report.csv"), "w", encoding="utf-8")
for name, amount in rows:
out.write(f"{name},{amount:.2f}\n")
out.close()
shutil.rmtree(workdir)
before = set(glob.glob(PATTERN))
rows = [("Ada", 12.5), ("Kwame", "n/a"), ("Lin", 3.0)]
try:
export_report(rows)
except ValueError as err:
print("export failed:", err)
print("new temp folders left behind:", len(set(glob.glob(PATTERN)) - before))
PY
uv run python -X dev leaky.py-X dev turns on Python's development mode, which prints a ResourceWarning when a file is thrown away while still open. Without it the leak is silent.
Check it worked
The output says export failed: Unknown format code 'f' for object of type 'str' and new temp folders left behind: 1. Above or below it you see a warning that ends with something like ResourceWarning: unclosed file <_io.TextIOWrapper name='/tmp/ctxdemo-report-…/report.csv' mode='w' encoding='utf-8'>. Both resources leaked. The final step removes the leftover folders.
Step 2 · Fix it with with, and see what __exit__ receives
A with block calls the object's __enter__ method on the way in and its __exit__ method on the way out, however the block ends: normally, by return, or by an exception. To see exactly what __exit__ is given, write a context manager that only reports:
cat > tracer.py <<'PY'
class Tracer:
def __init__(self, name):
self.name = name
def __enter__(self):
print(f"enter {self.name}")
return self
def __exit__(self, exc_type, exc, tb):
kind = exc_type.__name__ if exc_type else None
print(f"exit {self.name}: exc_type={kind} exc={exc!r} traceback={'yes' if tb else None}")
return False
with Tracer("calm") as t:
print("inside", t.name)
try:
with Tracer("stormy"):
raise KeyError("missing")
except KeyError:
print("the KeyError still reached the caller")
PY
uv run python tracer.pyThree things to notice. Whatever __enter__ returns is what as binds, here the tracer itself. __exit__ gets three arguments: the exception's class, the exception object and its traceback, or three None values when the block finished cleanly. Its return value decides what happens next: a false value lets the exception carry on to the caller, and a true value swallows it. Return False (or nothing) unless swallowing is the whole point.
Files and temp folders are already context managers, so fixing the report needs no new code, only with:
cat > fixed.py <<'PY'
import glob
import os
import tempfile
PATTERN = os.path.join(tempfile.gettempdir(), "ctxdemo-report-*")
def export_report(rows):
with tempfile.TemporaryDirectory(prefix="ctxdemo-report-") as workdir:
with open(os.path.join(workdir, "report.csv"), "w", encoding="utf-8") as out:
for name, amount in rows:
out.write(f"{name},{amount:.2f}\n")
before = set(glob.glob(PATTERN))
try:
export_report([("Ada", 12.5), ("Kwame", "n/a"), ("Lin", 3.0)])
except ValueError as err:
print("export failed:", err)
print("new temp folders left behind:", len(set(glob.glob(PATTERN)) - before))
PY
uv run python -X dev fixed.pyThe file closes first, then the folder is deleted, in the reverse order they were opened.
Locks work the same way. A threading.Lock is a context manager whose __enter__ acquires the lock and whose __exit__ releases it, so an error inside the block can never leave another thread waiting for ever:
cat > lock_demo.py <<'PY'
import threading
lock = threading.Lock()
try:
with lock:
raise RuntimeError("failed while holding the lock")
except RuntimeError:
pass
print("lock still held:", lock.locked())
PY
uv run python lock_demo.pyCheck it worked
tracer.py prints exit calm: exc_type=None exc=None traceback=None, then exit stormy: exc_type=KeyError exc=KeyError('missing') traceback=yes, then the KeyError still reached the caller. fixed.py prints the same export failed message as before, new temp folders left behind: 0, and no ResourceWarning. lock_demo.py prints lock still held: False, so the lock was released even though the block raised.
Step 3 · Write a timer and a change-directory helper with contextmanager
Writing a class with two methods is fine, but most context managers are shorter as a generator decorated with contextlib.contextmanager. The code before yield is the set-up, the yielded value is what as binds, and the code after it is the clean-up. If the block raises, the exception reappears at the yield line, so the clean-up must sit in a finally clause. Without try/finally, an error skips the clean-up and you are back to the leak.
Start the utilities module with two helpers. timer measures how long a block takes, and still records the time when the block fails. working_directory moves into a folder and always moves back. The imports at the top cover the whole module, including helpers you add in later steps:
cat > ctxutils.py <<'PY'
"""Small context managers that clean up after themselves."""
import asyncio
import contextlib
import os
import tempfile
import time
from pathlib import Path
class Timing:
"""Holds the result of a timer once its block has finished."""
def __init__(self):
self.seconds = None
@contextlib.contextmanager
def timer(label):
timing = Timing()
start = time.perf_counter()
try:
yield timing
finally:
timing.seconds = time.perf_counter() - start
print(f"{label}: {timing.seconds:.3f}s")
@contextlib.contextmanager
def working_directory(path):
previous = os.getcwd()
os.chdir(path)
try:
yield Path(path)
finally:
os.chdir(previous)
PYThe standard library has its own contextlib.chdir, which does the same job as working_directory; you write one here to see the pattern. Either way, the current directory belongs to the whole process, so do not change it from code that runs in several threads at once.
Try both helpers, including a failure inside the folder:
cat > demo_helpers.py <<'PY'
import os
import time
from ctxutils import timer, working_directory
with timer("short sleep"):
time.sleep(0.2)
os.makedirs("data", exist_ok=True)
start = os.getcwd()
try:
with working_directory("data"):
print("inside:", os.path.basename(os.getcwd()))
raise RuntimeError("something broke in data/")
except RuntimeError:
pass
print("back where we started:", os.getcwd() == start)
PY
uv run python demo_helpers.pyCheck it worked
The output is something like short sleep: 0.201s, then inside: data, then back where we started: True. The last line proves the directory was restored even though the block raised.
Step 4 · Ignore one expected error with suppress
Sometimes an error means "nothing to do". Deleting a file that is already gone is the classic case. contextlib.suppress swallows the exception types you name and nothing else. Add a helper to the module:
cat >> ctxutils.py <<'PY'
def remove_if_present(path):
"""Delete a file. A missing file is fine; any other problem still raises."""
with contextlib.suppress(FileNotFoundError):
os.remove(path)
PYThen check that it ignores a missing file but still complains about a real problem, such as trying to remove a folder with a function meant for files:
cat > demo_suppress.py <<'PY'
from pathlib import Path
from ctxutils import remove_if_present
Path("old.log").write_text("stale\n", encoding="utf-8")
remove_if_present("old.log")
remove_if_present("old.log")
print("old.log exists:", Path("old.log").exists())
try:
remove_if_present("data")
except OSError as err:
print("still raised:", type(err).__name__)
PY
uv run python demo_suppress.pyName the narrowest exception you mean. suppress(Exception) hides every bug in the block, including typos, and the code carries on as if it had worked.
Check it worked
The second remove_if_present("old.log") runs without error, and the output is old.log exists: False followed by still raised: IsADirectoryError on Linux. On macOS the second line says PermissionError; both are kinds of OSError, and neither was suppressed.
Step 5 · Open any number of files with ExitStack
with works when you know how many resources you need while writing the code. When the number comes from data, such as a list of files a user passes in, use contextlib.ExitStack. Each enter_context call enters a context manager and remembers to exit it. When the stack's own block ends, everything it holds is cleaned up in reverse order, and if opening the fifth file fails, the first four are still closed.
Add a function that reads several files in order:
cat >> ctxutils.py <<'PY'
def read_all(paths):
"""Return the lines of every file in order. Every opened file is closed, even on error."""
with contextlib.ExitStack() as stack:
files = [stack.enter_context(open(p, encoding="utf-8")) for p in paths]
return [line.rstrip("\n") for f in files for line in f]
PYAn ExitStack also takes plain functions through callback, which is handy for clean-up that has no context manager of its own. The demo shows both, and the reverse order:
cat > demo_stack.py <<'PY'
import contextlib
from pathlib import Path
from ctxutils import read_all
for name, text in [("a.txt", "alpha\n"), ("b.txt", "bravo\n"), ("c.txt", "charlie\n")]:
Path(name).write_text(text, encoding="utf-8")
print(read_all(["a.txt", "b.txt", "c.txt"]))
try:
read_all(["a.txt", "b.txt", "missing.txt"])
except FileNotFoundError as err:
print("failed on:", err.filename)
with contextlib.ExitStack() as stack:
for name in ["first", "second"]:
stack.callback(print, "clean up", name)
print("work done")
PY
uv run python demo_stack.pyCheck it worked
The output is ['alpha', 'bravo', 'charlie'], then failed on: missing.txt, then work done, clean up second and clean up first. The last three lines show the stack unwinding newest first. A test in the last step proves that a.txt and b.txt really were closed when missing.txt failed.
Step 6 · Close an async connection with async with
Async code has its own form: async with calls __aenter__ and __aexit__, which are coroutines, so set-up and clean-up can await network I/O. A network connection is the common case, because closing it properly means waiting for the close to finish. contextlib.asynccontextmanager works like contextmanager, with async def and the same try/finally rule:
cat >> ctxutils.py <<'PY'
@contextlib.asynccontextmanager
async def open_connection(host, port):
"""Connect over TCP and always close the connection, waiting until it is closed."""
reader, writer = await asyncio.open_connection(host, port)
try:
yield reader, writer
finally:
writer.close()
await writer.wait_closed()
PYTo try it without any outside service, the demo starts a small echo server on your own machine that sends back each line in capitals. Port 0 asks the operating system for any free port. The server is a context manager too: async with server closes it at the end of the block.
cat > demo_async.py <<'PY'
import asyncio
from ctxutils import open_connection
async def shout_back(reader, writer):
line = await reader.readline()
writer.write(line.upper())
await writer.drain()
writer.close()
await writer.wait_closed()
async def main():
server = await asyncio.start_server(shout_back, "127.0.0.1", 0)
port = server.sockets[0].getsockname()[1]
async with server:
async with open_connection("127.0.0.1", port) as (reader, writer):
writer.write(b"hello from lagos\n")
await writer.drain()
print((await reader.readline()).decode().strip())
print("client closed:", writer.is_closing())
asyncio.run(main())
PY
uv run python demo_async.pyCheck it worked
The output is HELLO FROM LAGOS, then client closed: True, and the script exits straight away. A script that hangs at the end usually has a connection or server that was never closed.
Step 7 · Write a file atomically
Writing a settings file in place has a nasty failure: if the program crashes, the disk fills or the power goes halfway through, the file is left half-written and the next start-up cannot read it. This matters on laptops and phones with flaky power, and on downloads over a mobile data connection that drops mid-file.
The fix is to write to a temporary file in the same folder, flush it to disk, then swap it into place with os.replace. When the swap succeeds on the same filesystem it is atomic: anyone reading the path sees the old file or the new one, never a mix. If anything fails before the swap, the context manager deletes the temp file and the original is untouched.
cat >> ctxutils.py <<'PY'
@contextlib.contextmanager
def atomic_write(path, encoding="utf-8"):
"""Yield a text file that replaces path only if the block finishes without error."""
path = Path(path)
fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
try:
with os.fdopen(fd, "w", encoding=encoding) as tmp:
yield tmp
tmp.flush()
os.fsync(tmp.fileno())
os.replace(tmp_name, path)
except BaseException:
with contextlib.suppress(FileNotFoundError):
os.remove(tmp_name)
raise
PYThe temp file must be in the same folder as the target, because os.replace across two filesystems is not atomic and can fail. except BaseException also catches Ctrl+C, so an interrupted write leaves no stray file; the bare raise passes the original error on. One side effect: mkstemp creates the file readable and writable only by you, so the replaced file ends up with those permissions. That suits settings and secrets; change the mode with os.chmod on the temp file before the swap if other users must read it.
Write a settings file, then fail halfway through a second write:
cat > demo_atomic.py <<'PY'
import json
from pathlib import Path
from ctxutils import atomic_write
with atomic_write("settings.json") as f:
json.dump({"theme": "dark", "retries": 3}, f)
print("first write:", Path("settings.json").read_text(encoding="utf-8"))
try:
with atomic_write("settings.json") as f:
f.write('{"theme": "li')
raise RuntimeError("power cut halfway")
except RuntimeError:
pass
print("after failed write:", Path("settings.json").read_text(encoding="utf-8"))
print("temp files left:", len(list(Path(".").glob(".settings.json.*"))))
PY
uv run python demo_atomic.pyCheck it worked
Both first write: and after failed write: show {"theme": "dark", "retries": 3}, and the last line is temp files left: 0. The broken half-write never reached settings.json.
Step 8 · Prove the clean-up with tests
Demos show the happy story once. Tests keep it true when you change the code later. Each test below makes a helper fail on purpose, then checks the clean-up. The read_all test swaps in a version of open that records every file it opens, so it can check that each one was closed. monkeypatch puts the real open back when the test ends.
Tell pytest where the tests are and to import ctxutils from the project folder by adding a section to the end of pyproject.toml:
cat >> pyproject.toml <<'TOML'
[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]
TOMLThen write the tests:
mkdir -p tests
cat > tests/test_ctxutils.py <<'PY'
import asyncio
import os
import pytest
import ctxutils
from ctxutils import (
atomic_write,
open_connection,
read_all,
remove_if_present,
timer,
working_directory,
)
def test_working_directory_returns_after_error(tmp_path):
start = os.getcwd()
with pytest.raises(RuntimeError):
with working_directory(tmp_path):
raise RuntimeError("boom")
assert os.getcwd() == start
def test_timer_records_time_after_error():
with pytest.raises(ValueError):
with timer("failing block") as timing:
raise ValueError("bad input")
assert timing.seconds is not None
assert timing.seconds >= 0
def test_remove_if_present_ignores_missing_file(tmp_path):
remove_if_present(tmp_path / "nothing-here.txt")
def test_read_all_closes_opened_files_on_error(tmp_path, monkeypatch):
opened = []
def tracking_open(*args, **kwargs):
f = open(*args, **kwargs)
opened.append(f)
return f
monkeypatch.setattr(ctxutils, "open", tracking_open, raising=False)
(tmp_path / "a.txt").write_text("alpha\n", encoding="utf-8")
(tmp_path / "b.txt").write_text("bravo\n", encoding="utf-8")
with pytest.raises(FileNotFoundError):
read_all([tmp_path / "a.txt", tmp_path / "b.txt", tmp_path / "missing.txt"])
assert len(opened) == 2
assert all(f.closed for f in opened)
def test_atomic_write_keeps_old_file_on_error(tmp_path):
target = tmp_path / "settings.json"
target.write_text("old", encoding="utf-8")
with pytest.raises(RuntimeError):
with atomic_write(target) as f:
f.write("half")
raise RuntimeError("stop")
assert target.read_text(encoding="utf-8") == "old"
assert list(tmp_path.iterdir()) == [target]
def test_open_connection_closes_on_error():
async def scenario():
async def hang_up(reader, writer):
writer.close()
await writer.wait_closed()
server = await asyncio.start_server(hang_up, "127.0.0.1", 0)
port = server.sockets[0].getsockname()[1]
async with server:
with pytest.raises(RuntimeError):
async with open_connection("127.0.0.1", port) as (reader, writer):
raise RuntimeError("stop")
return writer.is_closing()
assert asyncio.run(scenario())
PY
uv run pytest -vmonkeypatch.setattr(ctxutils, "open", ...) works because Python looks up a name in the module's own globals before the built-ins, so only code inside ctxutils sees the recording version.
Check it worked
pytest lists six tests, each marked PASSED, and ends with 6 passed. To see a test catch a real bug, delete the try: and finally: lines from working_directory (keeping os.chdir(previous) after the yield), run uv run pytest again and watch test_working_directory_returns_after_error fail. Put the lines back afterwards.
Step 9 · Clean up
Remove the temp folders that leaky.py left behind, then the demo project. Python and uv stay installed:
cd ~/ctxdemo
uv run python -c "import glob, os, shutil, tempfile; [shutil.rmtree(p) for p in glob.glob(os.path.join(tempfile.gettempdir(), 'ctxdemo-report-*'))]"
cd ~
rm -rf ~/ctxdemoCheck it worked
ls ~/ctxdemo reports that there is no such file or directory.
Next steps
- Go deeper on the exceptions that
__exit__sees: handle errors with try and except in Python. - Use
atomic_writewhen saving data: read and write files and JSON in Python. - Put
open_connectionto work on many connections at once: run many network calls at once with Python asyncio. - Learn more about fixtures and
monkeypatch: test Python code with pytest.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials