forked from adafruit/circuitpython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync_for.py
75 lines (49 loc) · 1.3 KB
/
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
# test basic async for execution
# example taken from PEP0492
class AsyncIteratorWrapper:
def __init__(self, obj):
print("init")
self._obj = obj
def __repr__(self):
return "AsyncIteratorWrapper-" + self._obj
def __aiter__(self):
print("aiter")
return AsyncIteratorWrapperIterator(self._obj)
class AsyncIteratorWrapperIterator:
def __init__(self, obj):
print("init")
self._it = iter(obj)
async def __anext__(self):
print("anext")
try:
value = next(self._it)
except StopIteration:
raise StopAsyncIteration
return value
def run_coro(c):
print("== start ==")
try:
c.send(None)
except StopIteration:
print("== finish ==")
async def coro0():
async for letter in AsyncIteratorWrapper("abc"):
print(letter)
run_coro(coro0())
async def coro1():
a = AsyncIteratorWrapper("def")
async for letter in a:
print(letter)
print(a)
run_coro(coro1())
a_global = AsyncIteratorWrapper("ghi")
async def coro2():
async for letter in a_global:
print(letter)
print(a_global)
run_coro(coro2())
async def coro3(a):
async for letter in a:
print(letter)
print(a)
run_coro(coro3(AsyncIteratorWrapper("jkl")))