Junior — Middle
What methods of implementing context managers in Python do you know?
sobes.tech AI
Answer from AI
In Python, there are two main ways to implement context managers:
-
Using
__enter__and__exit__methods in a classYou need to define a class with methods:
__enter__(self)— called when entering thewithblock, returns an object that will be assigned to the variable afteras.__exit__(self, exc_type, exc_val, exc_tb)— called when exiting the block, where you can handle exceptions and free resources.
Example:
class MyContext: def __enter__(self): print('Enter') return self def __exit__(self, exc_type, exc_val, exc_tb): print('Exit') with MyContext() as ctx: print('Inside block') -
Using the
@contextmanagerdecorator from thecontextlibmoduleAllows writing a generator where code before
yieldis the entry code, and code afteryieldis the exit code.Example:
from contextlib import contextmanager @contextmanager def my_context(): print('Enter') yield print('Exit') with my_context(): print('Inside block')
Both methods are widely used in Python for resource management, such as working with files, locks, network connections, etc.