Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the return value when using Python exec on the code object of a function?

For testing purposes I want to directly execute a function defined inside of another function.

I can get to the code object of the child function, through the code (func_code) of the parent function, but when I exec it, i get no return value.

Is there a way to get the return value from the exec'ed code?

like image 241
user2433423 Avatar asked May 28 '14 17:05

user2433423


People also ask

How do you return a value from exec in Python?

What does exec return in Python? Python exec() does not return a value; instead, it returns None. A string is parsed as Python statements, which are then executed and checked for any syntax errors.

What is exec () in Python?

exec() function is used for the dynamic execution of Python program which can either be a string or object code. If it is a string, the string is parsed as a suite of Python statements which is then executed unless a syntax error occurs and if it is an object code, it is simply executed.


3 Answers

Yes, you need to have the assignment within the exec statement:

>>> def foo():
...     return 5
...
>>> exec("a = foo()")
>>> a
5

This probably isn't relevant for your case since its being used in controlled testing, but be careful with using exec with user defined input.

like image 60
wnnmaw Avatar answered Oct 05 '22 20:10

wnnmaw


A few years later, but the following snippet helped me:

the_code = '''
a = 1
b = 2
return_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.

like image 28
Mr. B. Avatar answered Oct 05 '22 21:10

Mr. B.


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.

like image 10
devsnd Avatar answered Oct 05 '22 20:10

devsnd