Built-in Functions and Types

exec()

Execute trusted Python statements or a code object. Unlike eval(), exec() always returns None; use a supplied namespace to examine resulting bindings. If separate global and local mappings are used, code behaves with class-body-like namespace separation. A closure tuple applies to code objects with matching free variables. Never run untrusted source; custom namespace dictionaries do not create a safe sandbox.

Formal Syntax & Structure

python syntaxpython
exec(source, /, globals=None, locals=None, *, closure=None)

Parameters & Attributes

NameTypeDescription
sourcestr | code objectTrusted statements or compiled object; positional only.
globalsdict | NoneGlobal namespace, default caller globals.
localsmapping | NoneLocal namespace; defaults to globals when only globals is supplied.
closuretuple of cell objects | NoneKeyword-only; applicable to code objects with free variables; length must match.

Return Value

None

The execution can change bindings or have side effects but returns None.

Working Example

Example Snippetpython
# Fixed trusted statements for a local demonstration.namespace = {"quantity": 3, "price": 8}result = exec("total = quantity * price", globals=namespace)print(namespace["total"])print(result)
Python Reference