1 |
1881
|
aaronmk
|
# Iterators and iterables
|
2 |
1711
|
aaronmk
|
|
3 |
1881
|
aaronmk
|
def is_iterable(value): return getattr(value, '__iter__', False)
|
4 |
|
|
|
5 |
1892
|
aaronmk
|
# Sentinel to use in iter() if function return value should be ignored
|
6 |
|
|
iter_end = object()
|
7 |
|
|
|
8 |
|
|
def func_iter(func):
|
9 |
|
|
'''Used to iterate a generating function which raises StopIteration instead
|
10 |
|
|
of returning a sentinel value'''
|
11 |
|
|
return iter(func, iter_end)
|
12 |
|
|
|
13 |
|
|
def consume_iter(iter_):
|
14 |
|
|
for elem in iter_: pass
|
15 |
|
|
|
16 |
1711
|
aaronmk
|
def flatten(outer_iter):
|
17 |
|
|
for iter_ in outer_iter:
|
18 |
|
|
for el in iter_: yield el
|
19 |
|
|
|
20 |
|
|
def flatten_n(outer_iter, depth=2):
|
21 |
|
|
if depth < 2: return outer_iter
|
22 |
|
|
elif depth == 2: return flatten(outer_iter)
|
23 |
|
|
else: return flatten(flatten_n(outer_iter, depth-1))
|