Can a function access its own name?

Peter Hansen peter at engcorp.com
Sat Nov 19 19:19:59 CET 2005


bobueland at yahoo.com wrote:
[edited slightly]
>     def cap():
>         print "the name of this function is " + "???"
>     cap ()

sys._getframe() would help you here:

>>> import sys
>>> sys._getframe()
<frame object at 0x00B496D0>
>>> def f():
...   global x
...   x = sys._getframe()
...
>>> f()
>>> x
<frame object at 0x00B15250>
>>> dir(x)
[..., 'f_builtins', 'f_code', 'f_exc_traceback', 'f_exc_type', ...]
>>> dir(x.f_code)
[...'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames']
>>> x.f_code.co_name
'f'

So your function could be:

 >>> import sys
 >>> def cap():
...   print 'function name is', sys._getframe().f_code.co_name
...
 >>> cap()
function name is cap


-Peter



More information about the Python-list mailing list