Controlled code generation
A tool generates trusted Python statements from structured configuration and must run them.
Python · Function
exec dynamically executes Python statements from a string or code object. Explicit namespace mappings let you control where names are resolved and stored.
exec runs Python statements supplied as a string or code object. Optional globals and locals mappings control the execution namespace; when omitted, execution uses the current scope. The closure argument supplies cells for free variables when executing a code object that contains them.
exec(source, /, globals=None, locals=None, *, closure=None)| Name | Type | Description |
|---|---|---|
source | str | code | Python source text or a compiled code object to execute. |
globals | dict | None | Global namespace dictionary for execution. |
locals | mapping | None | Local namespace mapping for execution. |
closure | tuple | None | Tuple of cell objects supplying free-variable bindings for a code object. |
None
code = compile("answer = 6 * 7", "<string>", "exec")
namespace = {}
result = exec(code, namespace)
print(namespace["answer"])
print(result)Compiles a statement suite, executes it in an explicit namespace, and shows that exec returns None.
A tool generates trusted Python statements from structured configuration and must run them.
A system precompiles frequently executed statement suites and runs the resulting code objects.
A sandbox-like experiment needs results stored in a dedicated namespace dictionary.
exec accepts a string or code object. A string is parsed as a suite of Python statements, while a code object is executed directly; the function returns None.
Follow-up: How can execution be isolated from the caller’s namespace? Pass explicit globals and locals mappings, then read results from those mappings.
globals and locals are keyword-only optional mappings in the current signature. globals defines the global namespace, while locals defines the local namespace; if locals is omitted, globals is used for both.
Follow-up: What namespace requirement applies to globals? It must be a dict, not a dict subclass.
closure is an optional tuple of cell objects used when executing a code object that has free variables. Its length must match the number of free variables in the code object.
Follow-up: When is closure relevant? It matters for dynamically executing compiled code that references free variables.
compile()eval()globals()locals()