iter_except

sknano.core.itertools.iter_except(func, exception, first=None)[source] [edit on github][source]

Call a function repeatedly until an exception is raised.

Converts a call-until-exception interface to an iterator interface. Like builtins.iter(func, sentinel) but uses an exception instead of a sentinel to end the loop.

Parameters:

Examples

>>> from sknano.core import iter_except
>>> list(iter_except(list(range(3)).pop, IndexError))
[2, 1, 0]
>>>

priority queue iterator:

>>> # iter_except(functools.partial(heappop, h), IndexError)

non-blocking dict iterator:

>>> # iter_except(d.popitem, KeyError)

non-blocking deque iterator:

>>> # iter_except(d.popleft, IndexError)

loop over a producer Queue:

>>> # iter_except(q.get_nowait, Queue.Empty)

non-blocking set iterator:

>>> # iter_except(s.pop, KeyError)