iter_except

class iteration_utilities.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 iter(func, sentinel) but uses an exception instead of a sentinel to end the loop.

Parameters:
funccallable

The function that is called until exception is raised.

exceptionException

The exception which terminates the iteration.

firstcallable or None, optional

If not given (or not None) this function is called once before the func is executed.

Returns:
resultgenerator

The result of the func calls as generator.

Notes

Further examples:

  • bsd_db_iter = iter_except(db.next, bsddb.error, db.first)

  • heap_iter = iter_except(functools.partial(heappop, h), IndexError)

  • dict_iter = iter_except(d.popitem, KeyError)

  • deque_iter = iter_except(d.popleft, IndexError)

  • queue_iter = iter_except(q.get_nowait, Queue.Empty)

  • set_iter = iter_except(s.pop, KeyError)

Examples

>>> from iteration_utilities import iter_except
>>> from collections import OrderedDict
>>> d = OrderedDict([('a', 1), ('b', 2)])
>>> list(iter_except(d.popitem, KeyError))
[('b', 2), ('a', 1)]

Note

d.items() would yield the same result.

>>> from math import sqrt
>>> g = (sqrt(i) for i in [5, 4, 3, 2, 1, 0, -1, -2, -3])
>>> def say_go():
...     return 'go'
>>> list(iter_except(g.__next__, ValueError, say_go))
['go', 2.23606797749979, 2.0, 1.7320508075688772, 1.4142135623730951, 1.0, 0.0]
exception

(any type) The exception that ends iter_except (readonly).

New in version 0.6.

first

(any type) The function that is called once (as setup) by iter_except (readonly).

New in version 0.6.

func

(any type) The function that is called by iter_except (readonly).

New in version 0.6.