Context without manager

David Raymond David.Raymond at tomtom.com
Mon Nov 27 12:58:40 EST 2023


> I *must* do:
> 
> with device_open() as device:
>    device.do_something()
> 
> Nevertheless, I _need_ to have a class
> where the device is opened in the __init__()
> and used in some methods.
> 
> Any ideas?

Perhaps take a look at contextlib.ExitStack and see if you can do something with it.

(Below is not tested)

import contextlib
class myClass:
    def __init__(self):
        self._exitStack = contextlib.ExitStack()
        device = self._exitStack.enter_context(device_open(...))
    def __del__(self):
        self._exitStack.close()


More information about the Python-list mailing list