Junior — Middle
Have you had experience using context managers in Python for automatic resource management?
sobes.tech AI
Answer from AI
Yes, in Python, context managers are used for automatic resource management, such as files, network connections, locks, etc. They are implemented through the __enter__() and __exit__() methods.
The most common example is opening a file with with, which guarantees the file is closed even if an exception occurs:
with open('file.txt', 'r') as f:
data = f.read()
# file is automatically closed here
You can create your own context managers using a class or the contextlib.contextmanager decorator:
from contextlib import contextmanager
@contextmanager
def managed_resource():
print('Resource opened')
yield
print('Resource closed')
with managed_resource():
print('Working with resource')
This simplifies resource management and makes the code more reliable and readable.