python / python/mypy

Only use annotations of `@overload`ed functions to type check the implementation

Offen
#8,867 3 Kommentare 2 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

topic-overloads
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Consider the following real-world example of a function. The type of one of the parameters of this function depends on another one:

from typing import *

K = TypeVar("K", bound=Hashable)
V = TypeVar("V")


@overload
def dict_get_factory(dictionary: Dict[K, V], 
                     key: K, 
                     factory: Callable[[], V], 
                     takes_key: Literal[False]) -> V: ...

@overload
def dict_get_factory(dictionary: Dict[K, V], 
                     key: K, 
                     factory: Callable[[K], V], 
                     takes_key: Literal[True]) -> V: ...

def dict_get_factory(dictionary: Dict[K, V], 
                     key: K, 
                     factory: Union[Callable[[], V], Callable[[K], V]], 
                     takes_key: bool=False) -> V:
    """Like dict.setdefault(), but uses a factory

    >>> dict_get_factory(d := {}, "foo", int)
    0
    >>> dict_get_factory(d, "bar", lambda key: len(key), takes_key=True)
    3
    >>> d
    {'foo': 0, 'bar': 3}
    """
    try:
        return dictionary[key]
    except KeyError:
        return dictionary.setdefault(key, 
                factory(key) if takes_key else factory())
                
i1: int = dict_get_factory({"foo": 1}, "bar", lambda: 1, False)   # ok
i2: int = dict_get_factory({"foo": 1}, "bar", lambda s: 1, True)  # ok

It doesn't typecheck as if you only look at the annotations of the implementation, the signature of the factory is ambiguous:

main.py:36: error: Too many arguments
main.py:36: error: Too few arguments

I don't think it's possible to annotate the implementation in such a way that it would typecheck. So it would be nice if mypy used the signatures of the @overloaded methods, and one wouldn't have to annotate the signature of the implementation at all. Even if you could annotate it in such a way that it would typecheck, wouldn't it be redundant?

Beitragsleitfaden

Beitragsleitfaden öffnen

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 mit dem Overload-Beispiel im Issue und untersuche, wie mypy Implementierungssignaturen und Overload-Prüfungen behandelt. Bestimme das erwartete Verhalten für Aufrufe innerhalb der Implementierung, füge anschließend gezielte Regressionstests hinzu und verifiziere, dass das Beispiel nicht mehr über widersprüchliche Factory-Aufruffehler berichtet.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
compilers, devtools
Issue-Typ
Feature
Schwierigkeit
5/5
Geschätzter Aufwand
Über eine Woche
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
25/100

Neue Issues direkt in Ihr Postfach

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