if x:, vs if x == True, vs if x is True
Asked Answered
M

8

42

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.

Mindamindanao answered 6/12, 2013 at 9:55 Comment(0)
S
50

The following values in Python are false in the context of if and other logical contexts:

  • False
  • None
  • numeric values equal to 0, such as 0, 0.0, -0.0
  • empty strings: '' and u''
  • empty containers (such as lists, tuples and dictionaries)
  • anything that implements __bool__ (in Python3) to return False, or __nonzero__ (in Python2) to return False or 0.
  • anything that doesn't implement __bool__ (in Python3) or __nonzero__ (in Python2), but does implement __len__ to return a value equal to 0

An object is considered "false" if any of those applies, and "true" otherwise, regardless of whether it's actually equal to or identical with False or True

Now, if you've arranged that x is necessarily one of the objects True or False, then you can safely write if x. If you've arranged that the "trueness" of x indicates whether or not to perform the operation, regardless of type, then you can safely write if x. Where you can write that you should prefer to do so, since it's cleaner to read.

Normally, if it is allowed for x to take the value True then you're in one of those two cases, and so you would not write if x is True. The important thing is to correctly document the meaning of x, so that it reflects the test used in the code.

Python programmers are expected to know what's considered true, so if you just document, "runs the function if x is true", then that expresses what your original code does. Documenting it, "runs the function if x is True" would have a different meaning, and is less commonly used precisely because of the style rule in PEP8 that says to test for trueness rather than the specific value True.

However, if you wanted the code to behave differently in the case where x is an empty container from the case where it is None, then you would write something like if x is not None.

Sadness answered 6/12, 2013 at 10:12 Comment(2)
Thank you for explaining in detail. In my case, while I only would want the user to use True or False, and no other values, the code is documented enough to follow PEP 8 and leave my if x: statements as they are.Mindamindanao
docs.python.org - truth-value-testingCaveman
A
6

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
Aflcio answered 18/1, 2021 at 21:16 Comment(0)
M
3
x = 'False'
x = 123

Are both True

Other truth values.

The document explains other values.

As far as the PEP8 reason, its far more semantic to read if this_file_is_green

Meitner answered 6/12, 2013 at 9:58 Comment(1)
+1 for the link, without realising it, I had been looking at the tutorial for an older release of Python without this much detail.Mindamindanao
P
1

Other falsey values include 0, '', []. You should just use the if x: version.

Prakash answered 6/12, 2013 at 10:3 Comment(0)
C
1

It goes without saying that you should write code that does what you need. But in most cases, you simply don't need to say == True or is True, because you don't need to distinguish True from other "truthy" values. So it's recommended to leave that out for simplicity.

The case where you definitely should use == True or is True is when you do need to distinguish True from other truthy values.

In your example, do you care about the difference between True and 123? That would tell you which way to code it.

One thing about coding == True or is True: it will raise a minor red flag when other developers read your code. They won't think it's wrong, they will just wonder why it's there and will want to know why it's important to treat True differently from other truthy values in this particular case.

In other words, if you don't need it, it's best not to use it.

Covenantor answered 6/12, 2013 at 10:16 Comment(0)
R
0

The ability to say

if x:
   ...

is considered a feature. You can also specify when the test should be considered to pass or not for user defined classes (just define the method __nonzero__ in Python 2.x or __bool__ in Python 3).

For example for strings and containers like lists, dictionaries or sets the test if x ... means "if x is not empty".

Note that the rationale is not that this allows less code to write, but that resulting code is easier to read and to understand.

If you like instead to write if x is True ... have you considered to go farther down that path to if (x is True) is True ... or if ((x is True) is True) is True ... ? :-)

Renner answered 6/12, 2013 at 10:16 Comment(2)
You know that the value of x is True must be either True or False, whereas you may not know the same thing of x. So that's what stops the infinite recursion in the desperately unlikely scenario that True has special meaning distinct from other true values :-)Sadness
I understand what you mean, although I'm not sure why anybody would code "if (x is True) is True". It would be like using "if (x == False) == False". I agree with Steve on this one.Mindamindanao
R
0

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)
Reichstag answered 31/1, 2020 at 10:31 Comment(0)
F
-1

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.

Feisty answered 14/6, 2021 at 7:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.