Python 3 reference · Built-in Functions

Python exec() Function

Execute Python statements from a string or code object. Returns None; like eval(), never use it on untrusted input.

Python 3 Since 3.0

Syntax

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

Parameters

ParameterDescription
source A string of statements or a code object.
globals optional The global namespace to run in.
locals optional The local namespace.
closure optional Cells for the free variables of a code object.

Return value

None. Results stay in the namespaces you pass.

Examples

Run statements in a separate namespaceTry it yourself
namespace = {}
exec("def square(n):\n    return n * n\nresult = square(7)", namespace)
print(namespace["result"])

Output

49
Run a block of codeTry it yourself
code = '''
for i in range(3):
    print("line", i)
'''
exec(code)

Output

line 0
line 1
line 2

Security

Like eval(), exec() can do anything your program can. Use it for tools you control (code generators, teaching sandboxes), never for user input.

Version history

VersionChange
Python 3.0Added
Python 3.11Added the closure parameter.
Python 3.13globals and locals can be passed as keyword arguments.