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
| Name | Type | Description |
|---|---|---|
| source | str | code object | Trusted statements or compiled object; positional only. |
| globals | dict | None | Global namespace, default caller globals. |
| locals | mapping | None | Local namespace; defaults to globals when only globals is supplied. |
| closure | tuple of cell objects | None | Keyword-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)