POST 1 of 5 MorningPythonConcept
with-statements never leak resources
Every long-lived program eventually leaks something. File handles, network sockets, database connections, locks, GPU memory. The leak is rarely a single bug — it's the accumulation of forgotten cleanup. Open a thing on line 12; forget to close it on line 47; the leak waits.
Python's 'with' statement was designed to make this class of bug nearly impossible.
with open('file') as f:
process(f)
The runtime guarantees that f.close() runs when the block exits. Even if process(f) raises an exception. Even if you return early from a function. Even if a deeply nested call inside process() causes a stack unwind. The cleanup happens.
Behind the scenes, 'with' looks for two methods on the object — __enter__ and __exit__. __enter__ returns the resource (and runs setup). __exit__ runs at block end (and handles teardown). Python ensures __exit__ is called even on exceptions.
This pattern generalises far beyond files:
Database connections. with engine.begin() as conn: ... — transaction commits on success, rolls back on exception.
Locks. with lock: ... — acquire on enter, release on exit. Even if the body crashes, the lock releases.
Temp directories. with tempfile.TemporaryDirectory() as path: ... — directory created on enter, deleted on exit.
GPU memory. with torch.cuda.device(0): ... — device set on enter, restored on exit.
Timers and metrics. with timer('inference'): ... — start time recorded on enter, duration computed on exit.
The principle is simple — any resource with a 'must clean up' rule belongs in a context manager. If you find yourself writing try/finally with a paired open/close, you almost certainly want a context manager instead.
Leaks are bugs the runtime can prevent for you. Let it.#Python#AI#100DaysOfCode#BuildInPublic#PythonProgramming#PythonContextManagers