allowing braces around suites

Jeff Shannon jeff at
Thu Sep 2 22:34:47 CEST 2004

Antoon Pardon wrote:

>Suppose you have the following situation:
>|  def function
>|    def localfunction
>|      localfunction
>|      code
>|    function
>|    code
>My experience is that in such a situation, especially
>if the local functions grows of you have more 
>local functions it can become hard to see where the body
>of the global function begins. 

My experience is that defining local functions inside of parent 
functions is not a good way to deal with this situation.  I would, 
instead, write this as two separate module-level functions, one of which 
calls the other, and possibly indicating one of them as non-public via 
naming convention:

def mainfunction():
    x = y + z
    result = []
    for n in range(x):
        result.append( _subfunction(n) )
    return mylibrary.modify(result)

def _subfunction(n):
    if n > 5:
        while n:
            x, n = dostuff(n)
        x = math.sqrt(x)
    return x

Regardless of whether _subfunction() will ever be used anywhere else, I 
wouldn't define it inside of mainfunction().  (The only use I see for 
inner functions is to construct a function whose structure depends on 
outer-function data in a way that can't be reasonably expressed with a 
parameter -- and I see few cases of that.  Otherwise, the only gain from 
defining an inner function is name-hiding, and I find the complexity 
cost of inner functions to be much higher than the insignificant benefit 
gained by name-hiding.) 

There are few cases I have seen where the actions taken by an indented 
(possibly compound) code block cannot be given a reasonable name.  Once 
you can say "This segment of code does this action", you can encapsulate 
that segment into its own function named action().  You've now halved 
your indentation level, and also increased the abstraction level, making 
it easier for another person to read your code.

Presumably, you're going to assert that there are vague, undefined cases 
where there's no meaningful way to describe a subset of your nested 
code.  Personally, I wonder what the heck you're coding, because *I've* 
never seen (or heard of before now) use-cases in which it was so 
difficult to divide things into meaningful blocks. 

Jeff Shannon
Credit International

More information about the Python-list mailing list