Eval function with parameters

时间:2016-07-11 20:47:27

标签: python eval

I have three functions:

def function_1(arg_1, arg_1, arg_1, arg_1):
    return sol_1
def function_2(arg_1, arg_2, arg_3, arg_4):
    return sol_2
def function_3(arg_1, arg_2, arg_3, arg_4):
    return sol_3

And I would like to call them with a string:

myString = 'function_2'
eval(myString)

But I couldn't pass the arguments to the eval function to be passed to the custom defined function_2, as they are not homogeneous (np.array, float, float, int).

3 个答案:

答案 0 :(得分:4)

To call a function from a variable containing the name of the function, you can make use of the locals and globals function. Basically, you treat the output of locals() as a dictionary of your locally declared functions and then call the return value as normal using parentheses with comma-separated arguments.

(Helpful link: SO: Calling a function from a string)

Example:

def function_1 (a1, a2):
    print 'func1: ', a1, a2
def function_2 (a1, a2):
    print 'func2: ', a1, a2

f1 = 'function_1'
f2 = 'function_2'

locals()[f1](2, 3)
# func1: 23

locals()[f2]('foo', 'blah')
# func2: fooblah


You generally don't want to use the eval function for various reasons -- one of which being security. For example: if part of what you're passing to eval comes from user input, can you be sure that they aren't giving you dangerous values or doing unexpected things? Below are some links that talk about the pitfalls of eval:

Eval is really dangerous

SO: Why should exec and eval be avoided?

SO: Is using eval a bad practice?

答案 1 :(得分:3)

Thak you Tim,

Everything had to be in string format, that worked.

eval(myString + '(arg_1, arg_2, arg_3, arg_4)')

答案 2 :(得分:1)

您可以像这样将参数传递给eval函数:

def start(a, b, c):
    pass

func = "start" 
eval(func)(arg1, arg2, arg3)