Faulty type narrowing with value restrictions
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
When passing an empty list directly into a value restricted generic function, the inferred return type can end up being too narrow.
To Reproduce
from typing import TypeVar
TV = TypeVar("TV", str, int)
def foo(x: list[TV]) -> list[TV]:
return x
# Should be: builtins.list[builtins.str] | builtins.list[builtins.int]
reveal_type(foo([])) # "builtins.list[builtins.str]"
https://mypy-play.net/?mypy=latest&python=3.10&flags=strict&gist=129ba2fed0c6ba1a861149f944db3420
Expected Behavior
I would expect the revealed type to either be builtins.list[builtins.str] | builtins.list[builtins.int].
Alternatively, having this result in an error of some sort would be fine. As a reference, when assigning the empty list first, it becomes a list[Any] instead of a list[<nothing>]. This results in the revealed type being list[Any], but also an error along the lines of Need type annotation for "l" (hint: "l: List[<type>] = ...").
Actual Behavior
The revealed type was builtins.list[builtins.str]
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-play reproducer and trace handling of empty list arguments with value-restricted TypeVar inference. Compare the inferred type with the expected union and the acceptable diagnostic behavior described in the issue. Done means the example no longer narrows incorrectly to list[str].
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
- 45/100