Can a function access its own name?

Diez B. Roggisch deets at nospam.web.de
Sat Nov 19 19:09:18 CET 2005


bobueland at yahoo.com wrote:
> Look at the code below:
> 
>     # mystringfunctions.py
> 
>     def cap(s):
>         print s
>         print "the name of this function is " + "???"
> 
>     cap ("hello")
> 
> 
> Running the code above gives the following output
> 
>     >>>
>     hello
>     the name of this function is ???
>     >>>
> 
> I would like the output to be
> 
>     >>>
>     hello
>     the name of this function is cap
>     >>> 
> 
> Is that possible ?

Yes, use the moduloe inspect to access the current stack frame:

def handle_stackframe_without_leak():
     frame = inspect.currentframe()
     try:
         print inspect.getframeinfo(frame)[2]
     finally:
         del frame



Diez



More information about the Python-list mailing list