Search code examples
pythonstringbooleantruthiness

Returning the truthiness of a variable rather than its value?


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?


Solution

  • You can use bool:

    return bool(test_string)
    

    Demo:

    >>> bool('abc')
    True
    >>> bool('')
    False
    >>>