# Context Managers (with)

> What are context managers? How do you create custom ones?

Canonical: https://www.internhack.in/learn/interview/python-interview/python-context-managers
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

What are context managers? How do you create custom ones?

## Answer

Context managers ensure resources are properly acquired and released using the 'with' statement. They implement the context manager protocol: \__enter_\_ and \__exit_\_.

\__enter_\_: Called when entering the with block, returns the resource. \__exit_\_: Called when exiting (even if an exception occurred), handles cleanup.

Common uses: file handling, database connections, locks, temporary changes, timing.

Two ways to create context managers:

1. Class-based: implement \__enter_\_ and \__exit_\_
2. Function-based: use @contextlib.contextmanager decorator with yield

## Code examples

### Class-based Context Manager

```
class Timer:
    def __init__(self, label="Operation"):
        self.label = label
    
    def __enter__(self):
        import time
        self.start = time.perf_counter()
        return self  # Value assigned to 'as' variable
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        import time
        self.elapsed = time.perf_counter() - self.start
        print(f"{self.label} took {self.elapsed:.4f}s")
        return False  # Don't suppress exceptions

# Usage
with Timer("Computation") as t:
    total = sum(range(1_000_000))
print(f"Result: {total}, Time: {t.elapsed:.4f}s")

# Exception handling in __exit__
class SuppressErrors:
    def __enter__(self):
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is ValueError:
            print(f"Suppressed ValueError: {exc_val}")
            return True  # True = suppress the exception
        return False     # False = re-raise

with SuppressErrors():
    raise ValueError("test error")  # Suppressed!
print("Continues after suppressed error")
```

\__exit_\_ receives exception info (or None if no exception). Returning True suppresses the exception, False (or None) re-raises it.

### Function-based with @contextmanager

```
from contextlib import contextmanager

@contextmanager
def temp_directory():
    import tempfile, shutil, os
    dirpath = tempfile.mkdtemp()
    print(f"Created temp dir: {dirpath}")
    try:
        yield dirpath  # This is what 'as' receives
    finally:
        shutil.rmtree(dirpath)
        print(f"Cleaned up temp dir")

with temp_directory() as tmpdir:
    print(f"Working in: {tmpdir}")
    # Create files, do work...
# Automatically cleaned up after the block

@contextmanager
def database_transaction(db):
    """Commit on success, rollback on failure."""
    try:
        yield db
        db.commit()
        print("Transaction committed")
    except Exception:
        db.rollback()
        print("Transaction rolled back")
        raise

# Simulating
class FakeDB:
    def commit(self): pass
    def rollback(self): pass

with database_transaction(FakeDB()) as db:
    print("Doing database work...")
```

@contextmanager turns a generator function into a context manager. Code before yield is \__enter_\_, code after yield is \__exit_\_. The yield value is the 'as' target.

### Built-in Context Managers

```
# File handling (most common)
with open('example.txt', 'w') as f:
    f.write('Hello, World!')
# File is automatically closed, even if an exception occurs

# Multiple context managers
with open('input.txt') as src, open('output.txt', 'w') as dst:
    dst.write(src.read())

# Threading lock
import threading
lock = threading.Lock()
with lock:  # Acquires lock, releases on exit
    print("Critical section")

# Suppress specific exceptions
from contextlib import suppress
with suppress(FileNotFoundError):
    import os
    os.remove('nonexistent.txt')  # No error raised
print("Continues normally")

# Redirect stdout
from contextlib import redirect_stdout
import io
f = io.StringIO()
with redirect_stdout(f):
    print("This goes to the buffer")
captured = f.getvalue()
print(f"Captured: {captured.strip()}")
```

Python's standard library is full of context managers: files, locks, database connections, temporary directories, output redirection, and exception suppression.

## Key points

- Always use 'with' for file operations - it guarantees the file is closed even on exceptions
- contextlib.suppress() is cleaner than try/except/pass for ignoring specific exceptions
- contextlib.ExitStack() manages a dynamic number of context managers

## Common follow-up questions

- What happens if an exception occurs inside a with block?
- How does contextlib.ExitStack work?
- Can you nest context managers? What about async context managers?

## Interview tips

- Show both class-based and @contextmanager approaches
- File handling with 'with' is the most relatable example - start there
- Mention database transactions as a real-world use case for context managers

## Concepts covered

with statement, \__enter_\_, \__exit_\_, contextlib, Resource Management

Previous: [Exception Handling](https://www.internhack.in/learn/interview/python-interview/python-exceptions) · Next: [File I/O & CSV/JSON](https://www.internhack.in/learn/interview/python-interview/python-file-io) · [All of Python Interview](https://www.internhack.in/learn/interview/python-interview)

## More Python Interview questions

- [Regular Expressions](https://www.internhack.in/learn/interview/python-interview/python-regex)
- [Collections Module](https://www.internhack.in/learn/interview/python-interview/python-collections)
- [Itertools & Functools](https://www.internhack.in/learn/interview/python-interview/python-itertools-functools)
- [Metaclasses](https://www.internhack.in/learn/interview/python-interview/python-metaclasses)
- [Memory Management & GC](https://www.internhack.in/learn/interview/python-interview/python-memory-gc)
- [Virtual Environments & pip](https://www.internhack.in/learn/interview/python-interview/python-venv-pip)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Python Interview](https://www.internhack.in/learn/interview/python-interview)
