Reputation: 26405
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.
Upvotes: 2
Views: 5273
Reputation: 1035
bool(the_str)
is definitely the way to go, as several have mentioned.
But if your method requires that a string be given, I would also test for the string actually being a string (because bool(5)
and bool("this is a string")
will both return true.
return isinstance(the_str, str) and bool(the_str)
Or when used in an if
statement:
if isinstance(the_str, str) and the_str:
# here we are sure it's a string whose length > 0
Upvotes: 0
Reputation: 129
The if statement automatically evaluates a string as a boolean. However, if you want to return your string as a boolean you would simply do
return bool(the_str)
Upvotes: 1
Reputation: 1123900
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.
Upvotes: 8
Reputation: 398
def is_value_valid(the_str):
return bool(len(the_str) != 0)
Using bool(x) converts the value to a boolean. This function takes len(the_str) != 0
, evaluates it, converts it to bool, then returns the value.
The bool(x) is not required, you can just have the parentheses, because it will already return a bool, as evaluations return boolean by default.
Upvotes: -2
Reputation: 48506
>>> bool("foo")
True
>>> bool("")
False
Empty strings evaluate to False
, but everything else evaluates to True
. So this should not be used for any kind of parsing purposes.
So just return bool(the_str)
in your case.
Upvotes: 1