Python Forum

Full Version: How to inspect the code of __exit__ method used with 'with' statement?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I am new to Python.
I somehow understand the concept about context managers with __enter__ / __exit__ methods, which I can use with 'with' statement.
But my issue is that every explanation I could find described either a self-written __enter__/__exit__ methods or it was a plain statement that for example using 'with' statement with open() ensures that the file is eventually be closed no matter what happens inside the 'with' block.

So it is well known that 'with' statement together with open() function ensures proper file closure at the end.
Or 'with' together with database connection ensures the DB connection to be closed no matter what.

But how do I know which other python built-in functions I can use inside 'with' block?
And how do I know how does the __exit__ method behave in each case?

Thanks.
Martin
You can start with the original pep343 here: https://www.python.org/dev/peps/pep-0343/
and then search here: https://www.python.org/search/?q=PEP+343&submit=
for enhancements
Aside from files, database connections, and locks, I don't think there is anything else in the lib which uses them.  They really only make sense for a resource you're temporarily using, which you need to acquire and then release.
Thanks for your replies! ;)