Middle+
What is a context manager and why is it needed?
sobes.tech AI
Answer from AI
A context manager in Python is an object that defines the __enter__ and __exit__ methods, allowing automatic management of resources such as opening and closing files, locks, or network connections.
It is used to ensure proper release of resources even if exceptions occur within the block of code. It is used with the with statement.
Example:
with open('file.txt', 'r') as f:
data = f.read()
# the file is automatically closed after exiting the block
Here, open returns a context manager that opens the file upon entry and closes it upon exit.