tags:

views:

238

answers:

5

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 differences it would be great to know.

+19  A: 

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.

Ignacio Vazquez-Abrams
+4  A: 
x = 0
if x: ...  # False
if x is not None: ... # True
eduffy
+9  A: 

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 
systempuntoout
And in even more. *All* empty collections and 0-equivalents are (usually) falsy.
delnan
collections.deque, collections.defaultdict, collections.namedtuple, collections.OrderedDict... also anything with the magic methods `__bool__` or `__nonzero__` returning false.
Autoplectic
and to expand upon the 0-equivalents: Decimal(0), 0+0j, 0.0, etc all evaluate to false.
Autoplectic
+1  A: 

everything in python has a bool value. the values are True, False, None

everything is True or False

0 is False

[], (), {}, '' are False (everything is empty)

[False] ,('hello'), 'hello' , etc. are True ('cause are not empty)

Only None is None..

>>> x = None
>>> if not x:print x #because 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, not that True and False are 'special' version of 1 and 0... for example

>>>True + 1
2
>>>False + 1
1
>>>range(1, 5)[False]
1
Ant
+1  A: 
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
Koroviev