no ninguna prueba en Python [duplicar]
Esta pregunta ya tiene una respuesta aquí:
- Python `if x is not None` o `if not x is None`? 10 respuestas
Fuera de estos no ninguna prueba.
if val != None:
if not (val is None):
if val is not None:
¿Cuál es preferible y por qué?
4 answers
if val is not None:
# ...
Es el modismo pitónico para probar que una variable no está establecida en None
. Este modismo tiene usos particulares en el caso de declarar funciones de palabras clave con parámetros predeterminados. is
prueba la identidad en Python. Debido a que hay una y solo una instancia de None
presente en un script/programa Python en ejecución, is
es la prueba óptima para esto. Como Johnsyweb señala , esto se discute en PEP 8 bajo "Recomendaciones de programación".
En cuanto a por qué esto es preferred to
if not (val is None):
# ...
Esto es simplemente parte del Zen de Python: "La legibilidad cuenta."Buena Python es a menudo cerca de buena pseudocódigo .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:37
From, Programming Recommendations, PEP 8:
Las comparaciones con singletons como None siempre deben hacerse con "es" o "no es", nunca los operadores de igualdad.
Además, tenga cuidado de escribir "si x" cuando realmente quiere decir " si x no es Ninguno" -- por ejemplo, cuando se prueba si una variable o argumento que por defecto a Ninguno fue establecido a algún otro valor. El otro valor puede tener un tipo (como un contenedor) que podría ser falso en un booleano contexto!
PEP 8 es una lectura esencial para cualquier programador de Python.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-19 03:35:36
Cualquiera de los dos últimos, ya que val
podría ser potencialmente de un tipo que define __eq__()
para devolver true cuando se pasa None
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-19 03:23:34
La mejor apuesta con este tipo de preguntas es ver exactamente lo que hace python. El módulo dis
es increíblemente informativo:
>>> def f(val):
... if val != None:
... return True
... return False
...
>>> def g(val):
... if not (val is None):
... return True
... return False
...
>>> def h(val):
... if val is not None:
... return True
... return False
...
>>> import dis
>>> dis.dis(f)
2 0 LOAD_FAST 0 (val)
3 LOAD_CONST 0 (None)
6 COMPARE_OP 3 (!=)
9 POP_JUMP_IF_FALSE 16
3 12 LOAD_GLOBAL 1 (True)
15 RETURN_VALUE
4 >> 16 LOAD_GLOBAL 2 (False)
19 RETURN_VALUE
>>> dis.dis(g)
2 0 LOAD_FAST 0 (val)
3 LOAD_CONST 0 (None)
6 COMPARE_OP 9 (is not)
9 POP_JUMP_IF_FALSE 16
3 12 LOAD_GLOBAL 1 (True)
15 RETURN_VALUE
4 >> 16 LOAD_GLOBAL 2 (False)
19 RETURN_VALUE
>>> dis.dis(h)
2 0 LOAD_FAST 0 (val)
3 LOAD_CONST 0 (None)
6 COMPARE_OP 9 (is not)
9 POP_JUMP_IF_FALSE 16
3 12 LOAD_GLOBAL 1 (True)
15 RETURN_VALUE
4 >> 16 LOAD_GLOBAL 2 (False)
19 RETURN_VALUE
Tenga en cuenta que los dos últimos casos se reducen a la misma secuencia de operaciones (python lee not (val is None)
y utiliza el operador is not
). El primero utiliza el operador !=
cuando se compara con None.
Como se señala en otras respuestas, usar !=
cuando se compara con Ninguno es una mala idea
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-20 19:44:00