Reputation: 2923
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
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