Skip to content

Commit 493e35b

Browse files
Make asyncio.Task covariant (#8781)
1 parent 27e9fde commit 493e35b

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

stdlib/asyncio/tasks.pyi

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ __all__ = (
3636
)
3737

3838
_T = TypeVar("_T")
39+
_T_co = TypeVar("_T_co", covariant=True)
3940
_T1 = TypeVar("_T1")
4041
_T2 = TypeVar("_T2")
4142
_T3 = TypeVar("_T3")
@@ -265,21 +266,25 @@ else:
265266
) -> tuple[set[Task[_T]], set[Task[_T]]]: ...
266267
async def wait_for(fut: _FutureLike[_T], timeout: float | None, *, loop: AbstractEventLoop | None = ...) -> _T: ...
267268

268-
class Task(Future[_T], Generic[_T]):
269+
# pyright complains that a subclass of an invariant class shouldn't be covariant.
270+
# While this is true in general, here it's sort-of okay to have a covariant subclass,
271+
# since the only reason why `asyncio.Future` is invariant is the `set_result()` method,
272+
# and `asyncio.Task.set_result()` always raises.
273+
class Task(Future[_T_co], Generic[_T_co]): # pyright: ignore[reportGeneralTypeIssues]
269274
if sys.version_info >= (3, 8):
270275
def __init__(
271276
self,
272-
coro: Generator[_TaskYieldType, None, _T] | Awaitable[_T],
277+
coro: Generator[_TaskYieldType, None, _T_co] | Awaitable[_T_co],
273278
*,
274279
loop: AbstractEventLoop = ...,
275280
name: str | None = ...,
276281
) -> None: ...
277282
else:
278283
def __init__(
279-
self, coro: Generator[_TaskYieldType, None, _T] | Awaitable[_T], *, loop: AbstractEventLoop = ...
284+
self, coro: Generator[_TaskYieldType, None, _T_co] | Awaitable[_T_co], *, loop: AbstractEventLoop = ...
280285
) -> None: ...
281286
if sys.version_info >= (3, 8):
282-
def get_coro(self) -> Generator[_TaskYieldType, None, _T] | Awaitable[_T]: ...
287+
def get_coro(self) -> Generator[_TaskYieldType, None, _T_co] | Awaitable[_T_co]: ...
283288
def get_name(self) -> str: ...
284289
def set_name(self, __value: object) -> None: ...
285290

0 commit comments

Comments
 (0)