5

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?

cxw
  • 15,429
  • 2
  • 37
  • 69
K Engle
  • 942
  • 1
  • 9
  • 22
  • related: http://stackoverflow.com/q/8205558/674039 – wim Dec 04 '14 at 00:59
  • I don't see any difference, an empty string will evaluate to False and vice versa for a non empty string – Padraic Cunningham Dec 04 '14 at 00:59
  • @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. – K Engle Dec 04 '14 at 01:08

1 Answers1

11

You can use bool:

return bool(test_string)

Demo:

>>> bool('abc')
True
>>> bool('')
False
>>>
  • Fast answer :). Vote up – Khamidulla Dec 04 '14 at 00:56
  • 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? – K Engle Dec 04 '14 at 01:17
  • 1
    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](https://docs.python.org/2/reference/datamodel.html#object.__nonzero__). In Python 3.x however, `bool()` calls `__bool__` first, which is a replacement for `__nonzero__`. For a reference, see the link in my answer. –  Dec 04 '14 at 01:21