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

user2433423 picture user2433423 · May 28, 2014 · Viewed 26.9k times · Source

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?

Answer

wnnmaw picture wnnmaw · May 28, 2014

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.