有时在for
循环中需要以下模式。有时在同一循环中发生多次:
try:
# attempt to do something that may diversely fail
except Exception as e:
logging.error(e)
continue
现在我没有看到一个好的方法来将此内容封装为函数,因为它不能返回 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
但我觉得这并不能完全说明问题。我想告诉for循环从attempt
函数内部continue
(或伪造它)。