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

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.

Leave a Comment