Can't use Callable[..., T] | Callable[..., Awaitable[T]] as a function argument
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Code:
I was trying to define a callable that can be async or not and use a TypeVar as the return type, but it seem to be broken, here's the full example:
from typing import Union, Awaitable, Callable, TypeVar, Any
T = TypeVar("T")
_RESOLVER_TYPE = Union[
Callable[..., T],
Callable[..., Awaitable[T]],
]
def x() -> int:
return 1
async def a_x() -> int:
return 1
def field_ok(
resolver: _RESOLVER_TYPE,
) -> Any:
...
def field_broken(
resolver: _RESOLVER_TYPE[T],
) -> Any:
...
field_ok(x)
field_ok(a_x)
field_broken(x)
field_broken(a_x)
if I don't pass T it seem to work, no sure what is wrong, the error is:
main.py:31: error: Argument 1 to "field_broken" has
incompatible type "Callable[[], Coroutine[Any, Any, int]]";
expected "Union[Callable[..., <nothing>], Callable[..., Awaitable[<nothing>]]]" [arg-type]
Here's the playground url: https://mypy-play.net/?mypy=latest&python=3.11&gist=6d8ed4a4e55e0d6b2712eff23cd3e3b0
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the example from main.py using the linked mypy playground, comparing field_ok and field_broken with both synchronous and asynchronous callables. Trace how the parameterized Union of Callable and Awaitable is interpreted, and consider the issue resolved when the example no longer reports the incompatible-type error for either call.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100