09-12-2015
1,781,
705
Join Date: May 2008
Last Activity: 10 November 2021, 5:38 PM EST
Posts: 1,781
Thanks Given: 62
Thanked 705 Times in 653 Posts
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.
Last edited by Aia; 09-12-2015 at 08:57 PM..