Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading