Exec () and the scope of variables

I am sure that they asked and answered about this, but I could not find it specifically:

I just pick Python and I don't understand the problem with variable variable .

I simplified the problem as follows:

Case 1:

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

lev1()

Case 2:

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

lev1()

Case 3:

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

lev1()
  • Case 1and Case 2have aaaundefined in the print instruction.
  • Case 3works. Where aaadoes it really exist in Case 1and Case 2?
  • Is there a way to access aaacase 1 without an announcement global?
+4
source share
1 answer

From docs :

.. , locals() : . locals, exec().

, exec , - , Python , , .

exec uted , globals(). ( globals dict locals dict, exec dict , locals.)

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

lev1()
+5

Source: https://habr.com/ru/post/1683113/


All Articles