Project

General

Profile

1
# Iterators and iterables
2

    
3
def is_iterable(value): return getattr(value, '__iter__', False)
4

    
5
# 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
def flatten(outer_iter):
17
    if is_iterable(outer_iter):
18
        for iter_ in outer_iter:
19
            if is_iterable(iter_):
20
                for el in iter_: yield el
21
            else: yield iter_
22
    else: yield outer_iter
23

    
24
def flatten_n(outer_iter, depth=2):
25
    if depth < 2: return outer_iter
26
    elif depth == 2: return flatten(outer_iter)
27
    else: return flatten(flatten_n(outer_iter, depth-1))
(15-15/33)