Python exec() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
Built-in

Definition

In Python, exec(code) runs a string of Python statements: assignments, loops, function and class definitions, imports, anything a normal file can contain. Unlike eval(), it always returns None; results are read from the namespace the code ran in.

Pass a dictionary as globals (and optionally another as locals) to keep the executed code's variables separate from your own. Inside a function, exec() cannot change the function's local variables.

exec() is a built-in function: it lives in the builtins module, so it is always available without an import.

Syntax

Pass the code and, ideally, a namespace dict.

python
exec(code)
exec(code, globals_dict)
exec(code, globals_dict, locals_dict)
CallWhat it does
exec("x = 1", ns)Stores x in the dict ns.
exec(src, ns); ns["f"]Defines and retrieves a function.
exec(...)Always returns None.
exec(code_obj, ns)Runs a code object from compile().

For configuration, prefer real data formats (json, INI via configparser) or ast.literal_eval() over executing Python files.

Library declarations
python
exec(source, /, globals=None, locals=None, *, closure=None)
# closure was added in Python 3.11

Parameters

ParameterDescription
sourceRequired. A string of statements or a code object.
globalsOptional. Dict used as the global namespace; __builtins__ is added if missing.
localsOptional. Mapping for local names; defaults to globals.

Return Value

Return ValueDescription
NoneAlways None; read results from the namespace.

Python Examples

Example 1 — Run a Loop and Read the Result

Execute several statements in a fresh namespace and look at what exec() returns.

python
code = """
total = 0
for n in range(1, 5):
    total += n
"""
namespace = {}
result = exec(code, namespace)
print(result)
print(namespace["total"])

How It Works

  1. Statements allowed. Assignments and a for loop run exactly as in a file.
  2. Returns None. exec() does not hand back a value, even though the code computed one.
  3. Results live in the namespace. total was stored in the namespace dict: 1 + 2 + 3 + 4.
  4. Isolation. Your own variables are untouched because the code used its own dict.

Example 2 — Create a Function from Source Text

Define a function inside exec() and pull it out of the namespace.

python
source = "def greet(name):\n    return 'Hello, ' + name\n"
scope = {}
exec(source, scope)

greet = scope["greet"]
print(greet("Ana"))
print(sorted(k for k in scope if not k.startswith("__")))

How It Works

  1. Escapes in the string. \n and four spaces make a valid two-line function.
  2. Retrieve by name. The new function is stored under the key "greet".
  3. A real function. Once retrieved, it is called like any other function.
  4. Hidden extra key. Python adds __builtins__ to the dict, which the filter skips.

Example 3 — Separate Namespaces and Function Locals

Collect settings into a locals dict, then see that exec() cannot change a function's variable.

python
settings_text = """
debug = True
level = 2 * 3
"""
config = {}
exec(settings_text, {"__builtins__": {}}, config)
print(config)


def demo():
    value = 1
    exec("value = 99")
    return value


print(demo())

How It Works

  1. Separate locals. Assignments go into config, the third argument.
  2. Only trusted text. The empty __builtins__ limits accidents, not attacks.
  3. Function locals are protected. Inside demo(), exec() writes to a temporary dict, so value stays 1.
  4. Return values explicitly. Pass a dict and read results from it instead of relying on side effects.

Frequently Asked Questions

It runs a string or code object containing Python statements, such as assignments, loops, and definitions.
Always None. Read results from the globals or locals dict you passed in.
No, not with untrusted input. It can run any code. Use data formats like JSON or ast.literal_eval() for input.
Inside a function, exec() works on a temporary dict of the locals. Pass a dict and read from it instead.
exec() runs statements and returns None. eval() evaluates one expression and returns its value.

Next: filter()

Keep only the items that pass a test, lazily.

filter() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful