简体   繁体   中英

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.

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])

If you really want one try block you can try to refactor like this (this is overkill tbh):

def cast_dict(dict_, key, type_):
    try:
        dict_[key] = type_(dict_[key])
    except KeyError:
        pass

def cast_values(values):
    cast_dict(values, 'Price', float)
    for field in ('Pages', 'Quantity', 'Discount'):
        cast_dict(values, field, int)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM