Problem Statement
Explain contextlib.contextmanager and when you would prefer it over a class-based context manager.
Explanation
contextmanager turns a simple generator into a context manager. The code before the yield is the setup. The code after the yield is the teardown that always runs, even if an exception occurs.
Use it when the resource logic is small and linear. It keeps the pattern concise without defining enter and exit methods. For complex state or multiple exit paths, a class-based manager can be clearer and easier to extend.
Code Solution
SolutionRead Only
from contextlib import contextmanager
@contextmanager
def opened(path):
f=open(path,'r',encoding='utf-8')
try:
yield f
finally:
f.close()