Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have a string whose content is a function name, how to refer to the corresponding function in Python?

For example, if I have a function called add like

def add(x,y):     return x+y 

and I want the ability to convert a string or an input to direct to that function like

w=raw_input('Please input the function you want to use') 

or

w='add' 

Is there any way to use w to refer to the function add?

like image 481
Bob Avatar asked Oct 10 '11 22:10

Bob


People also ask

How do you call a function by its string name in Python?

Use locals() and globals() to Call a Function From a String in Python. Another way to call a function from a string is by using the built-in functions locals() and globals . These two functions return a Python dictionary that represents the current symbol table of the given source code.

How do you call a function in a string name?

There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.

How do you call a function name?

Define a function named "myFunction", and make it display "Hello World!" in the <p> element. Hint: Use the function keyword to define the function (followed by a name, followed by parentheses). Place the code you want executed by the function, inside curly brackets. Then, call the function.

How do you call a function variable in Python?

To use functions in Python, you write the function name (or the variable that points to the function object) followed by parentheses (to call the function). If that function accepts arguments (as most functions do), then you'll pass the arguments inside the parentheses as you call the function.


2 Answers

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.

like image 162
unutbu Avatar answered Sep 20 '22 17:09

unutbu


One safe way is to map from names to functions. It's safer than using eval.

function_mappings = {         'add': add, }  def select_function():     while True:         try:             return function_mappings[raw_input('Please input the function you want to use')]         except KeyError:             print 'Invalid function, try again.' 
like image 37
Chris Morgan Avatar answered Sep 23 '22 17:09

Chris Morgan