Skip to content

Commit c7fdb6a

Browse files
committed
TR updates, first round
1 parent 104ce52 commit c7fdb6a

File tree

7 files changed

+77
-43
lines changed

7 files changed

+77
-43
lines changed

python-asyncio/as_completed.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ async def coro(numbers):
88

99

1010
async def main():
11-
task1 = asyncio.create_task(coro([3, 2, 1]))
12-
task2 = asyncio.create_task(coro([10, 5, 2]))
11+
task1 = asyncio.create_task(coro([10, 5, 2]))
12+
task2 = asyncio.create_task(coro([3, 2, 1]))
1313
print("Start:", time.strftime("%X"))
1414
for task in asyncio.as_completed([task1, task2]):
1515
result = await task

python-asyncio/chained.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,21 @@
33
import time
44

55

6+
async def main():
7+
user_ids = [1, 2, 3]
8+
start = time.perf_counter()
9+
await asyncio.gather(
10+
*(get_user_with_posts(user_id) for user_id in user_ids)
11+
)
12+
end = time.perf_counter()
13+
print(f"\n==> Total time: {end - start:.2f} seconds")
14+
15+
16+
async def get_user_with_posts(user_id):
17+
user = await fetch_user(user_id)
18+
await fetch_posts(user)
19+
20+
621
async def fetch_user(user_id):
722
delay = random.uniform(0.5, 2.0)
823
print(f"User coro: fetching user by {user_id=}...")
@@ -25,21 +40,6 @@ async def fetch_posts(user):
2540
print(f" - {post}")
2641

2742

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-
4343
if __name__ == "__main__":
4444
random.seed(444)
4545
asyncio.run(main())

python-asyncio/except_group.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import asyncio
2+
3+
4+
async def coro_a():
5+
await asyncio.sleep(1)
6+
raise ValueError("Error in coro A")
7+
8+
9+
async def coro_b():
10+
await asyncio.sleep(2)
11+
raise TypeError("Error in coro B")
12+
13+
14+
async def coro_c():
15+
await asyncio.sleep(0.5)
16+
raise IndexError("Error in coro C")
17+
18+
19+
async def main():
20+
results = await asyncio.gather(
21+
coro_a(), coro_b(), coro_c(), return_exceptions=True
22+
)
23+
exceptions = [e for e in results if isinstance(e, Exception)]
24+
if exceptions:
25+
raise ExceptionGroup("Errors", exceptions)
26+
27+
28+
try:
29+
asyncio.run(main())
30+
except* ValueError as ve_group:
31+
print(f"[ValueError handled] {ve_group.exceptions}")
32+
except* TypeError as te_group:
33+
print(f"[TypeError handled] {te_group.exceptions}")
34+
except* IndexError as ie_group:
35+
print(f"[IndexError handled] {ie_group.exceptions}")

python-asyncio/gathers.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ async def coro(numbers):
88

99

1010
async def main():
11-
task1 = asyncio.create_task(coro([3, 2, 1]))
12-
task2 = asyncio.create_task(coro([10, 5, 2]))
11+
task1 = asyncio.create_task(coro([10, 5, 2]))
12+
task2 = asyncio.create_task(coro([3, 2, 1]))
1313
print("Start:", time.strftime("%X"))
1414
result = await asyncio.gather(task1, task2)
1515
print("End:", time.strftime("%X"))

python-asyncio/queued.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,19 @@
33
import time
44

55

6+
async def main():
7+
queue = asyncio.Queue()
8+
user_ids = [1, 2, 3]
9+
10+
start = time.perf_counter()
11+
await asyncio.gather(
12+
producer(queue, user_ids),
13+
*(consumer(queue) for _ in user_ids),
14+
)
15+
end = time.perf_counter()
16+
print(f"\n==> Total time: {end - start:.2f} seconds")
17+
18+
619
async def producer(queue, user_ids):
720
async def fetch_user(user_id):
821
delay = random.uniform(0.5, 2.0)
@@ -34,19 +47,6 @@ async def consumer(queue):
3447
print(f" - {post}")
3548

3649

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-
5050
if __name__ == "__main__":
5151
random.seed(444)
5252
asyncio.run(main())

python-asyncio/rand.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,14 @@
99
)
1010

1111

12+
async def main():
13+
return await asyncio.gather(
14+
makerandom(1, 9),
15+
makerandom(2, 8),
16+
makerandom(3, 8),
17+
)
18+
19+
1220
async def makerandom(delay, threshold=6):
1321
color = COLORS[delay]
1422
print(f"{color}Initiated makerandom({delay}).")
@@ -19,15 +27,6 @@ async def makerandom(delay, threshold=6):
1927
return number
2028

2129

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-
3130
if __name__ == "__main__":
3231
random.seed(444)
3332
r1, r2, r3 = asyncio.run(main())

python-asyncio/tasks.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ async def coro(numbers):
88

99
async def main():
1010
task = asyncio.create_task(coro([3, 2, 1]))
11-
print(f"task: type -> {type(task)}")
12-
print(f"task: done -> {task.done()}")
11+
print(f"{type(task) = }")
12+
print(f"{task.done() = }")
1313
return await task
1414

1515

0 commit comments

Comments
 (0)