python / python/mypy

Allow Callable type hint before function definition

Offen
#16,946 2 Kommentare 6 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

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

Beschreibung

Feature

Allow

f: Callable[[int], int]


def f(n):
    return 42

as an alternative to

def f(n: int) -> int:
    return 42

Pitch
Currently, the proposed syntax produces a Name "f" already defined ... [no-redef] error, unlike similar code for non-function values:

# OK
x: int
x = 3

For some complicated function signatures, it would be clearer to provide a single Callable hint than to have argument types
mixed in with the arguments themselves and the return type added after the parameter list. For that matter, the two styles above need not be mutually exclusive:

f: Callable[[int], int]
def f(n: int) -> int:
    return 42

mypy should report an error only if the types are identical. (Or perhaps compatible; I don't know if there would be use-cases
for the initial type to be a supertype of the one implied by the function annotations.)

This would be consistent with the def statement being a kind of assignment, as the following is currently allowed:

x: int
x = 3

as well as eliminate the asymmetry between function parameters and "ordinary" names.

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

Das Issue nennt keine Datei, keinen Test und keinen Einstiegspunkt. Beginne damit, mypy's Behandlung annotierter Zuweisungen und Funktionsdefinitionen zu lokalisieren, und vergleiche dann, wie doppelte Namen gemeldet werden. Erledigt ist es, wenn die Callable-Deklaration vor def akzeptiert wird, kompatible Annotationen konsistent behandelt werden und widersprüchliche Typen weiterhin einen Fehler erzeugen.

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
25/100

Neue Issues direkt in Ihr Postfach

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