[Tutor] getting the current method name

Jeff Shannon jeff@ccvcorp.com
Thu Apr 17 14:47:01 2003


antonmuhin at rambler.ru wrote:

>AG> how to do the following:
>
>AG> class x:
>AG>         def y():
>AG>                 print "Hi, my name is",<<method-name --> 'y'>>
>
>Try the following:
>
>import sys
>
>def get_callee_name(depth = 0):
>    return sys._getframe(depth + 1).f_code.co_name
>

Needless to say, this is black magic.  It may work, but one should be 
careful using it -- it seems very poor programming practice to make an 
application be dependent on the deep internals of the interpreter it's 
running on.  Among other issues, there's no guarantee that the next 
version of Python (or the current version of Jython) will have the same 
call frame structure.  (Indeed, I believe that Stackless does *not* have 
the same structure, and I wouldn't want to put any bets on this working 
consistently under Stackless...)

My immediate thought would be to ask why the name of the current method 
is needed?  There may be a better solution to the problem that is being 
addressed.

Jeff Shannon
Technician/Programmer
Credit International