The following code works in Python 2.7, to dynamically inject local variables into a function scope:
myvars = {"var": 123}
def func():
exec("")
locals().update(myvars)
print(var)
func()
# assert "var" not in globals()
It's a bit subtle, but the presence of an exec statement indicates to the compiler that the local namespace may be modified. In the reference implementation, it will transform the lookup of the name "locals" from a LOAD_GLOBAL op into a LOAD_NAME op, enabling addition to the local namespace.
In Python 3, exec
became a function instead of a statement, and the locals()
call returns a copy of the namespace, in which modifications have no effect.
How can you recreate the idea in Python 3, to dynamically create local variables inside a function? Or is this a "feature" only possible in Python 2.x?
Note: The code must not bind the names in outer scopes.