Python: The 'with' Statement

August 21, 2025 1 min read 2 views

You use with open(...) all the time. But how does it work?

Context Managers

The with statement is syntactic sugar for try/finally.

Code
with open('file.txt') as f:
    data = f.read()

Is roughly:

Code
f = open('file.txt')
try:
    data = f.read()
finally:
    f.close() # Always runs, even if error occurs

Creating your own

You just need __enter__ and __exit__.

Python
class Timer:
    def __enter__(self):
        self.start = time.time()
        return self

    def __exit__(self, *args):
        self.end = time.time()
        print(f"Time taken: {self.end - self.start}s")

with Timer():
    heavy_function()
# Output: Time taken: 2.5s

Conclusion

Context Managers are beautiful. Use them for Locks, Database Connections, and Files. Cleanup should be automatic.

Similar Posts