incompatible type "Callable[[], str]"; expected "Callable[[], <nothing>]"
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
I'm a bit unsure about whether this is supposed to work or not. The example seems to type check in VSCode, indicating that pyright can infer and match the type properly.
To Reproduce
from typing import Union, Callable, TypeVar
T = TypeVar("T")
def my_func(maybe_lazy: Union[Callable[[], T], T]) -> T:
...
a: str = my_func("foo")
b: str = my_func(lambda: "foo")
Expected Behavior
Type checks without error.
Actual Behavior
mypy complains with the following in the last line:
main.py:9: error: Argument 1 to "my_func" has incompatible type "Callable[[], str]"; expected "Callable[[], <nothing>]"
main.py:9: error: Return statement in function which does not return
Note that there is spurious "return statement in function which does not return" hinting to a similarity with https://github.com/python/mypy/issues/13014 and https://github.com/python/mypy/issues/10520 but I think this is a coincidence of using a lambda. Modifying the example to
from typing import Union, Callable, TypeVar
T = TypeVar("T")
def my_func(maybe_lazy: Union[Callable[[], T], T]) -> T:
...
def produce_a_string() -> str:
return "foo"
a: str = my_func("foo")
b: str = my_func(produce_a_string)
gets rid of the "return statement in function which does not return" but still errors with "incompatible type".
Your Environment
Reproduction example on mypy playground
- Mypy version used: 0.981
- Mypy command-line flags: None (playground default)
- Mypy configuration options from
mypy.ini(and other config files): None (playground default) - Python version used: 3.10
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
Start with the linked mypy playground reproduction using the reported Python 3.10 and mypy 0.981 settings. Compare inference for the string argument, lambda, and named function, then verify that both calls type check without the reported Callable or spurious return errors.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100