Function attributes

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Feb 11 18:36:40 EST 2010


En Thu, 11 Feb 2010 00:25:00 -0300, Terry Reedy <tjreedy at 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.

> 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.

Well, if people really want to shoot themselves in the foot, there's
nothing we can do to avoid that...

-- 
Gabriel Genellina




More information about the Python-list mailing list