Skip to content

Instantly share code, notes, and snippets.

@AndreaCrotti
Last active September 20, 2016 15:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndreaCrotti/1c98a8fbe313116f0a86ccd0221364ee to your computer and use it in GitHub Desktop.
Save AndreaCrotti/1c98a8fbe313116f0a86ccd0221364ee to your computer and use it in GitHub Desktop.
"""
Fun with toolz, wirting a decorator that merge dictionaries yielded from a genrator into a single result.
"""
import toolz
def merge_dicts(func):
"""Consume a generator that would yield dictionaries and merge them
all together
"""
def _merge_dicts(*args, **kwargs):
res = list(func(*args, **kwargs))
return toolz.merge(*res)
return _merge_dicts
@merge_dicts
def yield_dicts():
for n in range(10):
yield {n: (n + 1)}
print(yield_dicts())
# {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9, 9: 10}
@gglanzani
Copy link

def _merge_dicts(*args, **kwargs):
    Res = func(*args, **kwargs)
    dct = next(Res)
    for f in Res:
        dct = toolz.merge(dct, f)
        yield dct

@AndreaCrotti
Copy link
Author

Ok thanks but just to clarify the intent is to have a function that returns still a big dictionary, but writing it as it was yielding small ones.

So I can't really make it lazy in that sense, because I still want the whole result before returning..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment