Function attributes

Terry Reedy tjreedy at
Thu Feb 11 04:25:00 CET 2010

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
# 120

To generalize:

def g(a,b=1,me=None):
     if a: return me(0)
     else: return 41+b

g.__defaults__ = g.__defaults__[:len(g.__defaults__)-1] + (g,)

Of course, user could still screw up recursion by providing another 
value for 'me'. This strikes me as about a likely (low) as a user 
screwing up recursion in a library module function by rebinding the name 
in the imported module.

Terry Jan Reedy

More information about the Python-list mailing list