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 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.
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.
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.
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.
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