Returning value from exec()

You can capture side effects from an exec call and as other people have said, you can use eval to get the return value of a statement.

Your example also shows a bare return outside a function, which isn’t valid python syntax. Since exec is meant to run complete codeblocks (or even bootstrap a module by running an entire file), it wouldn’t make much sense to have it support invalid syntax.

Wouldn’t it be easier to just write a function and then eval that? Or just use a function?

What would be the point then in using eval, how would

retVal = eval(‘execFunc()’)

be any improvement over

retVal = execFunc())

My example does have what you describe as ‘a bare return outside a function’ which you state ‘isn’t valid python syntax’; question is why not? As Python has a return statement why does it then preclude it’s use from any piece of Python code as in my example? It would surely be quite simple to allow any piece of code to return a value to say an exec() function.

Deliberately restricting ‘return’ to use only from a function seems preversely pedantic to me. It may not be ‘Pythonic’ but what happened to allowing everyone to behave like adults and make their own decisions upon whether it should be used ot not.

Before complaining like this, I suggest you design your own programming language. It would be an excellent exercise in language design, and you’d learn all sorts of things about what’s good, what’s bad, and (most of all) what’s a compromise between two ideals.

Let’s say you had a module with a bunch of different functions that had compound name like get_item_as_*. You could have a dispatcher called get_item that takes a string to determine which function to call:


def get_item_as(typ, *args, **kwargs):
    try:
        return eval('get_item_as_{typ}(*args, **kwargs)')
    except Exception:
         return None

It’s a bit of a toy example, but there are valid reasons to use string interpolation to dispatch function calls.

Since eval also takes globals and locals, you could shift context during the eval to a private module that contains the called functions so they aren’t available in the namespace of the public function.

Are you saying that it is not as simple as I suggest it is to return a value from ‘return’?

Do you not see that the behaviour at the moment is illogical; exec() is a function and therefore has a return value. However it currently always returns ‘None’ as opposed to any value from a return statement. Why then is it a function? If it is not going to return a useful value would it not make more sense if ‘exec’ were a statement rather than a function?

That is, in fact, exactly what I am saying.

Many functions always return None (another example is print() or list.sort()), many user created functions may also always return None. Are you suggesting this behavior is illogical? If so, why? exec works like the others, None return value but with side effects (e.g. on globals/locals).

I would personally be surprised if return worked in exec because my mental model is exec is similar to running a code string as a file, and not as executing a function body.

That is what exec appears to do.

>>> exec('return 3')
Traceback (most recent call last):
  File "<python-input-0>", line 1, in <module>
    exec('return 3')
    ~~~~^^^^^^^^^^^^
  File "<string>", line 1
SyntaxError: 'return' outside function

The CPython REPL calls C code that executes the input string exex('return 3') as if it were read from a file. For the purpose of printing a possible traceback (as done here), it creates a fake file name, “”, that cannot be the name of an imported file. (This is similar to the non-identifier ‘’ as a fake function name.) The number is incremented for each new input statement. Exec does the same thing with the passed string return 3, but with the fake filename “string”. No index is needed because only one string is executed in one call.

Some languages have separate functions, which return values, and (subroutine/procedure)s, which do not. C uses the same syntax for both. A subroutine has return type ‘void’, meaning ‘no value returned’, and a body with no return statements or only blank return statements. Python, originally and mainly in C, does similarly. Python’s exec is a subroutine function and my guess is that it calls a C subroutine function or a C function that returns 0 for success, other int otherwise.

Because Python does not have a procedure type (like Pascal), or void method, (like Java), one where assigning the return value would be a semantic error.

That would make exec a keyword and, on the whole, keywords are to be minimised in language design, as the syntax errors can be obscure when they are used as variable names.

It WAS a keyword in Python 2, and it became a function in Python 3 with very little fanfare PEP 3100 – Miscellaneous Python 3.0 Plans | peps.python.org because it doesn’t benefit much from being a statement.

Really, I should know that.

I got slightly nerd sniped by this, so here is my solution:

import ast


def exec_function_body(code, globals=None, **kwargs):
    # Parse the user provided code
    code = ast.parse(code, mode="exec")
    # Wrap it in a function definition
    code = ast.FunctionDef(
        name="func",
        args=ast.arguments(args=[
            ast.arg(arg=arg, lineno=1, col_offset=0)
            for arg in kwargs
        ]),
        body=code.body,
        lineno=1,
        col_offset=0,
    )
    # Wrap it in a module
    code = ast.Module(body=[code])
    # Compile this module
    code = compile(code, filename="<string>", mode="exec")
    # Execute the module
    module = {}
    exec(code, globals, module)
    # Run the function
    return module["func"](**kwargs)

You can use it like this:

result = exec_function_body("""
arg2 = arg2[::-1] # reassign to local variable
blah = arg1 + arg2
print("blah is", blah)

if "ora" in blah:
    return blah[::-1] # early return

return "there is no ora"
""", arg1="foo", arg2="bar")
# blah is foorab
print("Got result", result)
# Got result baroof

or even like this:

result = exec_function_body("""
yield "x" + arg1
print("This is actually a proper generator!")
yield "y" + arg2
""", arg1="foo", arg2="bar")
print("Got result", result)
# Got result <generator object func at 0x...>
for x in result:
    print("Item", x)
# Item xfoo
# This is actually a proper generator!
# Item ybar

It’s obviously quite a bit more complicated compared to just assigning the result to a variable and then reading it from locals. But this solution actually creates a proper function (so the local/global variables have proper scoping, you can use keywords like return instead of assigning to a variable and control flow works as expected).

At the same time, this doesn’t rely on any “yucky string manipulation”. The "\n\t" solution is short and simple, but it can give slightly wrong results in some situations. For example, multiline strings inside the “function body” end up having extra indentation, but exec_function_body doesn’t have this problem:

code = """
return \"""
Multiline string
\"""
"""
print("Wrong")
locs = {}
exec("def func():" + code.replace("\n", "\n\t"), {}, locs)
print(locs["func"]())

print("Correct")
print(exec_function_body(code))

prints

Wrong

	Multiline string
	
Correct

Multiline string

Making ‘exec’ a function rather than a keyword allows it to be passed, as in map(exec, codeblocks).

Thanks for that code, Although more complicated it certainly works better than my original solution; I hadn’t noticed that I was creating extra tabs on multi-line string lines.

Although not mentioned in my original question my real-world use is actually using a patched importlib to create the .pyc and execute the code in the first case: then the next time it is run, if the source hasn’t changed, it reads from the .pyc file and executes that already compiled code.

It is going to take me a bit of time to fully understand how your example is working but let me try and post back later.

Edit:
At the moment this is how I am using the importlib patched loader:

-> source_file
-> module_name
print("compiling & running new", pyc_file)
import importlib.util
import importlib.machinery
class PatchedLoader(importlib.machinery.SourceFileLoader):
    def source_to_code(self, data, path, *, _optimize=-1):
        source = data.decode("utf-8")
        return compile(source, path, "exec", dont_inherit=True, optimize=_optimize)
spec = importlib.util.spec_from_file_location(module_name, source_file,
        loader=PatchedLoader(module_name, source_file))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)