Skip to content

Instantly share code, notes, and snippets.

@tubaman
Created June 1, 2024 16:07
Show Gist options
  • Save tubaman/c7080bbb830c87ea82065243c914b7d0 to your computer and use it in GitHub Desktop.
Save tubaman/c7080bbb830c87ea82065243c914b7d0 to your computer and use it in GitHub Desktop.
A generic version of listify that can take any type like list, set, dict
import functools
import types
def collect(collection_type):
"""A decorator that will collect stuff from a generator. For example,
>>> def tuple_generator():
... yield ('a', 'b')
... yield ('c', 'd')
...
>>> collect(dict)(tuple_generator)()
{'a': 'b', 'c': 'd'}
>>> collect(list)(tuple_generator)()
[('a', 'b'), ('c', 'd')]
>>> collect(set)(tuple_generator)()
{('c', 'd'), ('a', 'b')}
"""
def collectify(func):
@functools.wraps(func)
def new_func(*args, **kwargs):
r = func(*args, **kwargs)
if r is None:
return collection_type()
if isinstance(r, types.GeneratorType):
return collection_type(r)
return r
return new_func
return collectify
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment