Skip to content

Instantly share code, notes, and snippets.

@nikolas
Last active July 31, 2019 17:51
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 nikolas/911fdb907f556f506f35a01e3a31aa8e to your computer and use it in GitHub Desktop.
Save nikolas/911fdb907f556f506f35a01e3a31aa8e to your computer and use it in GitHub Desktop.
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