Search code examples
pythonbooleannonetype

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.


Solution

  • 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.