Accessing func_name from inside a function

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sun Mar 26 18:48:58 EST 2006


James Thiele a écrit :
> I'd like to access the name of a function from inside the function. My
> first idea didn't work.
> 
> 
>>>>def foo():
> 
> ...     print func_name
> ...
> 
>>>>foo()
> 
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<stdin>", line 2, in foo
> NameError: global name 'func_name' is not defined
> 
> My second attempt works but looks ugly.
> 
> 
>>>>def foo():
> 
> ...     import inspect
> ...     print inspect.stack()[0][3]
> ...
> 
>>>>foo()
> 
> foo
> 
> Is there a standard way of getting the name of a function from inside
> the function?
> 

You've already got good answers. Now here's another workaround:

class _FooFunction(object):
   def __call__(self):
     print self.__class__.__name__
foo = _FooFunction()




More information about the Python-list mailing list