Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should my function return False if it has to return a boolean value?

What are the benefits of writing:

def contains(lst, n):
  for x in lst:
    if x == n:
      return True
  return False

instead of:

def contains(lst, n):
  for x in lst:
    if x == n:
      return True

?

Please note that in the second example the last line of code is missing, and the function returns None instead of False.

Side note: I'm aware I should write n in lst, this is just an example.

like image 916
Nick Avatar asked Dec 11 '22 02:12

Nick


2 Answers

I think to some extent this is a matter of personal preference.

I personally would always prefer former over the latter, since "explicit is better than implicit".

Also, if the function is expected to return a bool, I think it's cleaner to return a bool and not some other object whose truthiness needs to be evaluated in order to get a bool.

like image 93
NPE Avatar answered Jan 18 '23 22:01

NPE


It really depends on how you intend the function to be used.

If it's only ever going to be used in a boolean context, it might make sense to define and document it as "returns something truthy or something falsey", in which case it's reasonable to return None as something falsey.

But if you expect people to, say, log the result for human debugging purposes, or use it as a key in a dictionary—or you just don't know how it's going to be used—it's a lot clearer to say it returns a boolean and then explicitly return False.

In fact, it's often a nice idea to be stricter than you promise in what you provide; even if you only document that you're returning something truthy or falsey, it won't actually hurt to always return True or False, unless you have some other value that could be meaningful.* As the other answers imply, this doesn't just go along with general programming principles, but also the specific Python Zen "explicit is better than implicit".

* If you're thinking that it could hurt performance, it won't, even if that were an issue. An implicit return None complies to exactly the same LOAD_CONST and RETURN_VALUE as an explicit return None—or, of course, an explicit return False.

like image 43
abarnert Avatar answered Jan 18 '23 22:01

abarnert