Thanks to visit codestin.com
Credit goes to github.com

Skip to content

asyncio.create_task hints say you can pass any Awaitable, but you cannot pass asyncio.Tasks #6770

Closed
@alkasm

Description

@alkasm

The following program passes mypy type checking, but fails at runtime:

import asyncio
from typing import Awaitable

async def main() -> None:
    async def coro() -> Awaitable[None]: pass
    task = asyncio.create_task(coro())
    asyncio.create_task(task)

asyncio.run(main())
(venv) ➜ python --version
Python 3.9.6
(venv) ➜ mypy --version
mypy 0.930
(venv) ➜ mypy --strict example.py 
Success: no issues found in 1 source file
(venv) ➜ python example.py
Traceback (most recent call last):
  File ".../create-task-types/example.py", line 10, in <module>
    asyncio.run(main())
  File ".../python3.9/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File ".../python3.9/asyncio/base_events.py", line 642, in run_until_complete
    return future.result()
  File ".../create-task-types/example.py", line 7, in main
    asyncio.create_task(task)
  File ".../python3.9/asyncio/tasks.py", line 361, in create_task
    task = loop.create_task(coro)
  File ".../python3.9/asyncio/base_events.py", line 433, in create_task
    task = tasks.Task(coro, loop=self, name=name)
TypeError: a coroutine was expected, got <Task pending name='Task-2' coro=<main.<locals>.coro() running at .../create-task-types/example.py:4>>

Metadata

Metadata

Assignees

No one assigned

    Labels

    stubs: false negativeType checkers do not report an error, but should

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions