[Tutor] Getting a function name from within itself

Michael P. Reilly arcege@speakeasy.net
Mon, 11 Jun 2001 08:07:43 -0400 (EDT)


Praveen Pathiyil wrote
>         I am posting a question which is not specific to python.=20
>         Is there a way to get the name of a function from within itself =
> at runtime ? Suppose that i have a function f1. At the run time when it =
> encounters some condition ( errors or some condition which i want to let =
> the user know by printing), I want to say that this warning originated =
> from this function f1, without actually hard coding that name in the =
> print statement.
> 
> def f1(self):
>     --- do something --
>     Print "Warning ......", function_name
> 
> Can i get the function name from execution environment or something ?

You can use the traceback object from exceptions to get this information.

>>> def get_caller():
...   import sys
...   try: raise SystemError
...   except SystemError:
...     exc, val, tb = sys.exc_info()
...     # from the traceback, get the second frame back (first is get_caller)
...     caller = tb.tb_frame.f_back
...     # delete the traceback object to free memory
...     del exc, val, tb
...     return caller
...

At this point, you would get a frame for the calling function, which
contain a reference to the code, and subsequently to the name.
>>> def whatsmyline():
...   print 'function name is', get_caller().f_code.co_name
...
>>> whatsmyline()
function name is whatsmyline
>>>

This is the most common (and least obtrusive) idiom.  In Python 2.1,
there is now a new standard library module called "inspect" which does
a lot of this for you.

  -Arcege

-- 
+----------------------------------+-----------------------------------+
| Michael P. Reilly                | arcege@speakeasy.net              |