All posts
Article · 1 min ·

Python: The 'with' Statement

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

Context Managers

The with statement is syntactic sugar for try/finally.

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

Is roughly:

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__.

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.

Related posts