Cannot infer value of constrained type parameter when calling function with union
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
I have a function that takes in either a list of X or a list of Y, and returns a list of the same X or Y that was input. When calling the function with a variable that's either list of X or a list of Y, I expect it to work the same as calling the function with either.
To Reproduce
from typing import TypeVar
StrOrInt = TypeVar("StrOrInt", str, int)
def func(vals: list[StrOrInt]) -> list[StrOrInt]:
return vals
def action(strs: list[str], ints: list[int]) -> None:
reveal_type(func(strs))
reveal_type(func(ints))
strOrInt: list[str] | list[int] = strs if strs else ints
reveal_type(func(strOrInt))
Expected Behavior
test.py:9: note: Revealed type is "builtins.list[builtins.str]"
test.py:10: note: Revealed type is "builtins.list[builtins.int]"
test.py:13: note: Revealed type is "builtins.list[builtins.str] | builtins.list[builtins.int]"
Actual Behavior
test.py:9: note: Revealed type is "builtins.list[builtins.str]"
test.py:10: note: Revealed type is "builtins.list[builtins.int]"
test.py:13: error: Cannot infer value of type parameter "StrOrInt" of "func" [misc]
test.py:13: note: Revealed type is "builtins.list[Any]"
Your Environment
- Mypy version used:
- Mypy command-line flags:
- Mypy configuration options from
mypy.ini(and other config files): - Python version used:
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 by running the supplied Python reproducer with mypy and compare the three revealed types with the expected output. Investigate type-parameter inference for a list[str] | list[int] argument; done means the union call is accepted and reveals list[str] | list[int] without an inference 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
- Clearly specified
- Newbie friendliness
- 35/100