According to the docs:
The mode argument specifies what kind of code must be compiled; it can be 'exec' if source consists of a sequence of statements, 'eval' if it consists of a single expression, or 'single' if it consists of a single interactive statement
So there's a couple of things here:
- You should use multi-line strings in Python (three
"""
)
- You shouldn't use
"eval"
but "exec"
- The returned object is not executed. You have to explicitly call it once created.
With all that in mind:
expr = """
def something():
print('hi')
return "done"
something()
"""
somevar = compile(expr, "", "exec")
exec(somevar)
This does print "hi"
. However, that code itself doesn't return anything. You run the function something()
which yes: returns "done"
but after running something()
? Where would you return the return?
One option, as explained in this other SO thread would be assigning the return value to what would become a sort of "global" variable:
expr = """
def something():
return "done"
retval = something()
"""
somevar = compile(expr, "", "exec")
exec(somevar)
print(retval)
I can't help but saying that this sort of convoluted coding, that runs code stored in strings is probably a bad idea. It's insecure, hard to track, debug, refactor... So if this is going to be used for something besides learning purposes... Well... I would invite you to try and think if there's another way of achieving what you want.