Getting method name from within the class method

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Wed Oct 18 19:27:49 EDT 2006


On Wed, 18 Oct 2006 13:59:55 -0700, Mitko Haralanov wrote:

> I need to be able to get the name of the currently executed method
> within that method. I know that the method object does have the
> __name__ attribute but I know know how to access it from withing the
> method.

Here is a useful (moderately advanced) technique:

def factory(arg):
    def foo(x=arg):
        print "My name is", foo.__name__
        print "My result is", x + 1
    return foo

class spam:
    pass

for i in range(10):
    name = "method_%d" % i
    f = factory(i)
    f.__name__ = name
    setattr(spam, name, staticmethod(f))


But:

>>> spam.method_0(1)
My name is method_0
My result is 2
>>> spam.method_7(9.4)
My name is method_7
My result is 10.4


-- 
Steven.




More information about the Python-list mailing list