Skip to content
Python

Context Manager

Custom context managers.

By EZ4Code Team
contextwith

Code

from contextlib import contextmanager

@contextmanager
def timer(name):
    import time
    start = time.time()
    try:
        yield
    finally:
        print(f"{name}: {time.time() - start:.2f}s")

with timer("operation"):
    sum(range(1000000))

# Class-based implementation
class FileManager:
    def __init__(self, path, mode):
        self.path = path
        self.mode = mode
    def __enter__(self):
        self.f = open(self.path, self.mode)
        return self.f
    def __exit__(self, *exc):
        self.f.close()

Explanation

Context managers ensure resources are properly released; contextmanager simplifies implementation.

More Python Snippets