Context without manager

Piergiorgio Sartor piergiorgio.sartor.this.should.not.be.used at nexgo.REMOVETHIS.de
Sat Nov 25 16:15:58 EST 2023


Hi all,

I apologize in advance for the "foggy"
question, but I've myself unclear ideas.

Anyway...

Python has "context manager".
For example, the "open()" class can be
simply used as follow:

with open(...) as fp:
   fp.do_something()

On the other hand, it is also possible to do:

fp = open()
fp.do_something()
fp.close()

Now, if we want to use "open()" in a class,
it would be possible to apply the second
variant, with "self.fp = open()" in "__init__(...)",
"self.fp.close()" maybe in "__del__(...)" and having
few methods doing this and that with the "self.fp".

Apparently, the "with" context manager is not usable
in classes, at least not with __init__() & co.

It seems there are classes ("gradio.Blocks()", for
example) which are *only* usable with context manager.

I found more...

One way to do the same as in "open()" is:

def __init__(...):
   fp = open(...)
   fp.__enter__()
...
def __del__(...):
   fp.__exit__()
   fp.close()

This works, but it seems quite ugly.
I could not find any other way, in case the
class do only support context manager.

Question: is there any other way to use a
context manager only object within a class,
with methods accessing the object?

Or any other solution to the same situation?

Thanks a lot in advance.

P.S.: currently gmail posts are deleted, due
to excessive spam, so I'll not see any reply
coming from this family of addresses.

bye,

-- 

piergiorgio


More information about the Python-list mailing list