Run Python code stored in a string
MediumFunction Programs · 13 of 39
Write a Python function that executes Python code stored in a string.
Approach
exec() runs code; give it a separate namespace dictionary so it cannot touch your variables.
Solution
Python
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"])
Line by line
Lines 2-3The code runs inside its own dictionary, which then holds the names it created.
Line 4Python adds __builtins__ to the namespace, so names starting with __ are filtered out.
Watch outNever 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.
More function programs
← All 39 Function Programs