Python:For
lastmod 2021-03-29created 2021-03-292 edits
How to use for and async for in python.
async for
To make a class that works with async for, you must implement the __aiter__ and __anext__ methods (meaning asynchronous iter and asynchronous next). And the methods must be defined with async def.
async for is available from Python 3.5 onward.
Example
The following is an asynchronous iterator that produces a number every second:
import asyncio
class AsyncCounter:
def __init__(self, stop):
self.current = 0
self.stop = stop
def __aiter__(self):
return self
async def __anext__(self):
if self.current < self.stop:
await asyncio.sleep(1.0)
r = self.current
self.current += 1
return r
else:
raise StopAsyncIteration
async def main():
async for i in AsyncCounter(3): # for 앞에 async를 붙임
print(i, end=' ')
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
Generator style
You can also make an asynchronous iterator in generator style using yield. As shown below, create a native coroutine with async def and pass values out with yield.
Available from Python 3.6 onward.
import asyncio
async def async_counter(stop): # 제너레이터 방식으로 만들기
n = 0
while n < stop:
yield n
n += 1
await asyncio.sleep(1.0)
async def main():
async for i in async_counter(3): # for 앞에 async를 붙임
print(i, end=' ')
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
One-line usage
See also
Pages that link here