python / python/mypy

Type narrowing issue: bounded TypeVar loses type information when list is sliced

Open
#16,086 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.