Feature proposal: Warn when narrowing to a mutable type
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
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.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit dem verknüpften mypy playground-Beispiel und überprüfe, wie die Eingrenzung von Sequence auf list derzeit behandelt wird. Als abgeschlossen gilt die Aufgabe, wenn mypy diese Eingrenzung von einem bekannten unveränderlichen Typ auf einen bekannten veränderlichen Typ erkennen und die vorgeschlagene Warnung ausgeben kann, ohne das Verhalten bei anderen Eingrenzungen zu ändern.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Feature
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100