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

exec, function, python, return

Solution

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.

Problem

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?

Original source

Related problems