Neil G
Neil G

Reputation: 33202

Inheritance with contextlib.contextmanager

Given a class

class SomeClass:
    @contextlib.contextmanager
    def on_connection(self, target_terminal, source_terminal):
        ...
        yield
        ...

How do you inherit from it?

Upvotes: 2

Views: 1209

Answers (1)

Neil G
Neil G

Reputation: 33202

It's possible to combine the contextlib.contextmanager pattern with a with block to bring in the superclass' context manager:

class SomeDerivedClass(SomeClass):
    @contextlib.contextmanager
    def on_connection(self, target_terminal, source_terminal):
        with super().on_connection(target_terminal, source_terminal):
            ...
            try:
                yield
            finally:
                ...

Upvotes: 2

Related Questions