python / python/typing

`Counter.__init__` can't be typed safely

Offen
#1,846 8 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

topic: other
Vorherrschende Sprache
Python
Sterne
1.8k
Forks
302
Ø Merge
23 Std.
Gemergte PRs (30 T.)
8

Beschreibung

Counter overloads are unsafe

from collections import Counter

# no type errors reported and nothing tricky going on
a = {"a": "hello"}
b = Counter(a)
c = b.get("a", 0)
print(c + 2)  # crash

and I think there isn't a way to express them safely in the current type system.
Iterable[_T] needs to be something like Iterable[_T] - Mapping[_T, ~int]

If type checkers want to address this now, it would probably have to be a special case.

Without having to worry about type intersections/differences/negations, maybe we could have a way to indicate:
"If this overload matches (after all previous overloads fail), a type error should be reported."

something like:

    @overload
    def __init__(self, mapping: Mapping[_T, Any], /) -> typing.Error: ...

Beitragsleitfaden

Für dieses Repository ist kein Beitragsleitfaden indexiert

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne damit, das Beispiel zur Counter-Überladung und das in diesem Issue vorgeschlagene Verhalten von typing.Error zu prüfen. Es sind keine Repository-Dateien oder Tests angegeben; für den Abschluss wären ein abgestimmtes Typsystem-Design und eine dokumentierte Möglichkeit erforderlich, die unsichere Überladung darzustellen oder zu diagnostizieren.

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
Muss geklärt werden
Anfängerfreundlichkeit
25/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.