-
Notifications
You must be signed in to change notification settings - Fork 0
/
break_from_async_for.py
85 lines (65 loc) · 2.03 KB
/
break_from_async_for.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import asyncio
import itertools
from typing import AsyncGenerator, AsyncIterator
async def numbers(delay: int = 1):
g = itertools.count()
generator_exit = False
for i in g:
await asyncio.sleep(delay)
print("before", i)
try:
yield i
except GeneratorExit:
print("---------------------------------- GENERATOR EXIT")
import traceback
traceback.print_stack()
generator_exit = True
except:
print("---------------------------------- GENRATOR THROW")
raise
print("after", i)
if generator_exit:
break
class ClassGen(AsyncIterator):
def __init__(self):
self.done = False
self.g = itertools.count()
async def asend(self, __value):
return await super().asend(__value)
async def athrow(self, __typ, __val = None, __tb = None):
self.done = True
return await super().athrow(__typ, __val, __tb)
async def aclose(self):
self.done = True
async def __anext__(self):
if self.done:
raise StopAsyncIteration()
return self.g.__next__()
async def worker(gen, cutoff=None):
cnt = 0
async for i in gen:
yield i
if cnt >= cutoff:
# no, it just drops the generator and the code
# never has a chance to return to the generator
# break
# the generator correctly receives the exception as long as the code calling this
# worker passes the exception to the generator
raise Exception("a")
# this correctly bubbles upwards
await gen.aclose()
cnt += 1
async def main(cutoff):
print("start")
nums = numbers()
try:
async for w in worker(nums, cutoff):
print(w)
except Exception as e:
print("----------------------------------------------------------------------", e)
await nums.athrow(e)
print("stop")
try:
asyncio.run(main(1))
except:
pass