Type narrowing issue: bounded TypeVar loses type information when list is sliced
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
When slicing a list variable that is annotated with a bounded list TypeVar, mypy reveals the type of the sliced list as builtins.list[Any] instead of retaining the bounded type variable T. This results in a loss of type information.
To Reproduce
import typing
T = typing.TypeVar("T", bound=list)
def example(a: T):
reveal_type(a[:1]) # note: Revealed type is "builtins.list[Any]"
In the above code, I would expect the revealed type of a[:1] to be T, representing a sublist of the input list a. However, mypy instead reveals the type as builtins.list[Any], indicating a loss of the bounded type information.
Expected Behavior
I expected the revealed type to retain the bounded type variable T, which would maintain the type information of the elements in the list.
Actual Behavior
The revealed type is builtins.list[Any], demonstrating a loss of type information.
Your Environment
- Mypy version used: 1.5.0
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): not relevent i guess - Python version used: 3.9
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 provided Python 3.9 reproducer with mypy 1.5.0 and tracing how bounded TypeVars and list slicing are analyzed. Compare the revealed type with the expected T, then add regression coverage for this example and verify that the bounded type information is retained.
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