In Python, how do I get a function name as a string, without calling the function?
def my_function():
pass
print get_function_name_as_string(my_function) # my_function is not in quotes
should output "my_function"
.
Is such function available in Python? If not, any ideas on how to implement get_function_name_as_string
, in Python?
You could also use
As an extension of @Demyn's answer, I created some utility functions which print the current function's name and current function's arguments:
sys._getframe() is not guaranteed to be available in all implementations of Python (see ref) ,you can use the traceback module to do the same thing, eg.
A call to stack[-1] will return the current process details.
If you're interested in class methods too, Python 3.3+ has
__qualname__
in addition to__name__
.This function will return the caller's function name.
It is like Albert Vonpupp's answer with a friendly wrapper.
You just want to get the name of the function here is a simple code for that. let say you have these functions defined
the output will be function1
Now let say you have these functions in a list
to get the name of the functions
the output will be
function1
function2
function3