not None test in Python
if val is not None:
# ...
is the Pythonic idiom for testing that a variable is not set to None
. This idiom has particular uses in the case of declaring keyword functions with default parameters. is
tests identity in Python. Because there is one and only one instance of None
present in a running Python script/program, is
is the optimal test for this. As Johnsyweb points out, this is discussed in PEP 8 under "Programming Recommendations".
As for why this is preferred to
if not (val is None):
# ...
this is simply part of the Zen of Python: "Readability counts." Good Python is often close to good pseudocode.
How to check in python if variable is not None and greater than something in one line?
You can also use python ternary operator. In your example, this might help you. You can extend the same further too.
#if X is None, do nothing
>>> x = ''
>>> x if x and x>0 else None
#if x is not None, print it
>>> x = 1
>>> x if x and x>0 else None
1
Dealing with string values
>>> x = 'hello'
>>> x if x and len(x)>0 else None
'hello'
>>> x = ''
>>> x if x and len(x)>0 else None
>>>
Python `if x is not None` or `if not x is None`?
There's no performance difference, as they compile to the same bytecode:
>>> import dis
>>> dis.dis("not x is None")
1 0 LOAD_NAME 0 (x)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 9 (is not)
6 RETURN_VALUE
>>> dis.dis("x is not None")
1 0 LOAD_NAME 0 (x)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 9 (is not)
6 RETURN_VALUE
Stylistically, I try to avoid not x is y
, a human reader might misunderstand it as (not x) is y
. If I write x is not y
then there is no ambiguity.
In Python how should I test if a variable is None, True or False
Don't fear the Exception! Having your program just log and continue is as easy as:
try:
result = simulate(open("myfile"))
except SimulationException as sim_exc:
print "error parsing stream", sim_exc
else:
if result:
print "result pass"
else:
print "result fail"
# execution continues from here, regardless of exception or not
And now you can have a much richer type of notification from the simulate method as to what exactly went wrong, in case you find error/no-error not to be informative enough.
How to test NoneType in python?
So how can I question a variable that is a NoneType?
Use is
operator, like this
if variable is None:
Why this works?
Since None
is the sole singleton object of NoneType
in Python, we can use is
operator to check if a variable has None
in it or not.
Quoting from is
docs,
The operators
is
andis not
test for object identity:x is y
is true if and only ifx
andy
are the same object.x is not y
yields the inverse truth value.
Since there can be only one instance of None
, is
would be the preferred way to check None
.
Hear it from the horse's mouth
Quoting Python's Coding Style Guidelines - PEP-008 (jointly defined by Guido himself),
Comparisons to singletons like
None
should always be done withis
oris not
, never the equality operators.
if A vs if A is not None:
The statement
if A:
will call A.__bool__()
(see Special method names documentation), which was called __nonzero__
in Python 2, and use the return value of that function. Here's the summary:
object.__bool__(self)
Called to implement truth value testing and the built-in operation
bool()
; should returnFalse
orTrue
. When this method is not defined,__len__()
is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither__len__()
nor__bool__()
, all its instances are considered true.
On the other hand,
if A is not None:
compares only the reference A
with None
to see whether it is the same or not.
What is the most pythonic way to check if multiple variables are not None?
There's nothing wrong with the way you're doing it.
If you have a lot of variables, you could put them in a list and use all
:
if all(v is not None for v in [A, B, C, D, E]):
Best way to do a not None test in Python for a normal and Unicode empty string?
Empty strings are considered false.
if string:
# String is not empty.
else:
# String is empty.
Related Topics
Python's JSON Module, Converts Int Dictionary Keys to Strings
How to Run Pygame or Pyglet in a Browser
Find First Sequence Item That Matches a Criterion
Python Multiprocessing: Handling Child Errors in Parent
Concatenate Two Numpy Arrays Vertically
How to Hide the Console Window in a Pyqt App Running on Windows
Creating Dynamically Named Variables from User Input
Python Urllib2 Basic Auth Problem
If Range() Is a Generator in Python 3.3, Why How to Not Call Next() on a Range
Numpy - Create Matrix with Rows of Vector
Why Does My Pandas Dataframe Not Display New Order Using 'Sort_Values'
Importing Modules: _Main_ VS Import as Module
Speed of Calculating Powers (In Python)
Simple Python Challenge: Fastest Bitwise Xor on Data Buffers
Running Get_Dummies on Several Dataframe Columns