Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is returning a calculated boolean pythonic or I should use traditional if/else? [closed]

Tags:

python

I was wondering which of the following examples is more accepted within the Python community:

1.

return any(host[0].endswith(bot_hosts) for bot_hosts in bot_hosts)

2.

if any(host[0].endswith(bot_hosts) for bot_hosts in bot_hosts):
    return True
else:
    return False

Or maybe something else?

Please advise.

like image 278
Adam Silver Avatar asked Jan 16 '13 07:01

Adam Silver


2 Answers

In your example case: str.endswith takes tuple as an argument. Overall, as a design pattern use the first version (check the reasoning @Ben's answer). That is any(host[0].endswith(bot_host) for bot_host in bot_hosts) is the same as:

host[0].endswith(bot_hosts) #if bot_hosts is a tuple
                            #if bot_hosts in not a tuple add tuple(bot_hosts)

Example:

In [1]: suffs = ('a','b','d')

In [2]: 'asd'.endswith(suffs)
Out[2]: True

In [3]: 'asap'.endswith(suffs)
Out[3]: False
like image 111
root Avatar answered Sep 18 '22 16:09

root


if <anything>:
    return True
else:
    return False

is usually extremely pointless. <anything> has to return something truthy or falsey anyway, so just return that.

The only reason you would want to do this is if you want to make sure that you're returning only True or False, because your <anything> might be returning some other object. For example, maybe it might return a large object, which you no longer care about after checking that it was there, so you'd rather not return a reference to it that might prevent its memory from being reclaimed. Or maybe your <anything> might be returning an object or None, and while None is falsey you're concerned that later code will be using is not None tests, and you want the false path to not be counted as None.

Even then (as poke has pointed out in the comment), you can use bool(<anything>) to get a value that is guaranteed to be True or False based on the truthiness of <anything>, so there's never a good reason to use an if statement that immediately returns either True or False.

In your case, any always returns True or False. So you literally have a value that is either True or False, checking which one it is, and then returning True if it was True and returning False if it was False.

like image 27
Ben Avatar answered Sep 22 '22 16:09

Ben