nested functions

Georg Brandl g.brandl-nospam at gmx.net
Thu Jun 15 02:08:30 EDT 2006


George Sakkis wrote:
> Ben Finney wrote:
> 
>> "Gregory Petrosyan" <gregory.petrosyan at gmail.com> writes:
>>
>> > I often make helper functions nested, like this:
>> >
>> > def f():
>> >     def helper():
>> >         ...
>> >     ...
>> >
>> > is it a good practice or not?
>>
>> You have my blessing. Used well, it makes for more readable code.
> 
> I'm not sure it's in general more readable; I typically use nested
> functions for closures only, not helper functions, so I'd read the code
> twice to check if it's a closure and if not why might have been defined
> locally. I prefer to define helpers at the module level, often making
> them 'private' by prepending their name with a single underscore.
> 
>> > What about performance of such constructs?
>>
>> What about it? Set up some examples maningful for your situation, with
>> and without such constructs, and use the profiler to find out.
> 
> It shouldn't come as a surprise if it turns out to be slower, since the
> nested function is redefined every time the outer is called.

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.

Georg



More information about the Python-list mailing list