Skip to content

Instantly share code, notes, and snippets.

@getadeo
Last active December 27, 2015 01:29
Show Gist options
  • Save getadeo/7245414 to your computer and use it in GitHub Desktop.
Save getadeo/7245414 to your computer and use it in GitHub Desktop.
def iter_except(func, exc_class, first=None):
try:
if first is not None:
yield first()
while 1:
yield func()
except exc_class:
pass
Samples:
>>> elements = set([1, 2, 3, 4, 5])
>>> iterator = iter_except(elements.pop, KeyError)
>>> iterator.next()
1
>>> elements
set([2, 3, 4, 5])
>>> list(iterator)
[2, 3, 4, 5]
>>> elements
set([])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment