python / python/mypy

Feature proposal: Warn when narrowing to a mutable type

Aperta
#11,384 7 commenti 3 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

Feature

I often encourage people to use "immutable" types for function parameters, as a way to indicate that the passed data structures won't be mutated by the function. Of course that isn't a guarantee, but a nice indication that can make it easier to reason about code like this:

vals = [1, 2, 3]
operation(vals)
print(vals)  # What is vals here?

If operation is typed with Sequence we can usually assume that vals isn't mutated by it. However, right now it wouldn't be a type error for operation to be implemented like this, which breaks that indication.

def operation(vals: Sequence[int]) -> None:
    assert isinstance(vals, list)
    vals += [3, 4, 5]

Here's the above example on mypy playground.

Pitch

I think it would be a valuable feature for mypy to warn when it narrows from a known immutable type such as Sequence to a known mutable type such as list.

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 l’esempio mypy playground collegato e verifica come viene attualmente gestito il narrowing da Sequence a list. Il lavoro è completato quando mypy è in grado di identificare questo narrowing da un tipo immutabile noto a un tipo mutabile noto ed emettere l’avviso proposto senza modificare il comportamento degli altri narrowing.

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

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Funzionalità
Difficoltà
5/5
Tempo stimato
Più di una settimana
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.