Python Forum
getting my head arounnd __enter__() for my new class
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
getting my head arounnd __enter__() for my new class
#1
i am creating a class to open a file via one of a few other methods/function based on the name to be opened. if the name of the file ends with '.bz2' then it will import bz2 and call bz2.open() to get an object that will compress or uncompress the file as it writes or reads it.

so i am trying to add context management for this class so it can be used on a with statement. i am working on __enter__() first. but this is confusing about what argument(s) it will get and what it should return when. the __exit__() seems simple but even it has confusion. PEP343 got into a lot of other details and i was unable to match it up to my misunderstanding of this API.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
I don't think __enter__ takes any argument apart from self. It may return anything.

As the documentation says, the return value of __exit__ is converted into a boolean to see if the potential exception that occurred in the with block should be suppressed or propagated. The default is propagated because functions return None by default.
Reply
#3
(Nov-28-2020, 12:18 PM)Gribouillis Wrote: propagated
what does "propagated" mean, in this context?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
Skaperen Wrote:what does "propagated" mean, in this context?
I mean it in the sense of exceptions propagation. When an exception is raised, it goes up the calling stack like a bubble until it is caught by some scope in the stack, and if it is never caught, the program exits. One usually say that un uncaught exception propagates to the calling frame. In the case of the with statement, if an exception occurs in the with block, it propagates to the calling frame unless the __exit__ method returns a true value.
Reply
#5
the interpreter engine can have a catch at the top scoped for everything with an action to dump and exit. is that like what you mean?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#6
Yes, you're right but this is not related to the __exit__ method.

Here is an example of suppressed exception
>>> class A:
...     def __enter__(self): pass
...     def __exit__(self, *args): return True
... 
>>> with A():
...     1/0
... 
>>> 
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  parser for LVM head Skaperen 0 1,404 Nov-02-2019, 04:04 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

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