Search code examples
pythoniterable-unpacking

Python idiomatic unpacking assignment or False


If function returns a two value list or tuple on success or False on failure, how can I best unpack the return list into two variables while also checking for False?

def get_key_value():
  if (cond != True):
    return False
  return [val1, val2]

# Call it
# How can I also check for False while unpacking?
key, value = get_key_value()

Solution

  • Coverting @Felix Kling's great comment into an answer.

    If not being able to find a (key, value) pair indicates some kind of system failure, it would be better to throw an exception. If your failure doesn't really fall into any of the standard exceptions, you should build a new exception type of your own.

    The cond != True is better written as not cond. Also it's better to not create a list if it's not necessary.

    class DataNotFound(Exception): pass
    
    def get_key_value():
      if not cond:
        raise DataNotFound("Couldn't find it!")
      return val1, val2
    
    try:
        key,value = get_key_value()
    except DataNotFound:
        #handle the failure somehow
        key, value = 'ERROR', 'ERROR'