[Tutor] getting the current method name
Magnus Lyckå
magnus@thinkware.se
Thu Apr 17 18:59:08 2003
At Thu, 17 Apr 2003 09:11:02 +0200, Adam Groszer wrote:
>how to do the following:
>
>class x:
> def y():
> print "Hi, my name is",<<method-name --> 'y'>>
>
>z=x()
>z.y()
>should print
>"Hi, my name is y"
>
>Of course, resolving "<<method-name --> 'y'>>" should not be done with
>simply 'y' :-)
Did that! See
http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/systemspecifyer/src/matrix.py?rev=1.16&content-type=text/vnd.viewcvs-markup
Python is certainly capable of introspection.
This function does the trick!:
>>> import sys
>>> def _fn():
... return sys._getframe(1).f_code.co_name
...
>>> class X:
... def y(self):
... print _fn()
...
>>> x = X()
>>> x.y()
y
Another option is to write:
>>> class X:
... def y(self):
... print sys._getframe(0).f_code.co_name
...
>>> x = X()
>>> x.y()
y
Notice 0 instead of one. Now we want the top-most (or
is it bottom-most) frame.
I prefer a separate (well commented?) function for
such magic though...
The docs say about sys._getframe that "This function
should be used for internal and specialized purposes only."
What does this really imply? That we can't expect the API
to remain?