4

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

martineau
  • 119,623
  • 25
  • 170
  • 301
fizcris
  • 427
  • 2
  • 6
  • 13
  • 1
    well make them as variables `x=[1,2,3]; y=1.2; z = 1.3; q = 5` and then pass it as `'function_2(x,y,z,q)` – Tim Jul 11 '16 at 20:48
  • They are already in this format, the issue is how to pass them to the 'function_2(x,y,z,q) form that you have said using the eval function. – fizcris Jul 11 '16 at 20:55
  • 1
    Does that not work? `eval('function_2(x,y,z,q)')` – Tim Jul 11 '16 at 20:55

3 Answers3

8

Thak you Tim,

Everything had to be in string format, that worked.

eval(myString + '(arg_1, arg_2, arg_3, arg_4)')
fizcris
  • 427
  • 2
  • 6
  • 13
6

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?

Community
  • 1
  • 1
xgord
  • 4,606
  • 6
  • 30
  • 51
  • 1
    Note that using `locals()` like that will only work if the named function itself is local (as it is in your example). – martineau Oct 10 '16 at 16:11
3

you can pass the arguments to the eval function just like this:

def start(a, b, c):
    pass

func = "start" 
eval(func)(arg1, arg2, arg3)
mujad
  • 643
  • 7
  • 15
  • 1
    Hi, answers with no explaination at all are considered as low quality, though are not forbidden. Please add at least one or two sentences like why you solution works or how you got there. In general high quality answers are also more likely to get rewarded. – mischva11 Feb 26 '20 at 13:36