No, it shouldn’t run fine. return outside of a function is illegal so it should be illegal when passed to exec as well. Otherwise exec runs a superset of Python: code that “works” in exec doesn’t work outside of exec. And that would be bad. I’m both horrified and impressed by your hack to get it w… Answer from steven.daprano on discuss.python.org
🌐
Python documentation
docs.python.org › 3 › library › functions.html
Built-in Functions — Python 3.14.5rc1 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).
🌐
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.
🌐
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
🌐
Medium
medium.com › @murungaephantus › why-you-should-not-use-eval-and-exec-in-python-77d19345128c
Why you should not use eval() and exec() in Python | by Murunga Kibaara | Medium
May 19, 2023 - The eval() and exec() functions in Python are powerful tools that can be used to evaluate and execute arbitrary Python code. However, they…
🌐
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.
Find elsewhere
🌐
GitHub
github.com › openinterpreter › open-interpreter
GitHub - openinterpreter/open-interpreter: A natural language interface for computers · GitHub
Open Interpreter equips a function-calling language model with an exec() function, which accepts a language (like "Python" or "JavaScript") and code to run.
Starred by 63.4K users
Forked by 5.5K users
Languages   Python
🌐
Nocomplexity
nocomplexity.com › exec-in-python
exec() in Python: Simple & smart or Career-Ending Mistake? – NO Complexity
November 27, 2025 - The problem is that the exec function executes code dynamically. Although this capability is intentionally part of the Python Standard Library (PSL) due to its simplicity in running external code—such as script files, data from an API, or user-provided input—its use presents a major security ...
🌐
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.
🌐
DEV Community
dev.to › sachingeek › using-pythons-exec-to-generate-code-dynamically-1nf8
Using Python's exec() To Generate Code Dynamically - DEV Community
April 25, 2023 - The exec() function in Python allows us to execute the block of Python code from a string. This...
🌐
TutorialsPoint
tutorialspoint.com › article › exec-in-python
exec() in Python
March 15, 2026 - The exec() function in Python allows you to dynamically execute Python code at runtime. It can execute code passed as a string or compiled code object, making it useful for scenarios where code needs to be generated and executed programmatically.
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.
🌐
Clay-Technology World
clay-atlas.com › home › [python] how to exec() function to execute a program as string
[Python] How to exec() function to execute a program as string - Clay-Technology World
April 7, 2021 - How to use exec() in Python to convert the string to a dynamic code. It can execute the dynamic code in Python. This function is simple and useful!
🌐
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.
🌐
ServiceNow
careers.servicenow.com › jobs
Explore Jobs | ServiceNow Careers
At the fastest-growing enterprise software company, your career is bound to grow, too.
🌐
Techieclues
techieclues.com › tutorials › python-built-in-functions › exec-function-in-python
exec() Function in Python
July 19, 2023 - Python exec() Function The exec() function in Python is a built-in function that allows you to dynamically execute Python code stored in a string or code object.
🌐
Python.org
discuss.python.org › python help
How can I use exec in functions in python3.6 similar to python2.7? - Python Help - Discussions on Python.org
August 17, 2021 - Hello, in python 2.7 the following code works: def f( b ): … exec( ‘a=%s’%b ) … print ‘a=, a … f( 1 ) a= 1 in python3.6 this works in the interpreter: b=1 exec(‘a=%s’%b) a 1 but not in a function: def f( b ): … exec( ‘a=%s’%b ) … print( ‘a=’, a ) … f( 1 ) Traceback ...
🌐
Quora
quora.com › How-can-I-use-the-exec-or-eval-in-python-to-execute-run-a-function
How to use the exec or eval in python to execute/run a function - Quora
Answer (1 of 2): I will only talk of eval() because I find it more useful. First off: eval() is a potential security risk because the globals (positional argument of eval) default to the current global namespace, making it available to anyone who can access the string inside the eval. This means ...