"helper function" style question

Paul Morrow pm_mon at yahoo.com
Tue Jul 13 01:20:35 CEST 2004


Your 2nd example makes the most sense from an encapsulation point of 
view.  If hf is only needed by m1, then it shouldn't be visible outside 
of m1.  Otherwise it just pollutes the namespace and makes it harder to 
move m1 to a separate module/class later on down the road.  I use this 
technique all the time.  I like to create functions, not only when I'm 
going to be reusing code, but also simply when it aids the readibility 
of my code.  And although I'm not sure whether the 2nd technique is 
slower than the first (I can imagine that the byte compiler could be 
smart enough not to recompile or rebind hf on each invocation of m1), in 
general, I don't worry about the performance of my code until I've got 
it working correctly.  And then it's usually algorithmic changes that 
offer the big performance gains (not code reorganization).

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?
> 
> Here are two short examples:
> 
> Helper function as method:
> 
> class K(object):
>   def _hf(self):
>     print 'Yo'
>   def m1(self):
>     self._hf()
>     return
> 
> Helper function as "private" function inside m1.
> 
> class K(object):
>   def m1(self):
>     def hf():
>       print 'Yo'
>     hf()
>     return
> 
> Opinions greatly appreciated.
> 
> thanks,
> -robert




More information about the Python-list mailing list