AsyncIO in Python
Here are some insights into topics about the async programming in python
import asyncio
@async_timeit
async def factorial(name, number):
f = 1
for i in range(2, number + 1):
print(f"Task {name}: Compute factorial({number}), currently i={i}...")
await asyncio.sleep(1)
f *= i
print(f"Task {name}: factorial({number}) = {f}")
return f
@async_timeit
async def main():
# Schedule three calls *concurrently*:
L = await asyncio.gather(
factorial("A", 2),
factorial("B", 3),
factorial("C", 4),
)
print(L)
asyncio.run(main())
And the output in the shell will look like the following:
Task A: Compute factorial(2), currently i=2...
Task B: Compute factorial(3), currently i=2...
Task C: Compute factorial(4), currently i=2...
Task A: factorial(2) = 2
func:'factorial' args:[('A', 2), {}] took: 1.0011 sec
Task B: Compute factorial(3), currently i=3...
Task C: Compute factorial(4), currently i=3...
Task B: factorial(3) = 6
func:'factorial' args:[('B', 3), {}] took: 2.0125 sec
Task C: Compute factorial(4), currently i=4...
Task C: factorial(4) = 24
func:'factorial' args:[('C', 4), {}] took: 3.0248 sec
[2, 6, 24]
func:'main' args:[(), {}] took: 3.0248 sec
Drag the keywords to the right places to complete the code example:
drop here!
def main():
L =
drop here!
asyncio.gather(...)