Returning the truthiness of a variable rather than its value?
Asked Answered
S

1

6

Consider this code:

test_string = 'not empty'

if test_string:
    return True
else:
    return False

I know I could construct a conditional expression to do it:

return True if test_string else False

However, I don't like testing if a boolean is true or false when I'd rather just return the boolean. How would I just return its truthiness?

Spoonbill answered 4/12, 2014 at 0:54 Comment(3)
related: https://mcmap.net/q/238532/-defining-quot-boolness-quot-of-a-class-in-python/674039Foregut
I don't see any difference, an empty string will evaluate to False and vice versa for a non empty stringMarthmartha
@PadraicCunningham I used a string for a simple example. Usually I can get away with just using the object. My actual code is checking if a service is running. If no response is given, I want to return False. If I do get a response though, I don't actually care what the value is. The fact I got a response is enough. The problem is I don't want to provide the response to my user.Spoonbill
G
11

You can use bool:

return bool(test_string)

Demo:

>>> bool('abc')
True
>>> bool('')
False
>>>
Gainey answered 4/12, 2014 at 0:55 Comment(3)
Fast answer :). Vote upAriew
I did some more research and found a book that says truthiness is checked by first calling __nonzero__, and if that is undefined it then calls __len__. I'm guessing this is the same way bool() works, right?Spoonbill
It depends on what version of Python you are using. In Python 2.x, bool() will call __nonzero__ or, if that is not implemented, __len__. If neither of those are implemented, then it will return True. Here is a reference. In Python 3.x however, bool() calls __bool__ first, which is a replacement for __nonzero__. For a reference, see the link in my answer.Gainey

© 2022 - 2024 — McMap. All rights reserved.