[英]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.