Example #1
0
def flatten(tree, leaves=()):
    ''' Flatten a tree, that is, recursively concatenate nested sequences.

        >>> flatten([1, [[2, 3], 4, 5], [[[[6]]]]])
        [1, 2, 3, 4, 5, 6]
        >>> mixed = [1, [[2], 3], (4, 5), [(6,)], 'abc']
        >>> flatten(mixed)
        [1, 2, 3, 4, 5, 6, 'a', 'b', 'c']
        >>> flatten(mixed, leaves=(str,))
        [1, 2, 3, 4, 5, 6, 'abc']
        >>> flatten(mixed, leaves=(str, tuple))
        [1, 2, 3, (4, 5), (6,), 'abc']
        >>> flatten([])
        []
        >>> flatten(1)
        [1]
    '''
    # Pass leaf types around, avoiding infinite regress on strings
    _is_fork = partial(is_fork, leaves=leaves)
    if isinstance(tree, basestring):
        leaves += (basestring, )
    _flatten = partial(flatten, leaves=leaves)

    if not _is_fork(tree):
        return [tree]
    else:
        return concat(_flatten(n) for n in tree)
Example #2
0
File: tree.py Project: fspaolo/code
def flatten(tree, leaves=()):
    ''' Flatten a tree, that is, recursively concatenate nested sequences.

        >>> flatten([1, [[2, 3], 4, 5], [[[[6]]]]])
        [1, 2, 3, 4, 5, 6]
        >>> mixed = [1, [[2], 3], (4, 5), [(6,)], 'abc']
        >>> flatten(mixed)
        [1, 2, 3, 4, 5, 6, 'a', 'b', 'c']
        >>> flatten(mixed, leaves=(str,))
        [1, 2, 3, 4, 5, 6, 'abc']
        >>> flatten(mixed, leaves=(str, tuple))
        [1, 2, 3, (4, 5), (6,), 'abc']
        >>> flatten([])
        []
        >>> flatten(1)
        [1]
    '''
    # Pass leaf types around, avoiding infinite regress on strings
    _is_fork = partial(is_fork, leaves=leaves)
    if isinstance(tree, basestring):
        leaves += (basestring,)
    _flatten = partial(flatten, leaves=leaves)

    if not _is_fork(tree):
        return [tree]
    else:
        return concat(_flatten(n) for n in tree)
Example #3
0
 def _get_sub_context_names ( self ):
     return concat( self._sub_contexts.values() )