if x:, vs if x == True, vs if x is True

Viewed 57709

Apologies if this has been asked before, but I have searched in vain for an answer to my exact question. Basically, with Python 2.7, I have a program running a series of geoprocessing tools, depended on what is reqested via a series of True/False variables that the user adjusts in the script e.g.

x = True

if x:
    run function

However, I have now discovered that x does not need to be literally "True" for the function to run. For example:

In: x = True
    if x:
        print True

Out: True

In: x = 123
    if x:
        print True

Out: True

In: x = 'False'
    if x:
        print True

Out: True

In: x = False
    if x:
        print True

Out: 

So any value other than False appears to evaluate to True, which would not be the case for if x == True or if x is True. Seeing as PEP 8 strongly recommends only using the if x: variant, can anybody explain why this behaviour occurs? It seems that if x: is more a test for "if x is not False" or "if x exists". With that in mind, I believe I should be using if x is True: in this case, despite what PEP 8 has to say.

8 Answers

I'd like to add a short example where those 3 tests differ:

def test(x):
    print(x, ":", bool(x), x == True, x is True)

test("something")
test(1)
test(True)

The output (pretty formatted):

# "something" : True False False
#           1 : True True  False
#        True : True True  True

In Python 2.7, if a: and if a==True are not giving the same output for values different to 1. Here are some snippets of code to demonstrate the different behaviors:

with a=1

a=1
if a==True: 
    print (a,"True")
else:
    print (a,"Not True")

output> (1,True)
a=1
if a: 
    print (a,"True")
else:
    print (a,"Not True")

output> (1, True)

with a=2

a=2
if a: 
    print (a,"True")
else:
    print (a,"Not True")

output> (2, True)
a=2
if a==True: 
    print (a,"True")
else:
    print (a,"Not True")

output> (2, Not True)

if you use if x ,it means it has to evaluate x for its truth value.But when you use x ==True or x is True.It means checking whether type(x)==bool and whether x is True.

attention : x is True is no equal to bool(x)==True

when you use x is True , you are checking the id of x and True.

Related