- Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathlesson04_async_iterator.py
More file actions
Latest commit
34 lines (29 loc) · 861 Bytes
/
Copy pathlesson04_async_iterator.py
File metadata and controls
34 lines (29 loc) · 861 Bytes
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
# SuperFastPython.com
# example of an async iterator with async for loop
importasyncio
# define an asynchronous iterator
classAsyncIterator():
# constructor, define some state
def__init__(self):
self.counter=0
# create an instance of the iterator
def__aiter__(self):
returnself
# return the next awaitable
asyncdef__anext__(self):
# check for no further items
ifself.counter>=10:
raiseStopAsyncIteration
# increment the counter
self.counter+=1
# simulate work
awaitasyncio.sleep(1)
# return the counter value
returnself.counter
# main coroutine
asyncdefmain():
# loop over async iterator with async for loop
asyncforiteminAsyncIterator():
print(item)
# execute the asyncio program
asyncio.run(main())