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.
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With