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
| Parameter | Description |
|---|---|
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
namespace = {}
exec("def square(n):\n return n * n\nresult = square(7)", namespace)
print(namespace["result"])
Output
49
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
| Version | Change |
|---|---|
| Python 3.0 | Added |
| Python 3.11 | Added the closure parameter. |
| Python 3.13 | globals and locals can be passed as keyword arguments. |
Related
eval()· Evaluate a single Python expression from a string and return its value. Dangerous with untrusted input.compile()· Compile source code into a code object that exec() or eval() can run. Mostly used by tools, REPLs and teaching examples.globals()· Return the dictionary of the current module's global names: variables, functions, classes and imports.locals()· Return a dictionary of the local variables in the current scope. Inside a function it is a snapshot since Python 3.13.