exec() and variable scope [duplicate]

From the docs:

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.

In other words, if you call exec with one argument, you're not supposed to try to assign any variables, and Python doesn't promise what will happen if you try.

You can have the executed code assign to globals by passing globals() explicitly. (With an explicit globals dict and no explicit locals dict, exec will use the same dict for both globals and locals.)

def lev1():
   exec("aaa=123", globals())
   print("lev1:", aaa)

lev1()