gpt4 book ai didi

python - 是否存在忽略多个错误并继续执行而不跳转的上下文?

转载 作者:行者123 更新时间:2023-12-01 14:33:36 30 4
gpt4 key购买 nike

with suppress(ValueError):
while test_condition:
biglist.remove(222) # element that doesn't exist, raises error. but we dont care abt this error.
# LINE-A: more remove kind of calls where we are dont care abt ValueError(s) raised
# LINE-B: ...
# ...
# LINE-Z: ...

# LINE-1: some statement..
# some more statements...

使用 contextlib.suppress,while 循环在第一个异常发生时停止,执行跳转到 LINE-1。Python 中是否有替代构造或设施,我们可以忽略上下文中发生的多个错误,并在上下文中从 LINE-A 到 LINE-Z 不间断地继续执行。也就是说,如果 LINE-A 发生异常,则继续执行 LINE-B 而不是跳转到 LINE-1。

使用多个 try-except-finally 来覆盖从 LINE-A 到 LINE-Z 的每一行对我来说并不是一个干净的选择,因为它会严重影响可读性。

try:
#LINE-A...
except ValueError:
pass
finally:
try:
#LINE-B...
except ValueError:
pass
finally:
#....

用它们自己的 with suppress 包装 LINE-A 到 LINE-Z 的 each 是一种可能性,但可读性较差,所以我问是否有替代方案更多

最佳答案

这个呢?

def do_it(func, *args,suppress_exc=None, **kwargs):
params = locals().copy()
suppress_exc= suppress_exc or (ValueError,)
try:
func(*args, **kwargs)
print("\nsweet %s worked" % (params))
return 0
except suppress_exc as e: #pragma: no cover
print("\nbummer %s failed" % (params))
return e


biglist = [200, 300, 400]

while True:

if not do_it(biglist.remove, 201):
break

if not do_it(biglist.pop, 6, suppress_exc=(IndexError,)):
break

if not do_it(biglist.remove, 200):
break

if not do_it(biglist.remove, 300):
break

if not do_it(biglist.remove, 400):
break

print("done:biglist:%s" % (biglist))

输出:

bummer {'kwargs': {}, 'args': (201,), 'suppress_exc': None, 'func': <built-in method remove of list object at 0x106093ec8>} failed

bummer {'kwargs': {}, 'args': (6,), 'suppress_exc': (<class 'IndexError'>,), 'func': <built-in method pop of list object at 0x106093ec8>} failed

sweet {'kwargs': {}, 'args': (200,), 'suppress_exc': None, 'func': <built-in method remove of list object at 0x106093ec8>} worked
done:biglist:[300, 400]

关于python - 是否存在忽略多个错误并继续执行而不跳转的上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59202054/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com