Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

exec()

Executes a suite of trusted Python statements in a chosen namespace.

Version: Python 3.14; repository image, production runtime not attested

Syntax

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

Executes a suite of trusted Python statements in a chosen namespace.

With a single namespace dictionary, ordinary top-level assignments become bindings there. The return value of statement execution is None.

Runs a trusted suite or a compiled code object. With one namespace dictionary that dictionary supplies both globals and locals. The assignment inserts total=15 into scope, while the return is None. A separate locals mapping receives ordinary top-level assignments instead. A missing __builtins__ key is inserted into globals. A function defined in the suite looks up global names in globals and raises NameError for a name available only in the separate locals. The optional closure applies only to suitable code objects with free variables.

scope = {"rate": 3}
assert exec("total = rate * 5", scope) is None and scope["total"] == 15
local = {}
exec("x = rate", scope, local)
assert local["x"] == 3 and "x" not in scope
assert isinstance(scope["__builtins__"], dict)
exec("def f(): return x", scope, local)
try:
    local["f"]()
except NameError:
    pass
else:
    raise AssertionError

Examples

scope = {"rate": 3}
result = exec("total = rate * 5", scope)
print(result)
print(scope["total"])

Result

None
15

Runs a trusted suite or a compiled code object. With one namespace dictionary that dictionary supplies both globals and locals. The assignment inserts total=15 into scope, while the return is None. A separate locals mapping receives ordinary top-level assignments instead. A missing `__builtins__` key is inserted into globals. A function defined in the suite looks up global names in globals and raises NameError for a name available only in the separate locals. The optional closure applies only to suitable code objects with free variables.

Sources