Return one of two types of strings

I have a Python function that can return either one of two return types, animal

or food

. Both are string types. Right now I differentiate between them, always returning two values, claiming that only of these True

:

def help(x):
    if some_condition(x):
        return 'monkey', None
    elif # ...
        animal = some_fantasy_animal(x)
        return animal, None
    elif #..
        food = some_food_no_one_has_ever_heard_of(x)
        return None, food
    elif # ...
        return None, 'steak'
    # ...



def main():
    animal, food = help('ddd')
    if animal:
        assert(not food)
        # do something useful
        pass
    else:
        assert(food)
        # do something useful
        pass
    return

      

There must be a better way to handle this. What are the options?

+3


source to share


4 answers


Your script looks strange

You might want to create an Animal class and a Food class and derive them from some common base class. Then you can use isinstance

or better, forget the conditions if

and call the method defined in the base class, which you can override for each type.



If there is no commonality between Food and Animal, then you probably shouldn't have one function that can return any type.

+1


source


Ok, you could create a set of animals and products like:

animals={'hippo', 'monkey'}
food={'bananas', 'steak'}

      



and then check with operator in

:

h = help('ddd')

if h in animals:
    ...
elif h in food:
    ...

      

0


source


This might be the solution. Presenting data as:

data = {'animal':['cat','dog'], 'food':['steak','egg']}

      

To check if a specific value is x

animal or food:

t = [k for k, v in data.iteritems() if x in data[k]]

      

t

will contain the class that a particular element belongs to. Note that if animal

also present as food

, then t

will contain both. Kind of flexible!

0


source


You can create a class that takes arguments to pass all the logic that refers to the type definition inside:

eg:

class Result(object):
  def __init__(self, animal=None, food=None):
    self.animal = animal
    self.food = food 

  @property
  def is_animal(self):
    return self.animal != None

  @property
  def is_food(self):
    return self.food != None

def help(x):
  if x == 1:
    return Result(animal='monkey')
  elif x == 2:
    return Result(animal='hippo')
  elif x == 3:
    return Result(food='bananas')
  else:
    return Result()

if __name__ == '__main__':
  result = help(3)
  if result.is_animal:
    print result.animal
  if result.is_food:
    print result.food

      

0


source







All Articles