python / python/mypy

UnionType of `Callable[P, Awaitable[T]] | Callable[P, T]` not being matched by async function.

Open
#16,646 1 comment 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report
I'm trying to annotate a decorator that can take both async and normal functions using

def decorator(func: Callable[P, Awaitable[T]] | Callable[P, T])
...

The Callable[P, Awaitable[T]] variant does not match when using the decorator with an async function and instead raises an error
"Argument 1 to "decorator" has incompatible type "Callable[[int], Coroutine[Any, Any, str]]"; expected "Callable[[VarArg(Never), KwArg(Never)], Awaitable[Never]] | Callable[[VarArg(Never), KwArg(Never)], Never]" [arg-type]"

This may be related to #16451 which was fixed by 1.7.1

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.11&flags=new-type-inference&gist=c5255c4185cf954aa32bc8f8b2c04c10
Expected Behavior
Both sync and async should be type matched correctly

Actual Behavior

I get a strange error with the async variant (main.py:61: error: Argument 1 to "decorator" has incompatible type "Callable[[int], Coroutine[Any, Any, str]]"; expected "Callable[[VarArg(Never), KwArg(Never)], Awaitable[Never]] | Callable[[VarArg(Never), KwArg(Never)], Never]" [arg-type])

Your Environment

  • Mypy version used: 1.7.1 compiled
  • Mypy command-line flags: new-type-inference (by default)
  • Python version used: 3.11.6

Also replicated in the playground with 1.7.1 compiled and Python 3.11 and 3.12.

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 report in the linked mypy-play example using Python 3.11 and the new-type-inference flag, focusing on the error at main.py:61. Trace how the type checker matches the UnionType of Callable variants against the async function. Done means both the synchronous and asynchronous decorator uses type-check without the reported arg-type error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.