python / python/typing

[@overload]: What is the effect of the *implementation* type-signature?

Aperta
#1,840 3 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

topic: documentation
Lingua principale
Python
Stelle
1.8k
Fork
302
Merge medio
23h
PR unite (30g)
8

Descrizione

One thing that I've found underspecified when using @overload is what the type signature of the actual function should be.

For example, let's say I have a function like:

from typing import overload, Literal

@overload
def f(x: int, z: Literal[True]) -> str: ...
@overload
def f(x: int, z: Literal[False] = ...) -> int: ...
def f(x: int, z: bool = False) -> str | int:
    if z:
        return "hello"
    return 1

What is the effect of the last line? In particular:

  • The documentation and examples often just use no annotations for the implementation signature (def f(x, z):). Is that the right thing to do (I sometimes get Overloaded implementation is not consistent with signature of overload 1 errors if I leave out the type annotations)?
  • If I do specify types on the last, do I also have to add it to @overload list -- in other words:
@overload
def f(x: int, z: Literal[True]) -> str: ...
@overload
def f(x: int, z: Literal[False] = ...) -> int: ...
@overload
def f(x: int, z: bool = ...) -> str | int   # is this overload necessary?
def f(x: int, z: bool = False) -> str | int:
    if z:
        return "hello"
    return 1

Both pyright and mypy seem to interpret things differently with and without it (e.g. see this play link).

I understand that @overload is a complicated feature, but I'm hoping this is a small corner we can start with.

Guida per i contributori

Nessuna guida per i contributori indicizzata per questo repository

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 gli esempi di @overload presenti in questa issue ed eseguili nel Pyright playground collegato, quindi confronta i risultati con mypy. Esamina come i due strumenti interpretano le firme di implementazione e gli elenchi di overload. Il lavoro è completato quando si è raggiunta una spiegazione condivisa della semantica e sono stati documentati il comportamento previsto e gli esempi.

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

Valutazione

Stack tecnologico
python
Ambito
documentation
Tipo di issue
Documentazione
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Da chiarire
Idoneità per principianti
25/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.