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