Python 3.0+Built-in functionsterm
exec
execution
Executes dynamically created Python code: a string or a code object. Modifies the namespace it is given.
Syntax
exec(object[, globals[, locals]])
The classic trap is calling exec('x = 1') inside a function and expecting a local x to appear: locals are laid out at compile time, so a name created by exec is invisible to the function's own code (at module level, where the namespace is a real dict, it does work). The reliable pattern is to give exec its own dict and read the result out of it: exec(src, g), then g['x']. exec always returns None — it cannot hand you the value of an expression; that is what eval is for.
Examples
exec('x = 1 + 2')
# print(x) # x есть в локальном пространстве?
g = {}
exec('y = 42', g)
print(g['y']) # → 42
exec('for i in range(3): print(i)') # → 0 1 2
def make_func(name):
exec(f'def {name}(): return "{name}"', globals())
make_func('hello')
print(hello()) # → hello
See also
Open in the full glossarydocs.python.orgReport an inaccuracy