Last active
December 27, 2015 01:29
-
-
Save getadeo/7245414 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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