Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def digfrom(iterable, *, depth=None, strings=True):
- """
- Dig values from nested iterables, flattening
- the input iterable.
- >>> iterable = [['a'], 'bc', ('de', ['f'])]
- >>> list(digfrom(iterable))
- ['a', 'b', 'c', 'd', 'e', 'f']
- Depth may be limited and "exploding" strings
- is optional.
- >>> list(digfrom(iterable, depth=2))
- ['a', 'b', 'c']
- >>> list(digfrom(iterable, strings=False))
- ['a', 'bc', 'de', 'f']
- """
- exhausted = object()
- iterable_attr = '__iter__'
- iterator_attr = '__next__'
- iterators = [iter(iterable)]
- while iterators:
- it = next(iterators[-1], exhausted)
- if it is exhausted:
- iterators.pop()
- continue
- if hasattr(it, iterable_attr):
- string = isinstance(it, str)
- if not ((string and len(it) <= 1) or
- (string and not strings)):
- it = iter(it)
- if hasattr(it, iterator_attr):
- iterators.append(it)
- iterators = iterators[:depth]
- else:
- yield it
- if hasattr(it, '__iter__'):
- string = isinstance(it, str)
- if not ((string and len(it) <= 1) or
- (string and not strings)):
- it = iter(it)
- if hasattr(it, '__next__'):
- iterators.append(it)
- iterators = iterators[:depth]
- is_string = isinstance(it, str)
- if not ((is_string and len(it) <= 1) or (is_string and not strings)):
- it = iter(it)
- is_string = isinstance(it, str)
- if not(is_string and len(it) <= 1) and not(is_string and not strings):
- it = iter(it)
- isnt_string = not isinstance(it, str)
- if (isnt_string or len(it) > 1) and (isnt_string or strings):
- it = iter(it)
- isnt_string = not isinstance(it, str)
- if isnt_string or (strings and len(it) > 1):
- it = iter(it)
- if (not hasattr(it, '__iter__')) or (len(it) <= 1):
- pass # can't explode this guy
- elif (not strings) and isinstance(it, str):
- pass # we're not exploding strings
- else:
- it = iter(it) # explode it
- iterators.append(it)
- iterators = iterators[:depth]
Add Comment
Please, Sign In to add comment