On 2/10/2010 9:36 AM, Steven D'Aprano wrote:
On Wed, 10 Feb 2010 05:59:41 -0800, Muhammad Alkarouri wrote:

Hi everyone,

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?

Not built-in.


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.

I completely agree with you. It is a wart that functions are only able to
refer to themselves by name, because if the name changes, things break.
Consider:

old_f = f  # save the old version of the function

def f(x):
     return old_f(x+1)  # make a new function and call it f

This won't work correctly, because old_f still tries to refer to itself
under the name "f", and things break very quickly.

They didn't break immediately for me -- what am I missing?:

#-------------------
def f(): return "old func"
g = f
print "name attr of f:", f.__name__
print "name attr of g:", g.__name__

def f(): return "new func"
print "name attr of f:", f.__name__
print "name attr of g:", g.__name__

print "*** calling function currently named f:"
print f()
print "*** calling function currently named g:"
print g()
#-------------------

program output (Python 2.6.4):

name attr of f: f
name attr of g: f
name attr of f: f
name attr of g: f
*** calling function currently named f:
new func
*** calling function currently named g:
old func

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

Reply via email to