Home > Software design >  Checking input multiple times and returning variables if found
Checking input multiple times and returning variables if found

Time:10-03

I am building a script that will have some kind of JSON as an input. One of the variables in this JSON is fruit name and based on the name of the fruit I want to set its family and sometimes return different variables depending on what fruit is it.

The code is working, but I don't really like it. I believe there is a better way of writing such stuff that I cannot really find. Can someone please point me to the right direction?

def check_fruit_type(fruit_description: dict) -> dict:
  fruit_type= fruit_description.get("fruit_name"):

  if "citrone" in fruit_name:
    fruit_family = "rutaceae"
    seeds = True
  elif "cherry" in fruit_name:
    fruit_family = "rosaceae"
    seedless = True
  else:
    logger.error("Sorry, but we are not able to recognize the fruit name")
    return None

  return {"fruit_family": fruit_family, "seeds": seeds }

Now my problem is that I am going to have a long list - around 10-15 of these elif comparisons. Another problem is that some fruits might not need seeds or seedless variable, so I suppose I should just put somewhere at the top of my function seeds = None or seedless = None and in case the fruit_name matches my if statement - it will overwrite the None value to the right one.

What will you change in this code to make it more pythonish/better in terms of readability and future maintenance?

CodePudding user response:

I'd suggest creating a mapping with all the information and then returning the specific value for your name:

MAPPING = {
    "citrone": {"fruit_family": "rutaceae", "seeds": True},
    "cherry": {"fruit_family": "rosaceae", "seeds": False, "key3": "info3"}
}  # you can place that in a separate file

def check_fruit_type(fruit_description: dict) -> dict:
    fruit_name = fruit_description.get("fruit_name")
    return MAPPING.get(fruit_name, {})

check_fruit_type({"fruit_name": "cherry", "key2": "val2"})

I'd also try to be consistent with the variable/names. Instead of having seeds = True and seedless = True I would go with seeds = True and seeds = False

CodePudding user response:

A simple dictionary to store your conditionals would make your code a lot easier to maintain:

def check_fruit_type(fruit_description: dict) -> dict:
    fruit_map = {
        'citrone': {'fruit_family': 'rutaceae', 'has_seeds': True},
        'cherry': {'fruit_family': 'rosaceae', 'has_seeds': True},
    }
    fruit_name = fruit_description['name']
    try:
        fruit_attr = fruit_map[fruit_name]
    except KeyError:
        logger.error("Sorry, but we are not able to recognize the fruit name")
        return None
    
    return {"fruit_family": fruit_attr['fruit_family'] , "has_seeds": fruit_attr['has_seeds']}

fruit = {'name': 'citrone'}
check_fruit_type(fruit)  # {'fruit_family': 'rutaceae', 'has_seeds': True}
  • Related