"helper function" style question

Paul Morrow pm_mon at yahoo.com
Tue Jul 13 18:02:35 EDT 2004


Terry Reedy wrote:
> "Paul Morrow" <pm_mon at yahoo.com> wrote in message
> news:ccv6ck$blt$1 at sea.gmane.org...
> 
>>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
> 
> 
>>From years ago comments by those in the know, the body of inner function is
> compiled just once, as for outer functions, and saved in a code object, but
> the function object is recreated each time the def statement is executed.
> Rebinding is necessary; so it either recreating the function object or at
> least patching a cached version .  Consider the following skeleton:
> 
> def outer(a, b):
>   if a:
>     def inner(x, y=b): pass
>   else:
>     def inner(x, y=[b]): pass
>   return inner
> 
> Terry J. Reedy
> 
> 
> 

But if the inner defs were not conditionally compiled (not inside of the 
if stmnt --- as in the example we were considering), the compiler 
*could* detect that and not have to rebind the local variable (inner) 
each time.  In fact, it could even inline the helper function 
(eliminating the function call entirely), thereby speeding things up 
even more.

But even if the Python compiler doesn't do that, I still prefer defining 
things so that they are visible only within the scope where they are 
needed.  That generally makes program maintenance/comprehension easier, 
which translates into saving 'my' time...

Paul





More information about the Python-list mailing list