Run Python code stored in a string

MediumFunction Programs · 13 of 39

Write a Python function that executes Python code stored in a string.

Advertisement
Output
inside exec: 81
81

Approach

  1. 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"])
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.

More function programs

← All 39 Function Programs

Leave a Comment