Python在第一个StopIteration上退出使用者 [英] Python exit consumer on first StopIteration
问题描述
It's a follow-up to my 1 generator -- multiple consumers question. As StopIteration
is the way the generator signals its exhaustion, unfortunately, I now have many exception-handling code littered all over the place in the client
code (for every next()
statement in the example below).
是否有一个遇到第一个 StopIteration
异常时,使用 meal
内置的任何值退出的更好方法是什么?
Is there a better way to exit with whatever value is built in meal
upon hitting the first StopIteration
exception?
def client(course, take):
meal = []
for _ in range(take):
try:
some_meal = next(course)
meal.append(some_meal)
except StopIteration:
pass
if take % 2 == 0:
try:
some_meal = next(course)
meal.append(some_meal)
except StopIteration:
pass
return meal
更新最终,我最终使用了'itertools.islice'(请参见accepte下面的d解决方案),因为此函数负责处理 StopIteration
本身(请参见 for
循环等效的实现, itertools
文档。与使用 next
默认第二个参数相比,我更喜欢这种解决方案,因为它暗示着检查每个 meal
(不过,我还是最好
UPDATE Eventually, I ended up using 'itertools.islice' (see accepted solution below) as this function takes care of the StopIteration
itself (see the for
-loop equivalent implementation shown in the itertools
doc. I prefer this solution over using next
default second argument as it would imply checking each meal
(still, I'd better use the latter than all the exception handling above).
推荐答案
只需直接在第一个异常处理程序中返回:
Just return directly in the first exception handler:
def client(course, take):
meal = []
for _ in range(take):
try:
some_meal = next(course)
meal.append(some_meal)
except StopIteration:
return meal
if take % 2 == 0:
try:
some_meal = next(course)
meal.append(some_meal)
except StopIteration:
pass
return meal
尽管我在这里仍会使用标准库,而不必捕获那些 StopIteration
异常几乎一样多:
although I'd still use the standard library more here and not have to catch those StopIteration
exceptions nearly as much:
from itertools import islice
def client(course, take):
meal = list(islice(course, take))
if take % 2 == 0:
some_meal = next(course, None)
if some_meal is not None:
meal.append(some_meal)
return meal
这篇关于Python在第一个StopIteration上退出使用者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!