python / python/typing

AnyOf - Union for return types

Abierto
#566 41 comentarios 23 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

topic: feature
Lenguaje dominante
Python
Estrellas
1.8k
Forks
302
Merge medio
23 h
PR fusionados (30 d)
8

Descripción

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 Union as the return type. This is usually not recommended, since it means that the caller needs to use isinstance() to use the return type.
  • Use Any as 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.

Guía de contribución

No hay ninguna guía de contribución indexada para este repositorio

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Lee la propuesta de AnyOf y compara sus ejemplos—open(), shutil.copy(), Union y @overload—con el comportamiento actual de typing. Revisa la discusión del issue para comprobar si hay acuerdo sobre la semántica y la documentación; se considerará terminado cuando exista una especificación acordada que cubra las asignaciones a cada tipo miembro, la compatibilidad con Union y los tipos no válidos.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
compilers
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Tranquilo
Claridad
Bastante claro
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.