wim - 4 months ago 9

Python Question

In

`/tmp/spam.py`

`n = 69`

if n == True:

print 'potato'

pep8 utility complains about this conditional:

`wim@SDFA100461C:/tmp$ pep8 spam.py`

spam.py:3:6: E712 comparison to True should be 'if cond is True:' or 'if cond:'

- the first suggestion is wrong/"worse" according to pep8 itself
- the second suggestion changes the behaviour of the code

What is the best practice for a case where you actually

`True`

`True`

`is`

Answer

If you really do need to check *equality* with `True`

then use `==`

and ignore PEP8, but in almost any conceivable case that isn't what you want.

If you want to know whether the value you have is one of the values Python considers to be true, use `if cond:`

. If you want to know whether the value you have is the singleton value `True`

then use `is True`

, the booleans `True`

and `False`

are singletons so it is correct to use `is`

in this situation.

Checking `x == True`

is a halfway house. It is true when `x is True`

is true, and false for your case of `x=69`

, but there are other objects which are not themselves `True`

but for which `x==True`

gives an unexpectedly true result such as `1 == True`

being true. (thanks @Ant).

So putting that together:

```
value of n: True 1 69 False 0
-----------------------------------------------
expression result
-----------------------------------------------
if n: True True True False False
if n is True: True False False False False
if n==True: True True False False False
```

Pick the row from that table which gives the results you really wanted (and the last one isn't it).

Source (Stackoverflow)

Comments