Opt-in error for `if x:` when `x: None | int` or `None | str` etc.
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
Feature
The bug function below has a bug: the else branch will execute both when x is None and when it is empty, and the latter is unexpected. The programmer was hoping "" would be handled by the if branch.
It'd be handy if Mypy could (optionally) flag this sort of mistake, to help reminder the programmer that they probably should write something like fixed, i.e. take optional values like None | str as expressing intent that "" should behave differently to None.
def bug(x: None | str):
if x: # error: None and str
print(f"the str value is {x}")
else:
print("the value is None")
def fixed(x: None | int):
if x is not None: # no error
print(f"the int value is {x}")
else:
print("the value is None")
This also applies to:
- built-ins like
bool,float,int,list,dict,set(etc) - any "truthy" types, that implement
__bool__or__len__ - arguably, type variables that could be substituted with any of those types (e.g.
def bug[T](x: None | T)called likebug(""))
Pitch
It's very easy to write if x: out of habit when handling strings, lists and any other type with falsey values. When None is involved, this can lead to unexpected behaviour, where the falsey values like [], 0, "", {} are handled like None.
Mypy is very well positioned to catch this mistake given it has full type info (and indeed linters without full type info cannot do so).
This is likely to have some false-positives, and so should be optional. It feels conceptually similar, to me, to truthy-bool.
I've sketched an incomplete implementation in https://github.com/python/mypy/pull/17893, that I can complete with agreement/guidance.
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 revisando la implementación incompleta del pull request 17893 junto con los ejemplos bug y fixed del issue. Rastrea cómo mypy estrecha actualmente None | str y None | int en las comprobaciones de truthiness y, a continuación, determina el comportamiento del diagnóstico opcional y su tratamiento de los built-ins, los tipos truthy y las variables de tipo. Se considera terminado cuando los casos acordados se diagnostican sin requerir la comprobación de forma predeterminada.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- python
- Área
- devtools
- Tipo de issue
- Nueva funcionalidad
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 35/100