Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Python · Function

exec

exec dynamically executes Python statements from a string or code object. Explicit namespace mappings let you control where names are resolved and stored.

How it works

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.

Syntax

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

Parameters

NameTypeDescription
sourcestr | codePython source text or a compiled code object to execute.
globalsdict | NoneGlobal namespace dictionary for execution.
localsmapping | NoneLocal namespace mapping for execution.
closuretuple | NoneTuple of cell objects supplying free-variable bindings for a code object.

Returns

None

Key points

  • Use exec when a program must run Python statements generated or selected at runtime.
  • The source may be text or a precompiled code object.
  • String input is parsed as a complete statement suite before execution.
  • A code object bypasses string parsing at the point of the exec call.
  • exec performs an action and does not produce an expression result.

Common mistakes

  • Never pass untrusted text to exec: it can execute arbitrary Python code.
  • Code executed by exec cannot use nonlocal, yield, or return unless those statements are inside function definitions.

Example: Execute compiled statements

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.

When to use it

Controlled code generation

A tool generates trusted Python statements from structured configuration and must run them.

Repeated execution of compiled code

A system precompiles frequently executed statement suites and runs the resulting code objects.

Separate execution namespace

A sandbox-like experiment needs results stored in a dedicated namespace dictionary.

Interview questions

QWhat does exec accept, and what does it return?

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.

QHow do globals and locals affect exec?

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.

QWhat is the purpose of closure?

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()

Source: Built-in Functions. Checked 2026-10-16.