🔒

How to Use Context Managers in Python

PythonAdvanced

Manage resources with context managers.

Code Example

Python
# Using with statement
with open("test.txt", "w") as f:
    f.write("Hello, World!")
print("File automatically closed")

# Custom context manager with class
class Timer:
    def __enter__(self):
        import time
        self.start = time.time()
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        import time
        self.end = time.time()
        print(f"Elapsed: {self.end - self.start:.4f}s")
        return False

with Timer():
    import time
    time.sleep(0.1)

# Context manager with contextlib
from contextlib import contextmanager

@contextmanager
def tag(name):
    print(f"<{name}>")
    yield
    print(f"</{name}>")

with tag("html"):
    with tag("body"):
        print("Content")

# Practical example
@contextmanager
def database_transaction(db):
    print("Starting transaction")
    try:
        yield db
        print("Committing transaction")
    except Exception as e:
        print(f"Rolling back: {e}")
        raise

class MockDB:
    pass

with database_transaction(MockDB()) as db:
    print("Executing queries")

# Multiple context managers
with open("file1.txt", "w") as f1, open("file2.txt", "w") as f2:
    f1.write("File 1")
    f2.write("File 2")
print("\nBoth files handled")

Explanation

Context managers ensure proper resource cleanup. Use with statement. Implement __enter__ and __exit__ methods or use @contextmanager decorator.

Related Tutorials