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.
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.
Difference between if x and if x is not None
In the following cases:
test = False
test = ""
test = 0
test = 0.0
test = []
test = ()
test = {}
test = set()
the if
test will differ:
if test: #False
if test is not None: #True
This is the case because is
tests for identity, meaning
test is not None
is equivalent to
id(test) == id(None) #False
therefore
(test is not None) is (id(test) != id(None)) #True
Check if value is not none before comparison
Perhaps:
if not None in (x, y) and x > y:
do_something()
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 not val, vs if val is None
Use a comparison to None if that's what you want. Use "if not value" if you just want to check if the value is considered false (empty list, none, false).
I find "if not value" to be cleaner looking and Pythonic.
Also, be careful with lists. You should not use is when comparing for an empty list. If you know you're getting a list, use if <list>
to check if it has any contents (or len()). Try typing this into the interpreter:
>>> a = []
>>> a is []
False
This is because the temporary list you just made has a different address in memory than the one stored at 'a'. You don't see this with None, False, or True because these are all values that are singletons (they all refer to the same section of memory) so using the 'is' keyword works.
You'll also find that CPython interns strings so the following works.
>>> 'a' is 'a'
True
You should not rely on this. It is an implementation detail and this is not specified to work with every version of Python.
Difference between if obj and if obj is not None
if obj is not None
test whether the object is not None. if obj
tests whether bool(obj)
is True.
There are many objects which are not None but for which bool(obj)
is False: for instance, an empty list, an empty dict, an empty set, an empty string. . .
Use if obj is not None
when you want to test if an object is not None. Use if obj
only if you want to test for general "falseness" -- whose definition is object-dependent.
variable' or 'variable is not None'
Is there any difference between these three in a specific scenario ?
The first asks whether the variable is anything falsy. This test will fail for all kinds of things besides None
—False
, 0
, any empty sequence, etc.
The second asks whether it's the magic singleton constant None
. This will fail only for None
itself.
The third asks whether it's anything that considers itself equal to None
. This will fail for, say, Holder(None)
, where Holder
is a wrapper class whose instances compare equal to whatever they're holding. Or, to give a less realistic but shorter to code exmaple:
class Stupid(object):
def __ne__(self, other):
return False
Variable = Stupid()
The last one is rarely useful; in fact, if you ever think you might need to check == None
or != None
, and you haven't specifically been creating transparent-wrapper classes or anything like that, you probably actually wanted is None
or is not None
. But the other two are both very useful and common.
if there is no difference which one is more suitable to use?
Well, there is a difference, and which one is more suitable depends on the specific use.
At the end of the question, it seems like you might be asking whether there's any difference in the specific case where Variable
is definitely None
. In that case, of course there is no functional difference between the three.* All of them are guaranteed to be false, and therefore do nothing. Which means there's also no difference between any of the three and writing no code at all. Which is a lot simpler, more readable, and faster.
* There is a performance difference—the first one doesn't have to LOAD_CONST
the None
, or call a comparison operator. And, even if you've somehow managed to rebind None
or change the value of the None
constant (maybe by stomping all over the heap with ctypes
?), the first one is more likely to still work. But neither of these is ever going to matter—and, if they do, again, no code at all will be even faster and more reliable.
Related Topics
No Module Named 'Pandas._Libs.Tslibs.Timedeltas' in Pyinstaller
Send Data from a Textbox into Flask
How to Redirect Print Statements to Tkinter Text Widget
Dataframe Set_Index Not Setting
Python (And Python C API): _New_ Versus _Init_
Constructing a Co-Occurrence Matrix in Python Pandas
High Performance Fuzzy String Comparison in Python, Use Levenshtein or Difflib
How to Make Custom Legend in Matplotlib
Python Mixed Integer Linear Programming
How to Check That Multiple Keys Are in a Dict in a Single Pass
Truncate to Three Decimals in Python
Memory-Efficient Built-In SQLalchemy Iterator/Generator
Working with Tiffs (Import, Export) in Python Using Numpy
Python Urllib2 with Keep Alive
Failedpreconditionerror: Attempting to Use Uninitialized in Tensorflow