Skip to content

Instantly share code, notes, and snippets.

@nikolas nikolas/
Last active Jul 31, 2019

What would you like to do?
from collections import Iterable, Mapping
from operator import methodcaller
def flatten(it, map_iter='values', max_depth=128):
if max_depth < 0:
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
yield it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.