Skip to content
This repository was archived by the owner on May 27, 2025. It is now read-only.

Commit f536cf9

Browse files
committed
vault backup: 2025-01-11 17:29:33
1 parent 3ebe74a commit f536cf9

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

content/programming/languages/python/asyncio/running-a-bunch-of-futures-safely.md

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,13 +79,37 @@ import asyncio
7979
from collections.abc import Awaitable, Iterable
8080
from typing import TypeVar
8181

82-
T = TypeVar("T")
82+
T = TypeVar("T") # for compatibility with python <=3.11
8383

8484

85-
async def run_futures(coros: Iterable[Awaitable[T]]) -> list[T]:
85+
async def gather_tg(coros: *Awaitable[T]) -> list[T]:
8686
async with asyncio.TaskGroup() as tg:
8787
tasks: list[asyncio.Task] = [tg.create_task(coro) for coro in coros]
8888
return [t.result() for t in tasks]
8989
```
9090

91-
Now, we can use it.
91+
Then, we can use it:
92+
93+
```python
94+
async def func1(val: int) -> int:
95+
return val
96+
97+
async def func2(val: str) -> int:
98+
return len(val)
99+
100+
async def func3(val: str) -> str:
101+
return val
102+
103+
104+
async def main() -> None:
105+
results_1 = await gather_tg(*[func1(val) for val in range(5)])
106+
print(results_1) # mypy thinks type is lint[int]
107+
108+
results_2 = await gather_tg(func1(1), func2("4"))
109+
print(results_2) # mypy thinks type is lint[int]
110+
111+
results_3 = await gather_tg(func2("1"), func3("4"))
112+
print(results_3) # mypy thinks type is lint[int | str]
113+
```
114+
115+
Interestingly, `mypy` throws an error on the `[tg.create_task(coro) for coro in coros]` block, claiming that `Argument 1 to "create_task" of "TaskGroup" has incompatible type "Awaitable[T]"; expected "Coroutine[Any, Any, Any]. Mypy[arg-type]`. But... it's right.

0 commit comments

Comments
 (0)