Last active
September 20, 2016 15:41
-
-
Save AndreaCrotti/1c98a8fbe313116f0a86ccd0221364ee to your computer and use it in GitHub Desktop.
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
""" | |
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
commented
Sep 20, 2016
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