python / python/mypy

Unsoundly accepts generic function with generic mutable default parameter

Aperta
#13,054 1 commento 1 reazione 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

Mypy unsoundly accepts a generic function with a generic mutable default parameter value. This value is evaluated once at runtime, but can be referred to with multiple incompatible types, breaking type safety.

from typing import TypeVar

T = TypeVar("T")

def f(x: T, y: list[T] = []) -> list[T]:
    return y

y_strs: list[str] = f("a")
y_ints: list[int] = f(4)
# Uh oh, y_strs and y_ints refer to the same list with incompatible types
y_strs.append("b")
print(y_ints[0] + 6)  # oops

mypy Playground link

(This is a sort of converse to #3737, where the complaint is that mypy fails to accept a generic function with a non-generic default parameter value. It further supports my claim that default parameter values should not be generalized to the generic type of the parameter at function definition time.)

Related:

  • #11538
  • #11585
  • #3737

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 con la riproduzione collegata in mypy Playground e confrontala con le issue correlate #3737, #11538 e #11585. Determina il trattamento previsto dei parametri predefiniti mutabili generici, quindi aggiungi una copertura di test che dimostri che gli alias di lista incompatibili segnalati non vengono accettati, preservando il comportamento previsto per i valori predefiniti non generici.

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

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Bug
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
30/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.