Junior — Middle
Can you show an example of resource management using a context manager?
sobes.tech AI
Answer from AI
Context managers in Python are used for automatic resource management, such as files, network connections, locks, etc. They ensure that the resource is properly released after use, even if errors occur during execution.
The simplest example is working with a file using the with statement:
with open('example.txt', 'r') as file:
data = file.read()
# The file is automatically closed here, even if an exception occurs during reading
You can also create your own context managers using a class that implements the __enter__ and __exit__ methods:
class ManagedResource:
def __enter__(self):
print('Resource opened')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('Resource closed')
# You can handle exceptions here if needed
with ManagedResource() as resource:
print('Working with resource')
This approach helps prevent resource leaks and makes the code more readable and reliable.