Possible Duplicate:
How to get the function name as string in Python?
I know that I can do that :
def func_name():
print func_name.__name__
which will return the name of the function as 'my_func'.
But as I am into the function, is there a way to directly call it generically ? Something like :
def func_name():
print self.__name__
In which Python would understand that I want the upper part of my code hierarchy?
You can get a function's name as a string by using the special __name__ variable.
It's this method object that has the __func__ attribute, which is just a reference to the wrapped function. By accessing the underlying function instead of calling the method, you remove the typecheck, and you can pass in anything you want as the first argument.
Method 1: Get Function Name in Python using function. func_name. By using a simple function property function, func_name, one can get the name of the function and hence can be quite handy for the Testing purpose and also for documentation at times. The drawback is that this works just for Python2.
Python does not support function overloading. When we define multiple functions with the same name, the later one always overrides the prior and thus, in the namespace, there will always be a single entry against each function name.
Not generically, but you can leverage inspect
import inspect
def callee():
return inspect.getouterframes(inspect.currentframe())[1][1:4][2]
def my_func():
print callee() // string my_func
Source http://code.activestate.com/recipes/576925-caller-and-callee/
AFAIK, there isn't. Besides, even your first method is not totally reliable, since a function object can have multiple names:
In [8]: def f(): pass
...:
In [9]: g = f
In [10]: f.__name__
Out[10]: 'f'
In [11]: g.__name__
Out[11]: 'f'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With