Skip to content

Commit 104ce52

Browse files
committed
Sample code for the article on asyncio
1 parent 757644a commit 104ce52

File tree

11 files changed

+279
-0
lines changed

11 files changed

+279
-0
lines changed

python-asyncio/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Async I/O in Python: A Complete Walkthrough
2+
3+
This folder provides the code examples for the Real Python tutorial [Async I/O in Python: A Complete Walkthrough](https://realpython.com/async-io-python/).

python-asyncio/as_completed.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import asyncio
2+
import time
3+
4+
5+
async def coro(numbers):
6+
await asyncio.sleep(min(numbers))
7+
return list(reversed(numbers))
8+
9+
10+
async def main():
11+
task1 = asyncio.create_task(coro([3, 2, 1]))
12+
task2 = asyncio.create_task(coro([10, 5, 2]))
13+
print("Start:", time.strftime("%X"))
14+
for task in asyncio.as_completed([task1, task2]):
15+
result = await task
16+
print(f'result: {result} completed at {time.strftime("%X")}')
17+
print("End:", time.strftime("%X"))
18+
print(f"Both tasks done: {all((task1.done(), task2.done()))}")
19+
20+
21+
asyncio.run(main())

python-asyncio/chained.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import asyncio
2+
import random
3+
import time
4+
5+
6+
async def fetch_user(user_id):
7+
delay = random.uniform(0.5, 2.0)
8+
print(f"User coro: fetching user by {user_id=}...")
9+
await asyncio.sleep(delay)
10+
user = {"id": user_id, "name": f"User{user_id}"}
11+
print(f"User coro: fetched user with {user_id=} (done in {delay:.1f}s).")
12+
return user
13+
14+
15+
async def fetch_posts(user):
16+
delay = random.uniform(0.5, 2.0)
17+
print(f"Post coro: retrieving posts for {user['name']}...")
18+
await asyncio.sleep(delay)
19+
posts = [f"Post {i} by {user['name']}" for i in range(1, 3)]
20+
print(
21+
f"Post coro: got {len(posts)} posts by {user['name']}"
22+
f" (done in {delay:.1f}s):"
23+
)
24+
for post in posts:
25+
print(f" - {post}")
26+
27+
28+
async def get_user_with_posts(user_id):
29+
user = await fetch_user(user_id)
30+
await fetch_posts(user)
31+
32+
33+
async def main():
34+
user_ids = [1, 2, 3]
35+
start = time.perf_counter()
36+
await asyncio.gather(
37+
*(get_user_with_posts(user_id) for user_id in user_ids)
38+
)
39+
end = time.perf_counter()
40+
print(f"\n==> Total time: {end - start:.2f} seconds")
41+
42+
43+
if __name__ == "__main__":
44+
random.seed(444)
45+
asyncio.run(main())

python-asyncio/countasync.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import asyncio
2+
3+
4+
async def count():
5+
print("One")
6+
await asyncio.sleep(1)
7+
print("Two")
8+
await asyncio.sleep(1)
9+
10+
11+
async def main():
12+
await asyncio.gather(count(), count(), count())
13+
14+
15+
if __name__ == "__main__":
16+
import time
17+
18+
start = time.perf_counter()
19+
asyncio.run(main())
20+
elapsed = time.perf_counter() - start
21+
print(f"{__file__} executed in {elapsed:0.2f} seconds.")

python-asyncio/countsync.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import time
2+
3+
4+
def count():
5+
print("One")
6+
time.sleep(1)
7+
print("Two")
8+
time.sleep(1)
9+
10+
11+
def main():
12+
for _ in range(3):
13+
count()
14+
15+
16+
if __name__ == "__main__":
17+
start = time.perf_counter()
18+
main()
19+
elapsed = time.perf_counter() - start
20+
print(f"{__file__} executed in {elapsed:0.2f} seconds.")

python-asyncio/gathers.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import asyncio
2+
import time
3+
4+
5+
async def coro(numbers):
6+
await asyncio.sleep(min(numbers))
7+
return list(reversed(numbers))
8+
9+
10+
async def main():
11+
task1 = asyncio.create_task(coro([3, 2, 1]))
12+
task2 = asyncio.create_task(coro([10, 5, 2]))
13+
print("Start:", time.strftime("%X"))
14+
result = await asyncio.gather(task1, task2)
15+
print("End:", time.strftime("%X"))
16+
print(f"Both tasks done: {all((task1.done(), task2.done()))}")
17+
return result
18+
19+
20+
result = asyncio.run(main())
21+
print(f"result: {result}")

python-asyncio/powers.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import asyncio
2+
3+
4+
async def powers_of_two(stop=10):
5+
exponent = 0
6+
while exponent < stop:
7+
yield 2**exponent
8+
exponent += 1
9+
await asyncio.sleep(0.2) # Simulate some asynchronous work
10+
11+
12+
async def main():
13+
g = []
14+
async for i in powers_of_two(5):
15+
g.append(i)
16+
print(g)
17+
18+
f = [j async for j in powers_of_two(5) if not (j // 3 % 5)]
19+
print(f)
20+
21+
22+
if __name__ == "__main__":
23+
asyncio.run(main())

python-asyncio/queued.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import asyncio
2+
import random
3+
import time
4+
5+
6+
async def producer(queue, user_ids):
7+
async def fetch_user(user_id):
8+
delay = random.uniform(0.5, 2.0)
9+
print(f"Producer: fetching user by {user_id=}...")
10+
await asyncio.sleep(delay)
11+
user = {"id": user_id, "name": f"User{user_id}"}
12+
print(f"Producer: fetched user with {user_id=} (done in {delay:.1f}s)")
13+
await queue.put(user)
14+
15+
await asyncio.gather(*(fetch_user(uid) for uid in user_ids))
16+
for _ in range(len(user_ids)):
17+
await queue.put(None) # Sentinels for consumers to terminate
18+
19+
20+
async def consumer(queue):
21+
while True:
22+
user = await queue.get()
23+
if user is None:
24+
break
25+
delay = random.uniform(0.5, 2.0)
26+
print(f"Consumer: retrieving posts for {user['name']}...")
27+
await asyncio.sleep(delay)
28+
posts = [f"Post {i} by {user['name']}" for i in range(1, 3)]
29+
print(
30+
f"Consumer: got {len(posts)} posts by {user['name']}"
31+
f" (done in {delay:.1f}s):"
32+
)
33+
for post in posts:
34+
print(f" - {post}")
35+
36+
37+
async def main():
38+
queue = asyncio.Queue()
39+
user_ids = [1, 2, 3]
40+
41+
start = time.perf_counter()
42+
await asyncio.gather(
43+
producer(queue, user_ids),
44+
*(consumer(queue) for _ in user_ids),
45+
)
46+
end = time.perf_counter()
47+
print(f"\n==> Total time: {end - start:.2f} seconds")
48+
49+
50+
if __name__ == "__main__":
51+
random.seed(444)
52+
asyncio.run(main())

python-asyncio/rand.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import asyncio
2+
import random
3+
4+
COLORS = (
5+
"\033[0m", # End of color
6+
"\033[36m", # Cyan
7+
"\033[91m", # Red
8+
"\033[35m", # Magenta
9+
)
10+
11+
12+
async def makerandom(delay, threshold=6):
13+
color = COLORS[delay]
14+
print(f"{color}Initiated makerandom({delay}).")
15+
while (number := random.randint(0, 10)) <= threshold:
16+
print(f"{color}makerandom({delay}) == {number} too low; retrying.")
17+
await asyncio.sleep(delay)
18+
print(f"{color}---> Finished: makerandom({delay}) == {number}" + COLORS[0])
19+
return number
20+
21+
22+
async def main():
23+
result = await asyncio.gather(
24+
makerandom(1, 9),
25+
makerandom(2, 8),
26+
makerandom(3, 8),
27+
)
28+
return result
29+
30+
31+
if __name__ == "__main__":
32+
random.seed(444)
33+
r1, r2, r3 = asyncio.run(main())
34+
print()
35+
print(f"r1: {r1}, r2: {r2}, r3: {r3}")

python-asyncio/tasks.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import asyncio
2+
3+
4+
async def coro(numbers):
5+
await asyncio.sleep(min(numbers))
6+
return list(reversed(numbers))
7+
8+
9+
async def main():
10+
task = asyncio.create_task(coro([3, 2, 1]))
11+
print(f"task: type -> {type(task)}")
12+
print(f"task: done -> {task.done()}")
13+
return await task
14+
15+
16+
result = asyncio.run(main())
17+
print(f"result: {result}")

0 commit comments

Comments
 (0)