How do I get the return value when using Python exec on the code object of a function?
A few years later, but the following snippet helped me:
the_code = '''a = 1b = 2return_me = a + b'''loc = {}exec(the_code, globals(), loc)return_workaround = loc['return_me']print(return_workaround) # 3
exec()
doesn't return anything itself, but you can pass a dict
which has all the local variables stored in it after execution. By accessing it you have a something like a return.
I hope it helps someone.
While this is the ugliest beast ever seen by mankind, this is how you can do it by using a global variable inside your exec call:
def my_exec(code): exec('global i; i = %s' % code) global i return i
This is misusing global variables to get your data across the border.
>>> my_exec('1 + 2')3
Needless to say that you should never allow any user inputs for the input of this function in there, as it poses an extreme security risk.