"helper function" style question

Peter Hansen peter at engcorp.com
Mon Jul 12 18:58:35 EDT 2004


Robert Ferrell wrote:

> I have a style question.  I have a class with a method, m1, which
> needs a helper function, hf.  I can put hf inside m1, or I can make it
> another method of the class.  The only place hf should ever be invoked
> is from inside m1.
> 
> Is either style preferred?

If either is, it's the first one, not the following one.

> class K(object):
>   def m1(self):
>     def hf():
>       print 'Yo'
>     hf()
>     return

Here you are wasting time executing the "def" statement
every single time you invoke m1.  I'm not sure if that
also means it is compiling it each time (I think not),
but at least it is rebinding the local hf to the function
each time through.

But I would just make hf() a function outside the class.
Since it does not reference anything inside K, it has
nothing inherently to do with K and should be outside,
possibly (eventually) to be moved to another module where
such helper functions reside to make them more maintainable.

-Peter



More information about the Python-list mailing list