python / python/mypy

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

Aperta
#16,086 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia eseguendo il riproduttore fornito per Python 3.9 con mypy 1.5.0 e tracciando come vengono analizzati i TypeVars vincolati e lo slicing delle liste. Confronta il tipo rivelato con il T previsto, quindi aggiungi la copertura di regressione per questo esempio e verifica che le informazioni sul tipo vincolato vengano mantenute.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
compilers, devtools
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.