Question

I was writing a unit test to assert the return value is not empty, so I wrote something like assert(value, True) and I got an error AssertionError: '72a7090610eb11e398d40050569e0016' != True

Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 'abc' == True
False

I always thought that an non empty string or > 1 integers would evaluate to True, maybe I got confused with PHP.

And I always thought if 'abc'is equivalent to if 'abc' == True obviously I was wrong :(

Was it helpful?

Solution 2

You are conflating thruthness with equality; they are not the same thing. Use bool() if you need to compare to actual True and False values:

>>> bool('abc')
True

You generally do not compare directly with == True or == False. Rather, you use conditional expressions or statements:

if 'abc':
    pass

while 'def':
    pass

foo if 'abc' else bar

Only empty containers, numeric zero and False and None are falsey, everything else is thruthy; you can use bool() to test for that condition explicitly. You can make custom types look like empty containers by implementing __len__() and returning 0, or look like a number by implementing __nonzero__()* and returning False when the instance is to be the boolean equivalent of numeric zero.

*In Python 3, use __bool__ instead.

OTHER TIPS

'abc' is not equal to True, but it's truthy. Those are two different concepts! in other words, this won't print 'ok':

if 'abc' == True:
    print 'ok'

... But this will:

if 'abc':
    print 'ok'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top