AnyOf - Union for return types
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 1.8k
- Fork
- 302
- Merge medio
- 23h
- PR unite (30g)
- 8
Descrizione
Sometimes a function or method can return one of several types, depending on the passed in arguments or external factors. Best example is probably open(), but there are other examples in the standard library, like shutil.copy()[1]. In many of those cases, the caller knows what return type to expect.
Currently there are several options, but none of them is really satisfactory:
- Use
@overload. This is the best solution if it can be used. But that is often not the case, like in the examples above. - Use a mypy plugin. This solution does not scale to outside the standard library (and arguably not even inside it) and is mypy-specific.
- Use
Unionas the return type. This is usually not recommended, since it means that the caller needs to useisinstance()to use the return type. - Use
Anyas the return type. This is currently best practice in those cases, but of course provides no type safety at all.
Therefore, I propose to add another type, for example AnyOf[...] that acts like Union, but can be used everywhere any of its type arguments could be used.
from datetime import date
x: AnyOf[str, date] = ...
s: str = x # ok
dt: date = x # ok
i: int = x # type error
u: Union[str, bytes] = x # ok
x = u # type error (although the type checker could do something smart here and infer that u can only be str here)
I also think that the documentation should make it clear that using AnyOf is a code smell.
[1] Currently the type behaviour in shutil is broken in my opinion, but that does not change the fact that currently it is as it is.
Guida per i contributori
Nessuna guida per i contributori indicizzata per questo repository
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Leggi la proposta AnyOf e confronta i suoi esempi—open(), shutil.copy(), Union e @overload—con il comportamento attuale di typing. Esamina la discussione dell’issue per verificare se c’è accordo sulla semantica e sulla documentazione; il lavoro è completo quando esiste una specifica definita che copre le assegnazioni a ciascun tipo membro, la compatibilità con Union e i tipi non validi.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- compilers
- Tipo di issue
- Funzionalità
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Stato di attività
- Tranquilla
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100