how to get name of function from within function?

Steven Bethard steven.bethard at gmail.com
Fri Jun 3 18:12:01 EDT 2005


Christopher J. Bottaro wrote:
> I want to get the name of the function from within the function.  Something
> like:
> 
> def myFunc():
>   print __myname__
> 
>>>> myFunc()
> 'myFunc'

There's not a really good way to do this.  Can you give some more detail 
on what exactly you're trying to do here?  Depending on a function's 
name within that function is probably a bad idea...

You *can* do this using a sys._getframe() hack:

py> def my_func():
...     print sys._getframe().f_code.co_name
...
py> my_func()
my_func

But that depends on a non-public API.  Also, what do you want to happen 
if someone binds another name to your function?  The code above will 
print the original name even if it's different from the new name(s):

py> g = my_func
py> del my_func
py> g()
my_func
py> my_func()
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
NameError: name 'my_func' is not defined

> Also, is there a way to turn normal positional args into a tuple without
> using *?  Like this:
> 
> def f(a, b, c):
>   print get_args_as_tuple()
> 
>>>>f(1, 2, 3)
> 
> (1, 2, 3)

Um...

py> def f(a, b, c):
...     print (a, b, c)
...
py> f(1, 2, 3)
(1, 2, 3)

?

STeVe



More information about the Python-list mailing list