Linked Questions

Popular Questions

In python, I'd like to use a with-statement context manager when using a particular third-party package because their context manager will handle clean-up for me in a best-practice way.

Right now I have (say):

class MyClass(object):

    def __init__(self):

    def open(self):
        # Instantiate something *e.g.* open() a file

    def run(self):
        # Do some work *e.g.* read() from a filehandle

    def cleanup(self):
        # Clean everything up *e.g.* close() filehandle

This would then be called as

my_obj = MyClass()

I'd ideally like to do all this using a context manager referenced within the class (if possible). It's the run() method that needs the context here. I am not sure how to do this - here are some theoretical attempts:

Option 1:

with my_obj2.third_party_context_manager_method() as mcmm:

Option 2:


Bonus: Now, in fact I need a double context manager in this case - how on earth..?

Please note: The file open example is just an example! My case is somewhat more complicated but the idea is that if I can make it work for that I can achieve anything :)

Another note: The use case is a dask cluster/client cleanup scenario - REF: How can I exit Dask cleanly?

Related Questions