# Context Managers in Python

**URL:** <https://community.unix.com/t/context-managers-in-python/355327>\
**Category:** Shell Programming and Scripting\
**Created:** [September 12, 2015, 11:46am UTC](https://community.unix.com/t/context-managers-in-python/355327 "2015-09-12T11:46:31Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![scriptscript](https://community.unix.com/letter_avatar/scriptscript/32/6_449c533f586939b6e5f246632a46421f.png) [@scriptscript](https://community.unix.com/u/scriptscript)\
**Post date:** [September 12, 2015, 11:46am UTC](https://community.unix.com/t/context-managers-in-python/355327/1 "2015-09-12T11:46:31Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Aia](https://community.unix.com/user_avatar/community.unix.com/aia/32/917_2.png) [@Aia](https://community.unix.com/u/Aia)\
**Post date:** [September 12, 2015, 1:00pm UTC](https://community.unix.com/t/context-managers-in-python/355327/2 "2015-09-12T13:00:19Z")

</div>

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.
