nested functions

George Sakkis george.sakkis at gmail.com
Thu Jun 15 06:12:28 CEST 2006


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. If you
actually call the outer function a lot, you'd better profile it.

George




More information about the Python-list mailing list