Guest User

Untitled

a guest
Jun 18th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. def digfrom(iterable, *, depth=None, strings=True):
  2. """
  3. Dig values from nested iterables, flattening
  4. the input iterable.
  5.  
  6. >>> iterable = [['a'], 'bc', ('de', ['f'])]
  7.  
  8. >>> list(digfrom(iterable))
  9. ['a', 'b', 'c', 'd', 'e', 'f']
  10.  
  11.  
  12. Depth may be limited and "exploding" strings
  13. is optional.
  14.  
  15. >>> list(digfrom(iterable, depth=2))
  16. ['a', 'b', 'c']
  17.  
  18. >>> list(digfrom(iterable, strings=False))
  19. ['a', 'bc', 'de', 'f']
  20.  
  21.  
  22. """
  23.  
  24. exhausted = object()
  25. iterable_attr = '__iter__'
  26. iterator_attr = '__next__'
  27.  
  28. iterators = [iter(iterable)]
  29.  
  30. while iterators:
  31. it = next(iterators[-1], exhausted)
  32.  
  33. if it is exhausted:
  34. iterators.pop()
  35. continue
  36.  
  37. if hasattr(it, iterable_attr):
  38. string = isinstance(it, str)
  39.  
  40. if not ((string and len(it) <= 1) or
  41. (string and not strings)):
  42. it = iter(it)
  43.  
  44. if hasattr(it, iterator_attr):
  45. iterators.append(it)
  46. iterators = iterators[:depth]
  47. else:
  48. yield it
  49.  
  50. if hasattr(it, '__iter__'):
  51. string = isinstance(it, str)
  52. if not ((string and len(it) <= 1) or
  53. (string and not strings)):
  54. it = iter(it)
  55. if hasattr(it, '__next__'):
  56. iterators.append(it)
  57. iterators = iterators[:depth]
  58.  
  59. is_string = isinstance(it, str)
  60. if not ((is_string and len(it) <= 1) or (is_string and not strings)):
  61. it = iter(it)
  62.  
  63. is_string = isinstance(it, str)
  64. if not(is_string and len(it) <= 1) and not(is_string and not strings):
  65. it = iter(it)
  66.  
  67. isnt_string = not isinstance(it, str)
  68. if (isnt_string or len(it) > 1) and (isnt_string or strings):
  69. it = iter(it)
  70.  
  71. isnt_string = not isinstance(it, str)
  72. if isnt_string or (strings and len(it) > 1):
  73. it = iter(it)
  74.  
  75. if (not hasattr(it, '__iter__')) or (len(it) <= 1):
  76. pass # can't explode this guy
  77. elif (not strings) and isinstance(it, str):
  78. pass # we're not exploding strings
  79. else:
  80. it = iter(it) # explode it
  81.  
  82. iterators.append(it)
  83. iterators = iterators[:depth]
Add Comment
Please, Sign In to add comment