You have to get the generator to go out. If the nature of the generator should look forever, you can use gen.throw () to throw an exception in the generator.
Actually, I just looked at the specification for generators, and they have a close () method that does just that (it throws a GeneratorExit () exception inside the generator. So just call gen.close () when you are done with any manager the context will refer to its exit methods.The generator will use an exception, so you donโt have to wrap the close () call in the try block:
>>> b= bar() >>> b.next() setup 'bar' >>> b.close() cleanup >>>
source share