gpt4 book ai didi

Python:如何告诉 for 循环从函数继续?

转载 作者:IT老高 更新时间:2023-10-28 21:12:59 25 4
gpt4 key购买 nike

有时我需要在 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 (或伪造它)。

最佳答案

Python 已经有一个非常好的结构来执行此操作,并且它不使用 continue:

for i in range(10):
try:
r = 1.0 / (i % 2)
except Exception, e:
print(e)
else:
print(r)

不过,我不会嵌套更多,否则您的代码很快就会变得非常难看。

在你的情况下,我可能会做更多这样的事情,因为对单个函数和 flat is better than nested 进行单元测试要容易得多。 :

#!/usr/bin/env python

def something_that_may_raise(i):
return 1.0 / (i % 2)

def handle(e):
print("Exception: " + str(e))

def do_something_with(result):
print("No exception: " + str(result))

def wrap_process(i):
try:
result = something_that_may_raise(i)
except ZeroDivisionError, e:
handle(e)
except OverflowError, e:
handle(e) # Realistically, this will be a different handler...
else:
do_something_with(result)

for i in range(10):
wrap_process(i)

请记住始终 catch specific exceptions .如果您不希望抛出 特定 异常,则继续处理循环可能不安全。

编辑以下评论:

如果你真的不想处理异常,我仍然认为这是一个坏主意,那么捕获所有异常 (except:) 而不是 handle(e),只需 pass。此时 wrap_process() 将结束,跳过真正完成工作的 else: block ,您将进入 的下一次迭代for-循环。

请记住,Errors should never pass silently .

关于Python:如何告诉 for 循环从函数继续?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6071050/

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