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로 이동합니다.파이썬에서 컨텍스트 내에서 발생하는 여러 오류를 무시하고 컨텍스트 내에서 중단없이 LINE-A에서 LINE-Z까지 계속 실행할 수있는 대체 구문이나 기능이 있습니까? 즉, LINE-A에서 예외가 발생하면 LINE-1로 건너 뛰는 대신 LINE-B로 실행이 계속됩니다.
LINE-A에서 LINE-Z까지 각 줄을 가리기 위해 여러 번의 시도 제외를 사용하는 것은 실제로 가독성에 심각한 영향을 미치기 때문에 깨끗한 옵션이 아닙니다.
try:
#LINE-A...
except ValueError:
pass
finally:
try:
#LINE-B...
except ValueError:
pass
finally:
#....
LINE-A의 각 을 자체 억제
로 LINE-Z로 감싸는 것은 하나의 가능성이지만 가독성이 떨어 지므로 더 많은 대안이 있는지 묻습니다.
이건 어때?
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]
목록을 완전히 지우려면 시도해보십시오.
while test_condition:
biglist.clear()
모든 단일 값을 제거하려고하면 이것을 사용하십시오.
a = 220
while test_condition:
try:
biglist.remove(a)
except ValueError:
a -= 1
continue