Search code examples
pythonexceptiontry-except

How can I group single and loop operations in one try/except block with same condition?


I wonder if there is any way to group operations below in one try/except block. I use the same exception in both cases. I was trying to shorten this code, but nothing good comes to my mind. Here is example code:

def cast_values(values):
    try:
        values['Price'] = float(values['Price'])
    except KeyError:
        pass

    for field in ('Pages', 'Quantity', 'Discount'):
        try:
            values[field] = int(values[field])
        except KeyError:
            pass

I want all keys to be checked, doesn't matter how many exceptions will occur.


Solution

  • You can generalize your code by factoring out the pairing of a key to a particular type. There you can have a single loop with a single try statement that accommodates all your key/type pairs.

    def cast_values(values):
        type_map = {
            'Price': float,
            'Pages': int,
            'Quantity': int,
            'Discount': int,
        }
    
        for key, type_ in type_map.items():
            type_ = types.get(key, int)
            try:
                values[key] = type_(values[key])
            except KeyError:
                pass
    

    In this case, I would probably get rid of the try statement altogether, and simply check if the key is in values:

    for key, type_ in type_map.items():
        if key not in values:
            continue
        values[key] = type_(values[key])