Last active
July 31, 2019 17:51
-
-
Save nikolas/911fdb907f556f506f35a01e3a31aa8e to your computer and use it in GitHub Desktop.
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
from collections import Iterable, Mapping | |
from operator import methodcaller | |
def flatten(it, map_iter='values', max_depth=128): | |
if max_depth < 0: | |
try: | |
raise RecursionError('maximum recursion depth exceded in flatten') | |
except NameError: | |
raise Exception('maximum recursion depth exceded in flatten') | |
elif isinstance(it, str): | |
yield it | |
elif isinstance(it, Mapping): | |
for item in methodcaller(map_iter)(it): | |
for x in flatten( | |
item, map_iter=map_iter, max_depth=max_depth-1): | |
yield x | |
elif isinstance(it, Iterable): | |
for item in it: | |
yield x | |
else: | |
yield it |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment