2

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.

11
  • 9
    bool(the_str)?? Commented Jan 12, 2016 at 14:36
  • 1
    @Burhan Why not simply if not the_str? Commented Jan 12, 2016 at 14:45
  • 1
    IMHO, the most Pythonic way would be to simply use the if statement. Why waste a function call for something so trivial? Unless, of course, this is just a simplified example. Commented Jan 12, 2016 at 14:45
  • 1
    I truly do not understand the reasoning behind explicitly casting the value, and would appreciate clarification. (I gather that there's some attempt to explain it in the question, but I don't get it.) Commented Jan 12, 2016 at 14:46
  • 2
    @PM2Ring: 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.. So the intention is for the function to return a boolean. Returning a string instead exposes an implementation detail of the function and returns the wrong type. bool() is the only proper solution for this use-case. Commented Jan 12, 2016 at 15:05

5 Answers 5

8

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.

Sign up to request clarification or add additional context in comments.

7 Comments

return True if the_str else False. I see the equivalent of this weird ternary idiom in PHP all the time. I just don't get why we're doing this exercise. :(
@kojiro: if a function promises to return a boolean, it is better to actually return a boolean. That makes for a cleaner interface.
Is that why? From the question, it sounds like the argument is that if expects a boolean, not that a function promises it.
@kojiro: That's the post-condition perspective; the post-condition is an expectation about what a function does. The post-condition here is that a boolean is returned.
@kojiro: There are loads of antipatterns in wide use, waiting to become bugs. Like this one or this one, see Why is Python 3.x's super() magic?. There are a lot of programmers out that that don't understand their craft.
|
1
>>> 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.

Comments

1

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)

1 Comment

You are very late to this party. Why repeat what others have already stated 15 minutes ago?
0

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

4 Comments

In an if context, just use isinstance(the_str, str) and the_str; using bool() there is entirely redundant.
This is not what the question is asking about though. They are asking how to produce a boolean to return from a function. It is not about validating that the value tested is a string, only how to produce a boolean for the truth value.
I would argue it depends on context -- for some methods return isinstance(the_str, str) and bool(the_str) might be what's necessary
That would return False or the value of the_str again, so not always a boolean.
-2
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.

1 Comment

!= already returns a bool, wrapping it again in bool() is entirely superfluous.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.