Name of a method of an instance

Christian Tismer tismer at tismer.com
Wed Mar 28 06:29:12 EST 2001


Richard Philips wrote:
> 
> A question on introspection:
> 
> class Log:
> 
>     def __init__(self):
>         self.previous = None
> 
>     def methodA(self):
>         self.previous = "methodA"
> 
>     def methodB(self):
>         self.previous = "methodB"
> 
> myinstance = Log()
> myinstance.methodA()
> myinstance.methodB()
> 
> How can I calculate the name of the method from within the method itself

<module name="funcname.py">
# obtaining the name of a function/method
# Christian Tismer
# March 2001

# the following function might be implemented in the
# sys module, when generators are introduced.
# For now, let's emulate it. The way is quite inefficient
# since it uses an exception, but it works.

import sys

def _getframe(level=0):
    try:
        1/0
    except:
        import sys
        tb = sys.exc_info()[-1]
    frame = tb.tb_frame
    while level >= 0:
        frame = frame.f_back
        level = level - 1
    return frame

sys._getframe = _getframe
del _getframe

# we now assume that we have sys._getframe

def funcname():
    return sys._getframe(1).f_code.co_name

class Log:

    def __init__(self):
        self.previous = None

    def methodA(self):
        self.previous = funcname()

    def methodB(self):
        self.previous = funcname()

myinstance = Log()
myinstance.methodA()
print myinstance.previous
myinstance.methodB()
print myinstance.previous

printout="""
methodA
methodB
"""
# that's all folks
</module>

ciao - chris

-- 
Christian Tismer             :^)   <mailto:tismer at tismer.com>
Mission Impossible 5oftware  :     Have a break! Take a ride on Python's
Kaunstr. 26                  :    *Starship* http://starship.python.net/
14163 Berlin                 :     PGP key -> http://wwwkeys.pgp.net/
PGP Fingerprint       E182 71C7 1A9D 66E9 9D15  D3CC D4D7 93E2 1FAE F6DF
     where do you want to jump today?   http://www.stackless.com/




More information about the Python-list mailing list