Difference between "if x" and "if x is not None"
It appears that "if x" is almost like short-hand for the longer "if x is not None" syntax. Are they functionally identical or are there cases where for a given value of x the two would evaluate differently?
I would assume the behavior should also be identical across Python implementations - but if there are subtle diffe开发者_如何学运维rences it would be great to know.
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
The former tests trueness, whereas the latter tests for identity with None
. Lots of values are false, such as False
, 0
, ''
, and None
, but only None
is None
.
x = 0
if x: ... # False
if x is not None: ... # True
if x
checks if x
is considered as True
.
In Python, everything has a boolean value (True
/False
).
Values that are considered as False
:
False
,None
0
,0.0
,0j
[]
,()
,{}
''
- Other instances that signal to Python that they are empty
Other values are considered as True
. For example, [False]
, ('hello')
, 'hello'
are considered as True
(because they are not empty).
When using if x is not None
, you are checking if x
is not None
, but it can be False
or other instances that are considered as False
.
>>> x = None
>>> if not x:print x # bool(None) is False
None
>>> if x == None:print x
None
>>> x = False
>>> if not x:print x
False
>>> if x == None:print x
Finally, note that True
and False
are respectively equal to 1
and 0
:
>>> True + 1
2
>>> False + 1
1
>>> range(1, 5)[False]
1
if x:
# Evaluates for any defined non-False value of x
if not x:
# Evaluates for any defined False value of x
if x is None:
# Evaluates for any instances of None
None is its own type, which happens to be False. "if not x" evaluates if x = None, only because None is False.
There aren't any subtle differences that I know of but there are exact methods to test for use for positivity/negativity in exact situations. Mixing them can work in some situations, but can lead to problems if they're not understood.
if x is True:
# Use for checking for literal instances of True
if x is False:
# Use for checking for literal instances of False
if x is None:
# Use for checking for literal instances of None
if x:
# Use for checking for non-negative values
if not x:
# Use for checking for negative values
# 0, "", None, False, [], (), {} are negative, all others are True
精彩评论