Junior — Middle
How to implement a custom context manager in Python as a function?
sobes.tech AI
Answer from AI
In Python, you can create a custom context manager using a function with the @contextlib.contextmanager decorator. This allows you to use the with statement to manage resources.
Here's an example of a simple context manager that prints messages on entry and exit:
from contextlib import contextmanager
@contextmanager
def my_manager():
print("Entering context")
try:
yield # point where the body of with executes
finally:
print("Exiting context")
Usage:
with my_manager():
print("Inside with block")
Output:
Entering context
Inside with block
Exiting context
Thus, yield splits the code into two parts: before yield is initialization code, after is cleanup code. It's a convenient way to create context managers without writing a class with __enter__ and __exit__ methods.