0

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()
Daniel Roseman
602k68 gold badges911 silver badges924 bronze badges
asked Jan 27, 2016 at 14:42
1
  • If you read the traceback for the error closely, you'll see that it is ocurring on line the globals()['square_it']() because that is where the function is being called with no arguments — not via the exec() (execution never gets that far). Commented Jan 27, 2016 at 14:59

1 Answer 1

1

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)
answered Jan 27, 2016 at 14:45
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.