Skip to content
Snippets Groups Projects
Commit d2730841 authored by Piotr Maślanka's avatar Piotr Maślanka
Browse files

add context manager to SelfClosingGenerator

parent 4ca1fc47
No related branches found
No related tags found
No related merge requests found
# v2.7.38
* added context manager to SelfClosingGenerator
__version__ = '2.7.38_a1'
__version__ = '2.7.38_a2'
......@@ -23,6 +23,8 @@ class SelfClosingGenerator:
This will additionally exhaust the generator upon deallocation of the generator.
You can feed it with either generators, or generator-functions, it will behave correctly each time.
You can also use it as a context manager, to decouple finalizing the generator from the GC collection:
"""
__slots__ = ('generator', 'stopped')
......@@ -46,6 +48,13 @@ class SelfClosingGenerator:
self.stopped = True
raise
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
return False
def close(self):
if not self.stopped:
try:
......
......@@ -26,3 +26,18 @@ class TestIterators(unittest.TestCase):
break
self.assertTrue(a['done'])
def test_self_closing_generator_function(self):
a = {'done': False}
def generator():
for i in range(5):
yield i
a['done'] = True
with SelfClosingGenerator(generator)() as gen:
for b in gen:
if b == 2:
break
self.assertTrue(a['done'])
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment