Python Practice › Function Programs › Program 13
Run Python code stored in a string
Write a Python function that executes Python code stored in a string.
Output
inside exec: 81 81
Approach
exec()runs code; give it a separate namespace dictionary so it cannot touch your variables.
Solution
def run_code(source): namespace = {} exec(source, namespace) return {k: v for k, v in namespace.items() if not k.startswith("__")} code = """def square(x): return x * xresult = square(9)print("inside exec:", result)"""print(run_code(code)["result"])Output
inside exec: 81 81
Line by line
Lines 2-3
The code runs inside its own dictionary, which then holds the names it created.
Line 4
Python adds __builtins__ to the namespace, so names starting with __ are filtered out.
Watch out
Never pass text from users or files you do not trust to exec(); it can run any code on your machine.
Learn the concept
New to this topic? Read the lesson, then come back.