optimization

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Tue Dec 2 05:27:00 EST 2008


On Mon, 01 Dec 2008 18:11:16 -0600, Robert Kern wrote about nested 
functions:

> I, for one, find that significantly less clear. I only expect functions
> to be defined inside of functions if they are going to use lexical
> scoping for some reason. If I read your code, I'd probably waste a good
> five minutes trying to figure out what part of the local scope you were
> using before I would conclude that you just did it because you thought
> it looked better.

Hah, I bet you aren't an ex-Pascal programmer :-)

Speaking as one, it took me a long time to teach myself not to bother 
nesting functions for the purpose of avoiding scoping clashes. I'd write 
something like this:

def parrot():
    def colour():
        return "Blue"
    return "Norwegian %s" % colour()


def cardinal(x):
    def colour():
        return "crimson"
    return "Cardinal Fang wears a %s robe" % colour()


Except of course that's a trivially silly example. (For the sake of the 
argument, let's pretend the two functions colour() do actual 
calculations.)

These days, I'd write them something like this:

def parrot_colour():
    return "Blue"

def cardinal_colour():
    return "crimson"

def parrot():
    return "Norwegian %s" % parrot_colour()

def cardinal(x):
    return "Cardinal Fang wears a %s robe" % cardinal_colour()


These days, almost the only time I use nested functions is for function 
factories.



-- 
Steven



More information about the Python-list mailing list