0

Suppose we have an object, which is intended to be used with with:

with somefunction() as f:
   ...
   f.somemethod()

Now I want to use it within class, to make object available full lifetime of class instance.

In constructor I would write

class MyClass:
   def __init__(self):
      self.f = somefunction().__enter__()

Where should I call __exit__() then?

Dims
  • 47,675
  • 117
  • 331
  • 600

1 Answers1

0

If somefunction is an object, first we could name it someobject and do something like:

class MyClass(object):

    def __init__(self, someobject):
        self._someobject = someobject


    def dothing(self):
        with self._someobject() as so:
            so.somemethod()


myinstance = MyClass(someobject)
myinstance.dothing()
Arount
  • 9,853
  • 1
  • 30
  • 43