【发布时间】:2011-08-29 14:06:03
【问题描述】:
有时我需要在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
但我不认为这样做是公平的。我想从 attempt 函数中告诉 for 循环到 continue(或伪造它)。
【问题讨论】:
-
为什么会有将四行代码 [try-except-log-continue] 包装成不那么透明的冲动?
-
在函数内部引发异常然后在循环中捕获它有什么问题?
-
你做错了。如果您将 for 循环用作常见模式,请将 that 包装在函数中,而不是循环的元素。
-
几年后看这个,“except Exception:”或“except Exception as e:”是最恶魔的Python反模式realpython.com/blog/python/…