Oct-04-2017, 08:25 AM
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
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