Last active
November 13, 2018 16:29
-
-
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"""
This file contains hidden or 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
| 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