inner methods and recursion

Steve Howell showell30 at yahoo.com
Mon Jan 18 23:00:17 CET 2010


Hi, I have a style/design question relating to recursion and inner
methods.

I wrote some code recently that implements a recursive algorithm that
takes several parameters from the original caller.  Once the algorithm
starts running and recursing, those parameters remain the same, so I
define an inner method called "recurse" that essentially curries those
parameters.  In particular, the recurse method can get passed to a
callback method that the caller supplies, so that the caller can wrap
the recursive step with their own logic.

The only thing I don't like about the technique that I'm using is that
it seems needlessly repetitive to define mostly the same parameter
list in two different places.  The repetition seems mostly harmless,
but it seems like some kind of a smell that I'm overlooking a simpler
way to write the code.  I just can't put my finger on what it is.

    def indent_lines(lines,
                branch_method,
                leaf_method,
                pass_syntax,
                flush_left_syntax,
                flush_left_empty_line,
                indentation_method,
                get_block,
                ):
        def recurse(lines):
            return indent_lines(
                    lines,
                    branch_method,
                    leaf_method,
                    pass_syntax,
                    flush_left_syntax,
                    flush_left_empty_line,
                    indentation_method,
                    get_block,
                    )
        output = []
        while lines:
            if lines[0].strip() == '':
                lines.pop(0)
                output.append('')
            else:
                prefix, i = get_block(lines, indentation_method)
                if i == 1:
                    line = lines.pop(0)[len(prefix):]
                    if line == pass_syntax:
                        pass
                    elif line.startswith(flush_left_syntax):
                        output.append(line[len(flush_left_syntax):])
                    elif line.startswith(flush_left_empty_line):
                        output.append('')
                    else:
                        output.append(prefix + leaf_method(line))
                else:
                    block = lines[:i]
                    lines = lines[i:]
                    output += branch_method(prefix, block, recurse)
        return output

Does anybody have any inspiration here?  I vaguely recall a discussion
some time back about having some kind of @recursive decorator, but I
can't seem to find the thread.






More information about the Python-list mailing list