En Wed, 10 Feb 2010 10:59:41 -0300, Muhammad Alkarouri <malkaro...@gmail.com> 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)
2

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

--
Gabriel Genellina

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to