user1179317
user1179317

Reputation: 2923

Calling a function using exec

Trying to call a function as a string using exec but it doesn't work. I attached a simple example code below.

I get an error that square_it() is missing 1 required positional argument: 'num.' I know it is missing but I don't know how to have the argument in that globals syntax.

Below is an example:

def square_it(num):

    result = num * num
    return result

def test():

    #code_globals = {}
    globals()['square_it']()
    code_locals = {'testing':0}
    comd_str = "testing = square_it(2)"
    exec(comd_str, globals(), code_locals)
    print(code_locals['testing'])


test()

Upvotes: 0

Views: 56

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600041

The error isn't happening in the exec call; it's happening in the first line, when you call globals. All the rest of the code is irrelevant.

Calling the function there is exactly the same as doing it any other way; you have the calling parentheses, you just need to put your argument in there:

globals()['square_it'](2)

Upvotes: 1

Related Questions