Python 101 : Manually setting up a context manager

Context managers make it possible for us to manage our resources.

When python enters a context, it calls the __enter__() methods and it calls the __exit__() method when it leaves the context.

We can use the __enter__() method to allocate resources, for example, and the __exit__() method to release them after the context block termination.

The methods __enter__()  and __exit__() return a context manager object.

We write a context manager class as below:


context manager class contains both the __enter__() and the __exit__() methods.
The __exit__ () method must have three arguments.


Leave as a comment: