Junior
Provide an example of using a context manager in Python.
sobes.tech AI
Answer from AI
# Opening a file:
# Using a context manager guarantees automatic file closure,
# even if an exception occurs.
with open('my_file.txt', 'w') as f:
# Writing data to the file
f.write('Hello, world!\n')
f.write('This is a test.')
# Example of creating a custom context manager using a class:
class ManagedResource:
def __enter__(self):
print('Resource allocated')
# Can return an object that will be assigned after 'as'
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('Resource released')
# Can handle exceptions. Returning True suppresses the exception.
return False
# Using the created context manager:
with ManagedResource() as res:
print('Working with resource')
# res is the object returned by __enter__
# Example of creating a custom context manager using the @contextmanager decorator:
from contextlib import contextmanager
@contextmanager
def efficient_resource():
print('Efficient resource allocated')
try:
yield 'Efficient resource' # The object to be returned
finally:
print('Efficient resource released')
# Using the context manager with the decorator:
with efficient_resource() as eff_res:
print(f'Using: {eff_res}')