2016-04-13 10:27:06 -04:00
|
|
|
# test basic async for execution
|
|
|
|
# example taken from PEP0492
|
|
|
|
|
2023-05-19 03:00:53 -04:00
|
|
|
|
2016-04-13 10:27:06 -04:00
|
|
|
class AsyncIteratorWrapper:
|
|
|
|
def __init__(self, obj):
|
2023-05-19 03:00:53 -04:00
|
|
|
print("init")
|
|
|
|
self._obj = obj
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return "AsyncIteratorWrapper-" + self._obj
|
2016-04-13 10:27:06 -04:00
|
|
|
|
2020-07-21 13:47:28 -04:00
|
|
|
def __aiter__(self):
|
2023-05-19 03:00:53 -04:00
|
|
|
print("aiter")
|
|
|
|
return AsyncIteratorWrapperIterator(self._obj)
|
|
|
|
|
|
|
|
|
|
|
|
class AsyncIteratorWrapperIterator:
|
|
|
|
def __init__(self, obj):
|
|
|
|
print("init")
|
|
|
|
self._it = iter(obj)
|
2016-04-13 10:27:06 -04:00
|
|
|
|
|
|
|
async def __anext__(self):
|
2023-05-19 03:00:53 -04:00
|
|
|
print("anext")
|
2016-04-13 10:27:06 -04:00
|
|
|
try:
|
|
|
|
value = next(self._it)
|
|
|
|
except StopIteration:
|
|
|
|
raise StopAsyncIteration
|
|
|
|
return value
|
|
|
|
|
2023-05-19 03:00:53 -04:00
|
|
|
|
|
|
|
def run_coro(c):
|
|
|
|
print("== start ==")
|
|
|
|
try:
|
|
|
|
c.send(None)
|
|
|
|
except StopIteration:
|
|
|
|
print("== finish ==")
|
|
|
|
|
|
|
|
|
|
|
|
async def coro0():
|
|
|
|
async for letter in AsyncIteratorWrapper("abc"):
|
2016-04-13 10:27:06 -04:00
|
|
|
print(letter)
|
|
|
|
|
2023-05-19 03:00:53 -04:00
|
|
|
|
|
|
|
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")))
|