nested functions

Duncan Booth duncan.booth at invalid.invalid
Thu Jun 15 09:58:32 CEST 2006

Georg Brandl wrote:

> That's right. However, if the outer function is only called a few times
> and the nested function is called a lot, the locals lookup for the
> function name is theoretically faster than the globals lookup. Also,
> in methods you can use closures, so you don't have to pass, for example,
> self to the inner function.

If you are worried about the overhead of looking up the function name in 
the local rather than global scope then you should also worry about the 
overhead of accessing self through a closure rather than as a parameter.

As always in these cases, don't worry about it until you know definitely 
(by timing) that performance is an issue in that part of your code, and 
then time the different options and refuse the temptation to guess as you 
will probably get it wrong. The relative times here will depend on a lot of 
factors, such as how often you access the closure/parameter, and whether or 
not there are other arguments to the function.

I frequently nest functions, but I do it in cases where I want to simplify 
a function body and don't see any case for creating yet another generally 
accessible method or function.

Some benefits of nested functions: you can use a function name which is 
short by self-explanatory within the context of the outer function without 
having to worry about it conflicting with other function/variable names. 

The extracted functions are kept close to the place where they are used: a 
small support function which is a few hundred lines away from where it 
is used is more accident prone than one right next to the place it is used. 
Also, if you later refactor out the main method the support functions will 
disappear as well rather than lying around unused.

You can use closures, not because you have to, but because it simplifies 
the calls and therefore keeps expressions simpler and easier to read.

Of course you can also mess things up totally by overdoing it.

More information about the Python-list mailing list