Problem Statement
Explain how a context manager works in Python. Show a small custom example.
Explanation
A context manager defines enter and exit steps around a code block. Python calls the enter method before the block starts and exit after it ends, even when exceptions happen. This pattern centralizes resource handling and prevents leaks.
You can implement one by defining __enter__ and __exit__ methods or by using contextlib.contextmanager. Common uses include file handles, locks, temporary directories, and timing utilities.
Code Solution
SolutionRead Only
class Locker:
def __enter__(self): print('acquire'); return self
def __exit__(self, exc_type, exc, tb): print('release')
with Locker() as l:
do_work()