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, ...);
}
}
Calling a function of a module by using its name (a string)
Given a module foo
with method bar
:
import foo
bar = getattr(foo, 'bar')
result = bar()
getattr
can similarly be used on class instance bound methods, module-level methods, class methods... the list goes on.
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
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);
Determine function name from within that function (without using traceback)
Python doesn't have a feature to access the function or its name within the function itself. It has been proposed but rejected. If you don't want to play with the stack yourself, you should either use "bar"
or bar.__name__
depending on context.
The given rejection notice is:
This PEP is rejected. It is not clear how it should be implemented or what the precise semantics should be in edge cases, and there aren't enough important use cases given. response has been lukewarm at best.
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
Format Numbers to Significant Figures Nicely in R
Possible to Create Latex Multicolumns in Xtable
How to Change Positions of X and Y Axis in Ggplot2
Knitr Wont Compile PDF: "Error in Tools::File_Path_As_Absolute(Output_File)"
Crop for Spatialpolygonsdataframe
Print Pretty Data.Frames/Tables to Console
How to Group by Two Columns in R
Output Error/Warning Log (Txt File) When Running R Script Under Command Line
Issue with Ggplot2, Geom_Bar, and Position="Dodge": Stacked Has Correct Y Values, Dodged Does Not
Add Image in Title Page of Rmarkdown PDF
Avoiding the Infamous "Eval(Parse())" Construct
An Na in Subsetting a Data.Frame Does Something Unexpected
Add Values to a Reactive Table in Shiny
Creating (And Accessing) a Sparse Matrix with Na Default Entries
Merge Nearest Date, and Related Variables from a Another Dataframe by Group