Skip to content Skip to sidebar Skip to footer

Generator And Context Manager At The Same Time

Imagine I have some code that I want it to run: with F() as o: while True: a = o.send(2) print(a) It means that the F class should return an generator and also

Solution 1:

You can use collections.abc and subclass your class F from Generator (manual pages). If you implement enter and exit, your instance will be generator and have context manager support as well:

from collections.abc import Generator

classF(Generator):
    def__init__(self):
        self.__my_generator = self._my_generator()
        next(self.__my_generator)   # prime the generatordef_my_generator(self):
        whileTrue:
            v = yield42print('generator received ', v)

    # context manager interace:def__enter__(self):
        return self

    def__exit__(self, *exc):
        print('exit')

    # Generator interface:defsend(self, value):
        return self.__my_generator.send(value)

    defthrow(self, typ, value=None, traceback=None):
        return self.__my_generator.throw(typ, value, traceback)


with F() as o:
    whileTrue:
        a = o.send(2)
        print('I received ', a)

Prints:

generator received  2I received  42
...etc.

Post a Comment for "Generator And Context Manager At The Same Time"