[issue20663] Introduce exception argument to iter
Raymond Hettinger
report at bugs.python.org
Thu Jul 3 23:16:55 CEST 2014
Raymond Hettinger added the comment:
Your suggestion and an example appears to have been taken directly from the itertools recipes:
def iter_except(func, exception, first=None):
""" Call a function repeatedly until an exception is raised.
Converts a call-until-exception interface to an iterator interface.
Like __builtin__.iter(func, sentinel) but uses an exception instead
of a sentinel to end the loop.
Examples:
bsddbiter = iter_except(db.next, bsddb.error, db.first)
heapiter = iter_except(functools.partial(heappop, h), IndexError)
dictiter = iter_except(d.popitem, KeyError)
dequeiter = iter_except(d.popleft, IndexError)
queueiter = iter_except(q.get_nowait, Queue.Empty)
setiter = iter_except(s.pop, KeyError)
"""
try:
if first is not None:
yield first()
while 1:
yield func()
except exception:
pass
FWIW, this idea was explored before an aside from the examples given in the docstring above, it seems to have very limited application. Accordingly, it was left as a recipe and not added to itertools or the the iter() function.
----------
assignee: -> rhettinger
nosy: +rhettinger
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue20663>
_______________________________________
More information about the Python-bugs-list
mailing list