Last active
September 27, 2021 12:41
-
-
Save georg-wolflein/c2a2c5358fba22be447f83cbd202f518 to your computer and use it in GitHub Desktop.
Decorator to convert Python generator functions to lists or dicts. Also supports asynchronous functions.
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 functools import wraps, partial | |
| import inspect | |
| def _ify(func, factory=list): | |
| if inspect.isasyncgenfunction(func): | |
| @wraps(func) | |
| async def new_func(*args, **kwargs): | |
| return factory([x async for x in func(*args, **kwargs)]) | |
| else: | |
| @wraps(func) | |
| def new_func(*args, **kwargs): | |
| return factory(func(*args, **kwargs)) | |
| return new_func | |
| listify = partial(_ify, factory=list) | |
| dictify = partial(_ify, factory=dict) |
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 listify import listify, dictify | |
| def test_listify(): | |
| @listify | |
| def func(): | |
| yield from range(10) | |
| assert func() == list(range(10)) | |
| def test_dictify(): | |
| @dictify | |
| def func(): | |
| for i in range(10): | |
| yield i, i+1 | |
| assert func() == dict(zip(range(10), range(1, 11))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment