Home > Mobile >  Raise an Error if input is an empty list in Python function
Raise an Error if input is an empty list in Python function

Time:02-11

I have got the following function which has to check if the input_list is empty.

def prepare_data(
    input_list: List[np.ndarray], data: Union[np.ndarray, Dict[str, np.ndarray]]
) -> Dict[str, np.ndarray]:
    """[summary]
    Function to dynamically preprare input data to in correct input format for ONNX InferenceSession (dict)
    Parameters
    ----------
    input_list : List[np.ndarray]
        [description]
    data : Union[np.ndarray, Dict[str, np.ndarray]]
        Data for Inferencession which can be an np.array or dictionary with multiple np.arrays

    Returns
    -------
    Dict[str, np.ndarray]
        Dynamic input_feed as dictionary
    """
    if len(input_list) == 0:
        raise IndexError("input_list is not allowed to be an empty list") # Wrong?

    if len(input_list) > 1:
        input_feed = {}
        for feed in input_list:
            input_feed[feed] = data.get(feed)
    else:
        input_feed = {input_list[0]: data}
    return input_feed

I tried to solve it with raise IndexError, but I am not sure if that´s the best way or might not even work as expected.

The function has to stop executing if an empty list is passed. What is a good pythonic way to do this?

CodePudding user response:

First of all your if condition is wrong. It should be

if len(input_list) == 0:

Secondly, error handling in python is done using try except blocks. You can do it like this:

try:
    # do something that might raise an exception
except IndexError:
    print("Exception raised")
    sys.exit() # if you want the program to end

Note: you need to import sys first if you want to use sys.exit

CodePudding user response:

As @daniyal-ishfaq mentioned you have to correct your conditional first. Then a good oneliner for such things would be using assert method as follows:

assert len(input_list) == 0, "your error message here"
  • Related