Skip to content

Instantly share code, notes, and snippets.

@Tadaboody
Last active November 13, 2018 16:29
Show Gist options
  • Select an option

  • Save Tadaboody/046da962566f4d32cfe926fd28ff71d5 to your computer and use it in GitHub Desktop.

Select an option

Save Tadaboody/046da962566f4d32cfe926fd28ff71d5 to your computer and use it in GitHub Desktop.
"""Returns an generator of all the items in `generator` that didn't throw"""
from typing import Iterator, TypeVar, Generator
T = TypeVar('T')
def try_yield(generator: Iterator[T])->Generator[T, None, None]:
"""Returns an generator of all the items in `generator` that didn't throw"""
while True:
try:
yield next(generator)
except StopIteration:
return
except Exception:
pass
# Example usage converting only strings that are numbers:
numbers = list(try_yield(int(thing) for thing in ['a','1','not a number','2',4]))
# numbers = [1,2,4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment