QA
Intermediate LevelPython

How do you create custom Context Managers using __enter__ / __exit__ classes or @contextlib.contextmanager?

❓ Interview Prompt: Explain context manager protocol (`__enter__`, `__exit__`), exception suppression, and `@contextlib.contextmanager` generator decorator.

You can build custom context managers via two approaches:

1. Class Protocol ('__enter__' / '__exit__'):

•
'__enter__()': Prepares resource and returns value.
•
'__exit__(exc_type, exc_val, exc_tb)': Performs cleanup. Returning 'True' suppresses exceptions!

2. Generator Decorator ('@contextlib.contextmanager'):

Decorates a generator function yielding resource between setup and cleanup code.

Code Implementation Example

python
from contextlib import contextmanager
import time

@contextmanager
def timer(label):
    start = time.time()
    try:
        yield # Control passes to with-block body!
    finally:
        print(f'[{label}] Elapsed: {round(time.time() - start, 4)}s')

with timer('Database Query'):
    time.sleep(0.1)
💡Creating custom context managers using @contextlib.contextmanager.
🎯 Interview Key Takeaway

Use @contextlib.contextmanager for clean, generator-based context manager implementations.

#Context Manager#contextlib#__enter__#__exit__#Intermediate
Back to all Python Questions→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?