Search code examples
pythonoopcontextmanager

Entering to context manager with method of instance


I would like to implement a context manager in my class that wouldn't create a new instance but would be invoked on an existing one using a certain method,

so that in usage, it would look as follows:

some_instance = SomeClass()

with some_instance.context_manager_method():
    ... # do something

is it possible?


Solution

  • Sure. You can use contextlib.contextmanager to create any context manager that you want. Here's a snippet:

    from contextlib import contextmanager
    
    class SomeClass:
        @contextmanager
        def context_manager_method(self):
            # setup
            yield
            # teardown