Non-optional send types and the Generator.send() parameter
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Python
- Estrellas
- 20.6k
- Forks
- 3.3k
- Métricas de merge de PR
- Métricas de PR pendientes
Descripción
Bug Report
Python doesn’t allow you to send a non-None value to a just-started generator, but if the send type of a generator is not annotated Optional then .send(None) can’t be used.
You could just use next() at the start, but a situation can be created where Python and Mypy don’t agree on a type error. Pyright behaves similarly.
I’m not sure what the solution is here. This issue might require discussion.
To Reproduce
$ cat file1.py
from collections.abc import Generator
def g() -> Generator[int, int, None]:
sent = 0
while True:
sent = yield sent
gen = g()
print(gen.send(0)) # <--
print(gen.send(1))
print(gen.send(2))
$ mypy --strict file1.py
Success: no issues found in 1 source file
$ python3 file1.py
Traceback (most recent call last):
File "/Users/danpro/Desktop/fold/file1.py", line 10, in <module>
print(gen.send(0)) # <--
TypeError: can't send non-None value to a just-started generator
$
$
$ cat file2.py
from collections.abc import Generator
def g() -> Generator[int, int, None]:
sent = 0
while True:
sent = yield sent
gen = g()
print(gen.send(None)) # <--
print(gen.send(1))
print(gen.send(2))
$ mypy --strict file2.py
file2.py:10: error: Argument 1 to "send" of "Generator" has incompatible type "None"; expected "int"
Found 1 error in 1 file (checked 1 source file)
$ python3 file2.py
0
1
2
Expected Behavior
A TypeError should not occur at runtime when Mypy reports successful type checking.
Actual Behavior
A TypeError occurs even though Mypy reports successful type checking.
My Environment
- Mypy version used: 0.910
- Python version used: 3.9.6
- Pyright version used: 1.1.163
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Comienza con el comportamiento de tipado de Generator.send() descrito en las dos reproducciones file1.py y file2.py, comparando los resultados de mypy con el TypeError en tiempo de ejecución de Python. Revisa cómo el tipo send de Generator gestiona el valor None inicial y considera la interacción con el comportamiento comparable de Pyright. Se considera terminado cuando el comprobador de tipos ya no acepta código que pueda fallar inmediatamente en tiempo de ejecución, con el comportamiento previsto establecido para ambos ejemplos.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- python
- Área
- devtools
- Tipo de issue
- Error
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Estado de actividad
- Estancado
- Claridad
- Necesita aclaración
- Aptitud para principiantes
- 25/100