Context Managers in Python

Could anyone please explain Context Managers in Python with some detailed example or any URL that explains in detail?

Initially tried to get some help from google... but not much satisfied.

Thanks in advance...

Regards,
J

A Context Manager is any class that must, at least, implement a __enter__() method and a __exit__() method. The purpose of this class is to setup, or build up an object and tear it down when you are done with it.
The __enter__() method would initialize the object, it would utilized the try, except and finally statements, and it would produce a proper return.
The __exit__() method would do the proper clean up after the object is not necessary any longer.

A common example of using a Context Manager is with opening files.
If you do it manually, you would have to do the checks necessary: that the file exists, that it can be accessed and opened, etc. After that you need to release the object file by closing it. This setup and tear-down action can be taken care of, nicely, using a Context Manager.