python / python/typeshed

asyncio.create_task doesn't accept coroutine like objects

Open
#10,236 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic: asyncio
Dominant language
Python
Stars
5.1k
Forks
2.1k
Avg merge
1d 19h
Merged PRs (30d)
82

Description

The following code fails to typecheck with latest mypy but works just fine at runtime.

from typing import Any
import asyncio

class MyCoro:
    def __init__(self):
        async def coro() -> None:
            print("coro works!")

        self.coro = coro()

    def send(self, value: Any) -> None:
        return self.coro.send(value)

    def throw(self, exc: BaseException) -> None:
        return self.coro.throw(exc)

    def close(self) -> None:
        return self.coro.close()

    def __await__(self) -> Any:
        return self.coro.__await__()

async def main() -> None:
    coro = MyCoro()
    await asyncio.create_task(coro)


asyncio.run(main())

Error:

cpython on  isolate-decimal [?] via 🐍 v3.11.2 
❯ mypy main.py 
main.py:25: error: Argument 1 to "create_task" has incompatible type "MyCoro"; expected "Union[Generator[Any, None, <nothing>], Coroutine[Any, Any, <nothing>]]"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the example with mypy and inspect the typeshed stub for asyncio.create_task. Compare its accepted argument types with the runtime behavior shown for MyCoro. Done means the example typechecks without weakening unrelated asyncio typing behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.