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 <rep...@bugs.python.org> <http://bugs.python.org/issue20663> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com