Parametrized type alias union of callables unsubstitued using unannotated functions
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
A parametrized type alias of union of callable types doesn't substitute the type var parameters properly when using unannotated functions.
To Reproduce
from typing import Union, Callable, TypeVar, List
T = TypeVar("T")
T2 = TypeVar("T2")
F = Union[Callable[[T, int], T2], Callable[[T], T2]]
def foo(l: List[T], f: F[T, T2]) -> T2:
...
reveal_type(foo([1, 2], lambda x: x + 1)) # Revealed type is "Any"
reveal_type(foo([1, 2], lambda x, y: x + y)) # Revealed type is "Any"
Expected Behavior
Both expressions in reveal_type should have builtins.int type as I think it has enough information to solve the type variables there.
As a workaround this works well:
from typing import List, Callable, TypeVar, overload
T = TypeVar("T")
T2 = TypeVar("T2")
@overload
def bar(l: List[T], f: Callable[[T, int], T2]) -> T2:
...
@overload
def bar(l: List[T], f: Callable[[T], T2]) -> T2:
...
def bar(l, f):
...
reveal_type(bar([1, 2], lambda x: x + 1)) # Revealed type is "builtins.int"
reveal_type(bar([1, 2], lambda x, y: x + y)) # Revealed type is "builtins.int"
But in my understanding I would expect the previous code to work the same
It also works fine with type annotated function:
from typing import Union, Callable, TypeVar, List
T = TypeVar("T")
T2 = TypeVar("T2")
F = Union[Callable[[T, int], T2], Callable[[T], T2]]
def foo(l: List[T], f: F[T, T2]) -> T2:
...
def bar(x: int) -> int:
...
reveal_type(foo([1, 2], bar)) # Revealed type is "builtins.int"
Actual Behavior
Mypy doesn't substitute the type variables properly and reveal the type as Any
Your Environment
- Mypy version used: 0.991
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): none - Python version used: 3.11
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 issue with the provided Python 3.11 examples using mypy 0.991 and confirm that both unannotated lambda calls reveal as Any instead of int. Trace the type-variable substitution for the parametrized union of Callable types, then add regression coverage showing both calls infer builtins.int without changing the annotated-function case.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers, devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100