Python Forum
How to inspect the code of __exit__ method used with 'with' statement?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to inspect the code of __exit__ method used with 'with' statement?
#1
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
Reply
#2
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
Reply
#3
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.
Reply
#4
Thanks for your replies! ;)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Photo Python code: While loop with if statement HAMOUDA 1 578 Sep-18-2023, 11:18 AM
Last Post: deanhystad
  An unexplainable error in .format statement - but only in a larger piece of code? ToniE 4 720 Sep-05-2023, 12:50 PM
Last Post: ToniE
  code won't advance to next statement MCL169 2 759 Apr-11-2023, 09:44 PM
Last Post: Larz60+
  List Creation and Position of Continue Statement In Regular Expression Code new_coder_231013 3 1,673 Jun-15-2022, 12:00 PM
Last Post: new_coder_231013
  Inspecting without using inspect deanhystad 3 1,592 Nov-11-2021, 07:17 PM
Last Post: snippsat
  Unable to understand a statement in an existing code ateestructural 1 2,232 Aug-01-2020, 09:38 PM
Last Post: deanhystad
  Inspect.getmembers with isclass returns an empty list Aldar 1 2,787 Oct-02-2019, 01:48 PM
Last Post: Aldar
  How to call a method in a module using code KingPieter 4 3,017 Jan-15-2019, 09:13 PM
Last Post: KingPieter
  Trying to code backwords in if statement for different output in some scenarios skrivver99 1 2,445 Dec-03-2018, 01:32 AM
Last Post: Windspar
  module inspect error jupiter 1 2,787 Sep-17-2018, 08:37 AM
Last Post: Mekire

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020