简体   繁体   English

如何在具有相同条件的一个 try/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.我想知道是否有任何方法可以将下面的操作分组到一个 try/except 块中。 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.在那里你可以有一个包含所有键/类型对的单个try语句的循环。

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 :在这种情况下,我可能会完全摆脱try语句,而只需检查键是否在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):如果你真的想要一个 try 块,你可以尝试像这样重构(这是矫枉过正的 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在try块中为条件执行相同的代码而不重复except子句中的代码 - How can I execute same code for a condition in try block without repeating code in except clause 我怎样才能让我的for循环从try和except块中停下来的地方继续呢? Python 3 - How can i make my for loop continue from where it left off in the try and except block? Python 3 我应该如何在我的 for 循环中添加 Try & except Block 来处理 - How should I add Try & except Block to handle in my for loop 如何在try中除了块之外在Python中处理多个相同的错误类型 - How can I handle multiple same Error type in Python in try except block 如何编写捕获所有异常的 `try`/`except` 块? - How can I write a `try`/`except` block that catches all exceptions? 我如何在尝试中使用循环代码,除了代码? - How can I use loop code on try, except code? 如何使用单个 Try-Except 块解决多个错误消息? - How do I account for multiple error messages with a single Try-Except block? 使用Python,我如何尝试-除了单个函数中的几个不同输入之外,如果其中一个失败,其余部分仍会得到处理? - Using Python, how can I try - except a few different inputs in a single function, where if one fails, the remainder still get processed? Python:如何使用相同的 try/except 块简化多个语句 - Python: How to simplify multiple statements with the same try/except block 为什么我不能使用try / except块“忽略”这个ConnectionError? - Why can't I “ignore” this ConnectionError using a try/except block?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM