"Gabriel Genellina" <gagsl-...@yahoo.com.ar> writes: > En Thu, 11 Feb 2010 00:25:00 -0300, Terry Reedy <tjre...@udel.edu> > escribió: >> On 2/10/2010 4:49 PM, Gabriel Genellina wrote: >> >>> I've written a decorator for "injecting" a __function__ name into the >>> function namespace, but I can't find it anywhere. I think I implemented >>> it by adding a fake additional argument and replacing LOAD_GLOBAL with >>> LOAD_NAME in the bytecode. >> >> The decorator only needs to replace the defaults args tuple. >> It does not even need to know the parameter name, >> just that it is the only (or last) with a default . >> >> def f(n, me=None): >> if n > 0: return n*me(n-1) >> elif n==0: return 1 >> >> f.__defaults__ = (f,) # 3.1 >> print(f(5)) > > This is simple to implement, but requires changing the function > definition. My goal was to keep the original code unchanged, that is, > leave it as: > > def f(n): > if n > 0: return n*f(n-1) > elif n==0: return 1 > > (like a normal, recursive function), and make the 'f' inside the function > body "magically" refer to the function itself.
I posted an example of a decorator that does just this in this thread a couple of days ago: http://mail.python.org/pipermail/python-list/2010-February/1235742.html It doesn't require any bytecode hacking, although it requires breaking apart the function object and making a new one from the bits. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list