Re:Python: Uncovering the Overlooked Core Functionalities
by strunz on Tuesday July 25, 2023 @12:43AM
(#36857984)
I actually had a great use case for this last week. Needed to flatten a list of nested dicts, e.g.:
Wound up writing a recursive generator (with some help from #python on IRC):
which results in:
[ Parent
| on HN ]
Re:Python: Uncovering the Overlooked Core Functionalities
by TrianguloY on Tuesday July 25, 2023 @02:51AM
(#36858847)
I see your function and "yield" (pun definitely intended) the following:
def flatten(children=[], **other):
if other: yield other
for child in children: yield from flatten(**child)
Re:Python: Uncovering the Overlooked Core Functionalities
by strunz on Tuesday July 25, 2023 @11:16AM
(#36863557)
That's pretty brilliant to use `children` as the keyword name, thanks!
Re:Python: Uncovering the Overlooked Core Functionalities
by noitpmeder on Friday July 28, 2023 @03:26AM
(#36903946)
Thanks for the example, but I was more looking for something that uses "generator.send(...)". I definitely agree that yielding items out of generators is extremely useful, but not so sure on examples of generators that are sent values.