Function attributes

Gabriel Genellina gagsl-py2 at
Wed Feb 10 22:49:40 CET 2010

En Wed, 10 Feb 2010 10:59:41 -0300, Muhammad Alkarouri  
<malkarouri at> escribió:

> What is the simplest way to access the attributes of a function from
> inside it, other than using its explicit name?
> In a function like f below:
> def f(*args):
>     f.args = args
>     print args
> is there any other way?

See this:

>>> def foo(): pass
>>> import sys
>>> sys.getrefcount(foo)

The 2 means that there is a *single* reference to the function - the foo  
name in the global namespace. No other reference exists, there is no  
hidden attribute somewhere that you may use. If you want another way to  
reach the function, you'll have to add it yourself.

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.

> I am guessing the next question will be: should I really care? It just
> feels like there should be a way, but I am not able to verbalise a
> valid one at the moment, sorry.

One reason would be to write truly recursive functions (currently, a  
recursive call involves a name lookup, which could potentially return a  
different function). Another one, to implement some kind of tail call  

Gabriel Genellina

More information about the Python-list mailing list