🌐
GeeksforGeeks
geeksforgeeks.org › python › exec-in-python
exec() in Python - GeeksforGeeks
November 29, 2023 - Dynamic execution in Python allows the execution of specific methods such as sum() and iter() along with built-in methods inside the exec() function, demonstrating the flexibility of dynamic execution in Python. Through this, only the sum, and iter methods along with all the built-in methods can be executed inside exec() function.
🌐
Programiz
programiz.com › python-programming › methods › built-in › exec
Python exec() (With Examples)
The exec() method executes a dynamically created program, which is either a string or a code object.
🌐
DataFlair
data-flair.training › blogs › python-exec-function
Python exec Function - Example and Risk - DataFlair
November 24, 2018 - Learn what the exec function is in Python with syntax and example, Exec vs eval, Risks with Python Exec - problem & Solution
🌐
Python documentation
docs.python.org › 3 › library › functions.html
Built-in Functions — Python 3.14.4 documentation
February 27, 2026 - This function supports dynamic execution of Python code. source must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs).
🌐
Real Python
realpython.com › python-exec
Python's exec(): Execute Dynamically Generated Code – Real Python
November 10, 2022 - Python’s built-in exec() function allows you to execute any piece of Python code. With this function, you can execute dynamically generated code. That’s the code that you read, auto-generate, or obtain during your program’s execution.
🌐
W3Schools
w3schools.com › python › ref_func_exec.asp
Python exec() Function
Python Examples Python Compiler ... Python Interview Q&A Python Bootcamp Python Training ... The exec() function executes the specified Python code....
🌐
Codecademy
codecademy.com › docs › python › built-in functions › exec()
Python | Built-in Functions | exec() | Codecademy
August 24, 2023 - The exec() function executes a code object or string containing Python code.
🌐
AskPython
askpython.com › home › understanding the python exec() method
Understanding the Python exec() Method - AskPython
August 6, 2022 - Basically, the Python exec() method executes the passed set of code in the form of string. It is very useful as it practically supports dynamic execution.
Find elsewhere
🌐
Vultr Docs
docs.vultr.com › python › built-in › exec
Python exec() - Execute Dynamically | Vultr Docs
September 27, 2024 - Execute the code using exec() while defining the variable externally. ... This snippet defines a Python code in the form of a string that calculates the sum of two variables a and b. It then uses exec() to execute this code, passing a dictionary defining these variables.
🌐
TechVidvan
techvidvan.com › tutorials › python-exec-syntax-examples
Python Exec() with Syntax and Examples - TechVidvan
January 9, 2021 - exec() function is used for dynamic execution of Python program which can either be a string or object code. Learn Exec() va Eval() in Python
🌐
Armin Ronacher
lucumr.pocoo.org › 2011 › 2 › 1 › exec-in-python
Be careful with exec and eval in Python | Armin Ronacher's Thoughts and Writings
February 1, 2011 - Wait what. Python compiles? That is correct. CPython and PyPy (the implementations worth caring about currently) are in fact creating a code object from the string you pass to exec or eval before executing it. And that’s just one of the things many people don’t know about the exec statement.
🌐
Python Geeks
pythongeeks.org › python geeks › learn python › python exec() with examples
Python exec() with Examples - Python Geeks
November 1, 2021 - We are going to discuss another built-in function in Python. This is Python exec(), which is a short form for execution. This article will learn this function, its parameters, and also its limitations with examples.
🌐
Real Python
realpython.com › ref › builtin-functions › exec
exec() | Python’s Built-in Functions – Real Python
The built-in exec() function allows for the dynamic execution of Python code, which can be provided as either a string or a compiled code object.
🌐
Toppr
toppr.com › guides › python-guide › references › methods-and-functions › methods › built-in › exec › python-exec
Python exec() function | What is Python exec()? | Why do we use exec()? |
August 18, 2021 - The python exec() function is used for dynamic execution of Python programs that can be either strings or object code, and it takes huge blocks of code, as opposed to the eval() method, which only accepts a single expression.
Top answer
1 of 4
56

There is a big difference between exec in Python 2 and exec() in Python 3. You are treating exec as a function, but it really is a statement in Python 2.

Because of this difference, you cannot change local variables in function scope in Python 3 using exec, even though it was possible in Python 2. Not even previously declared variables.

locals() only reflects local variables in one direction. The following never worked in either 2 or 3:

def foo():
    a = 'spam'
    locals()['a'] = 'ham'
    print(a)              # prints 'spam'

In Python 2, using the exec statement meant the compiler knew to switch off the local scope optimizations (switching from LOAD_FAST to LOAD_NAME for example, to look up variables in both the local and global scopes). With exec() being a function, that option is no longer available and function scopes are now always optimized.

Moreover, in Python 2, the exec statement explicitly copies all variables found in locals() back to the function locals using PyFrame_LocalsToFast, but only if no globals and locals parameters were supplied.

The proper work-around is to use a new namespace (a dictionary) for your exec() call:

def execute(a, st):
    namespace = {}
    exec("b = {}\nprint('b:', b)".format(st), namespace)
    print(namespace['b'])

The exec() documentation is very explicit about this limitation:

Note: The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.

2 of 4
9

I'd say it's a bug of python3.

def u():
    exec("a=2")
    print(locals()['a'])
u()

prints "2".

def u():
    exec("a=2")
    a=2
    print(a)
u()

prints "2".

But

def u():
    exec("a=2")
    print(locals()['a'])
    a=2
u()

fails with

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in u
KeyError: 'a'

--- EDIT --- Another interesting behaviour:

def u():
    a=1
    l=locals()
    exec("a=2")
    print(l)
u()
def u():
    a=1
    l=locals()
    exec("a=2")
    locals()
    print(l)
u()

outputs

{'l': {...}, 'a': 2}
{'l': {...}, 'a': 1}

And also

def u():
    l=locals()
    exec("a=2")
    print(l)
    print(locals())
u()
def u():
    l=locals()
    exec("a=2")
    print(l)
    print(locals())
    a=1
u()

outputs

{'l': {...}, 'a': 2}
{'l': {...}, 'a': 2}
{'l': {...}, 'a': 2}
{'l': {...}}

Apparently, the action of exec on locals is the following:

  • If a variable is set within exec and this variable was a local variable, then exec modifies the internal dictionary (the one returned by locals()) and does not return it to its original state. A call to locals() updates the dictionary (as documented in section 2 of python documentation), and the value set within exec is forgotten. The need of calling locals() to update the dictionary is not a bug of python3, because it is documented, but it is not intuitive. Moreover, the fact that modifications of locals within exec don't change the locals of the function is a documented difference with python2 (the documentation says "Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns"), and I prefer the behaviour of python2.
  • If a variable is set within exec and this variable did not exist before, then exec modifies the internal dictionary unless the variable is set afterwards. It seems that there is a bug in the way locals() updates the dictionary ; this bug gives access to the value set within exec by calling locals() after exec.
🌐
Tutorialspoint
tutorialspoint.com › python › python_exec_function.htm
Python exec() Function
The Python exec() function allows dynamic execution of Python code. It can execute a string containing Python statements or a compiled code object. Generally, this function is used for running code generated by another part of the program.
🌐
Reintech
reintech.io › blog › python-understanding-the-exec-method
Python: Understanding the exec() Method | Reintech media
January 4, 2026 - The exec() function stands as one of Python's most powerful—and potentially dangerous—built-in functions. It executes arbitrary Python code at runtime, enabling dynamic program behavior that's impossible with static code alone.