Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a function name as a string?

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?

like image 977
X10 Avatar asked Oct 30 '08 19:10

X10


People also ask

How do you use a function name as a string?

You just need convert your string to a pointer by window[<method name>] . example: var function_name = "string"; function_name = window[function_name]; and now you can use it like a pointer.

How do you define a function called as name?

Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature. Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument.

Can we use a function name as a variable name?

The best suggestion is to discontinue the use of function names as variable names completely. However, in certain applications in which this is not possible, place the relevant code in a separate script and then invoke the script from the function.


1 Answers

my_function.__name__ 

Using __name__ is the preferred method as it applies uniformly. Unlike func_name, it works on built-in functions as well:

>>> import time >>> time.time.func_name Traceback (most recent call last):   File "<stdin>", line 1, in ? AttributeError: 'builtin_function_or_method' object has no attribute 'func_name' >>> time.time.__name__  'time' 

Also the double underscores indicate to the reader this is a special attribute. As a bonus, classes and modules have a __name__ attribute too, so you only have remember one special name.

like image 107
user28409 Avatar answered Oct 01 '22 06:10

user28409