adding new functionality to a function non-intrusively!

Terry Reedy tjreedy at udel.edu
Wed Feb 16 20:52:13 EST 2005


"peter" <Peter.Vandersteegen at gmail.com> wrote in message 
news:1108591505.670637.258590 at c13g2000cwb.googlegroups.com...
> indeed it does,  so basically everything works except my original
> solution:
>
> def myfunction(a,b):
>    return a+b
>
> def _myfunction(a,b):
>       return myfunction(a,b)
> myfunction = _myfunction
>
> oh well, it was enough to puzzle my tiny brain....

For newbies reading this, the point is that names within functions, 
including global function names, are looked up when and each time the 
function is *called*, not when it is defined.  So even though _myfunction 
does not *look* recursive, since it appears to call some other function, 
the name rebinding after *makes* it recursive.  Conversely, we can make a 
recursive-looking function not recursive.
>>> def f(): return f() # sure looks infinitely recursive
...
>>> g = f
>>> f = int # arbitrary choice of function that will accept no args
>>> f()
0
>>> g()
0

Moral: be careful about rebinding function names, and the order in which 
you do so.

Terry J. Reedy






More information about the Python-list mailing list