Search code examples
pythonbooleantruthiness

How to evaluate string as boolean in return statement?


I have a function like this in Python 3.4:

def is_value_valid(the_str):
    return len(the_str) != 0

There are of course other ways to write this, such as return the_str != "". Are there more pythonic ways of writing this expression? I am familiar with the concepts of truthy/falsy, so I know I could shortcut this in an if condition:

if not the_str:
    # do stuff

But the if expects a boolean result in its expression (this is my naive oversimplification here as a C++ programmer; I'm not familiar with standardese for this). However, there is nothing there to force the expression to evaluate to boolean in the return statement. I have tried just returning the string, and as long as no one treats the returned value as a string, it works just fine in calling code under boolean context. But from a post-condition perspective, I don't want to return a non-boolean type.


Solution

  • This is exactly what the bool() function does; return a boolean based on evaluating the truth value of the argument, just like an if statement would:

    return bool(the_str)
    

    Note that if doesn't expect a boolean value. It simply evaluates the truth value of the result of the expression.