Middle
What are context managers? Why use them?
sobes.tech AI
Answer from AI
Context managers in Python are constructs that manage resources, ensuring their proper opening and closing. They implement the __enter__ and __exit__ methods, allowing them to be used with the with keyword.
Why use them:
- Guarantee resource release (files, network connections, locks) even in case of errors.
- Simplify code, making it more readable and safe.
Example:
with open('file.txt', 'r') as f:
data = f.read()
# the file is automatically closed after exiting the with block
Here, open returns a context manager that opens the file and guarantees its closure.