Created
June 1, 2024 16:07
-
-
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
This file contains 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
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