async_for2.py 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # test waiting within "async for" aiter/anext functions
  2. import sys
  3. if sys.implementation.name == 'micropython':
  4. # uPy allows normal generators to be awaitables
  5. coroutine = lambda f: f
  6. else:
  7. import types
  8. coroutine = types.coroutine
  9. @coroutine
  10. def f(x):
  11. print('f start:', x)
  12. yield x + 1
  13. yield x + 2
  14. return x + 3
  15. class ARange:
  16. def __init__(self, high):
  17. print('init')
  18. self.cur = 0
  19. self.high = high
  20. async def __aiter__(self):
  21. print('aiter')
  22. print('f returned:', await f(10))
  23. return self
  24. async def __anext__(self):
  25. print('anext')
  26. print('f returned:', await f(20))
  27. if self.cur < self.high:
  28. val = self.cur
  29. self.cur += 1
  30. return val
  31. else:
  32. raise StopAsyncIteration
  33. async def coro():
  34. async for x in ARange(4):
  35. print('x', x)
  36. o = coro()
  37. try:
  38. while True:
  39. print('coro yielded:', o.send(None))
  40. except StopIteration:
  41. print('finished')