Skip to content

Instantly share code, notes, and snippets.

@georg-wolflein
Last active September 27, 2021 12:41
Show Gist options
  • Select an option

  • Save georg-wolflein/c2a2c5358fba22be447f83cbd202f518 to your computer and use it in GitHub Desktop.

Select an option

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.
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)
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