AnyOf - Union for return types
Personne n'a encore pris cette issue.
- Langage dominant
- Python
- Étoiles
- 1.8k
- Forks
- 302
- Merge moyen
- 23 h
- PR mergées (30 j)
- 8
Description
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.
Guide de contribution
Aucun guide de contribution indexé pour ce dépôt
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Piste de recherche
Lisez la proposition AnyOf et comparez ses exemples—open(), shutil.copy(), Union et @overload—au comportement actuel de typing. Examinez la discussion de l’issue pour vérifier s’il y a un accord sur la sémantique et la documentation ; le travail est considéré comme terminé lorsqu’une spécification arrêtée couvre les affectations à chaque type membre, la compatibilité avec Union et les types invalides.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Évaluation
- Stack technique
- python
- Domaine
- compilers
- Type d'issue
- Fonctionnalité
- Difficulté
- 5/5
- Temps estimé
- Plus d'une semaine
- Activité
- Calme
- Clarté
- Plutôt claire
- Accessibilité débutants
- 35/100