有时我需要在for
循环中使用以下模式。有时在同一个循环中不止一次:
try:
# attempt to do something that may diversely fail
except Exception as e:
logging.error(e)
continue
现在我看不到将其包装在函数中的好方法,因为它不能return continue
:
def attempt(x):
try:
raise random.choice((ValueError, IndexError, TypeError))
except Exception as e:
logging.error(e)
# continue # syntax error: continue not properly in loop
# return continue # invalid syntax
return None # this sort of works
如果return None
我能:
a = attempt('to do something that may diversely fail')
if not a:
continue
但我不觉得这样做是正义的。我想continue
从attempt
函数内部告诉 for 循环(或伪造它)。