How to get a function name as a string?
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.
How to get a function's name as string?
greeting.capitalize
is a function object, and that object has a .__name__
attribute that you can access. But greeting.capitalize()
calls the function object and returns the capitalized version of the greeting
string, and that string object doesn't have a .__name__
attribute. (But even if it did have a .__name__
, it'd be the name of the string, not the name of the function used to create the string). And you can't do str.capitalize()
because when you call the "raw" str.capitalize
function you need to pass it a string argument that it can capitalize.
So you need to do
print str.capitalize.__name__
or
print greeting.capitalize.__name__
Get called function name as string
You need a C compiler that follows the C99 standard or later. There is a pre-defined identifier called __func__
which does what you are asking for.
void func (void)
{
printf("%s", __func__);
}
Edit:
As a curious reference, the C standard 6.4.2.2 dictates that the above is exactly the same as if you would have explicitly written:
void func (void)
{
static const char f [] = "func"; // where func is the function's name
printf("%s", f);
}
Edit 2:
So for getting the name through a function pointer, you could construct something like this:
const char* func (bool whoami, ...)
{
const char* result;
if(whoami)
{
result = __func__;
}
else
{
do_work();
result = NULL;
}
return result;
}
int main()
{
typedef const char*(*func_t)(bool x, ...);
func_t function [N] = ...; // array of func pointers
for(int i=0; i<N; i++)
{
printf("%s", function[i](true, ...);
}
}
How to execute a JavaScript function when I have its name as a string
Don't use eval
unless you absolutely, positively have no other choice.
As has been mentioned, using something like this would be the best way to do it:
window["functionName"](arguments);
That, however, will not work with a namespace'd function:
window["My.Namespace.functionName"](arguments); // fail
This is how you would do that:
window["My"]["Namespace"]["functionName"](arguments); // succeeds
In order to make that easier and provide some flexibility, here is a convenience function:
function executeFunctionByName(functionName, context /*, args */) {
var args = Array.prototype.slice.call(arguments, 2);
var namespaces = functionName.split(".");
var func = namespaces.pop();
for(var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(context, args);
}
You would call it like so:
executeFunctionByName("My.Namespace.functionName", window, arguments);
Note, you can pass in whatever context you want, so this would do the same as above:
executeFunctionByName("Namespace.functionName", My, arguments);
function name as a string
If you have a finite set of functions which you would like to be able to call I would recommend building a Map which maps Strings to instances of Runnable (or similar functional interfaces). Your useFunction method may then look up the function implementation in the Map and call it if it exists.
Example:
public class SomeClass {
private final Map<String, Runnable> methods = new HashMap<>();
{
methods.put("helloworld", () -> {
System.out.println("Hello World!");
});
methods.put("test", () -> {
System.out.println("test!");
});
methods.put("doStuff", () -> {
System.out.println("doStuff!");
});
}
public void perform(String code) {
methods.getOrDefault(code,
() -> {
System.err.println("No such Method: "+code);
})
.run();
}
}
If you want to call arbitrary methods you should probably use Reflection as stated by others.
Get function name as a string in python
That's simple.
print func.__name__
EDIT: But you must be careful:
>>> def func():
... pass
...
>>> new_func = func
>>> print func.__name__
func
>>> print new_func.__name__
func
Get function name to string
Sure, simply look into __name__
:
>>> def foo(): pass
...
>>> foo.__name__
'foo'
I have a string whose content is a function name, how to refer to the corresponding function in Python?
Since you are taking user input, the safest way is to define exactly what is valid input:
dispatcher={'add':add}
w='add'
try:
function=dispatcher[w]
except KeyError:
raise ValueError('invalid input')
If you want to evaluate strings like 'add(3,4)'
, you could use safe eval:
eval('add(3,4)',{'__builtins__':None},dispatcher)
eval
in general could be dangerous when applied to user input. The above is safer since __builtins__
is disabled and locals
is restricted to dispatcher
. Someone cleverer than I might be able to still cause trouble, but I couldn't tell you how to do it.
WARNING: Even eval(..., {'__builtins__':None}, dispatcher)
is unsafe to be applied to user input. A malicious user could run arbitrary functions on your machine if given the opportunity to have his string evaluated by eval
.
Related Topics
Total Memory Used by Python Process
How to Read a (Static) File from Inside a Python Package
Get Mouse Deltas Using Python! (In Linux)
Multiple Instances of Python Running Simultaneously Limited to 35
How to Convert .Pcm Files to .Wav Files (Scripting)
How Does One Set Specific Vim-Bindings in Ipython 5.0.0
How to Default Python3.8 on My MAC Using Homebrew
How to Find Out the Date of the Last Saturday in Linux Shell Script or Python
How to Downgrade My Version of Python from 3.7.5 to 3.6.5 on Ubuntu
Auto Executable Python File Without Opening from Terminal
Pandas Column of Lists, Create a Row For Each List Element
How to Get Hard Disk Serial Number Using Python
Default Buffer Size for a File on Linux
Better Way to Script Usb Device Mount in Linux
Trying to Import Pypyodbc Module Gives Error 'Odbc Library Is Not Found. Is Ld_Library_Path Set'