What is a context manager?
A construct that automatically handles setup and cleanup of resources using the with statement
Why use the with statement?
Ensures resources (files, connections) are properly closed, even if an error occurs.
What happens internally in a with block?
Calls __enter__()
Executes block
Calls __exit__() (even on exception)
What does __enter__ do?
Runs at the start and returns the resource used inside the block.
What does __exit__ do?
Runs at the end, handles cleanup, and executes even if an error occurs.
How does a context manager handle exceptions?
__exit__ receives exception details and still performs cleanup.
What is contextmanager used for?
To create context managers using a generator and yield instead of a class.
In contextmanager, what does yield represent?
Before yield → setup (__enter__)
After yield → cleanup (__exit__)
Where are context managers used?
File handling, DB connections, locks, network resources.