3

First

x = 30
def out():
    x = 50
    def inner():
        print x
        print locals()
    return inner
out()()    # print locals() output {'x': 50}

Second

But when I use exec , the output of print locals() is empty

x =30
def out():
    x = 50
    def inner():
        print x
        print locals()
        exec 'print x' in globals(), locals()
    return inner
out()()    #  print locals() ouput {}

Does exec have any side effects to the output of locals() ?

caffrey
  • 31
  • 4
  • 1
    Yes it does. the `exec` statement explicitly copies all variables found in `locals()` back to the function locals. In Python 3, where `exec` was made into a function instead of a statement, the above, corrected for print and exec syntax changes, works. – Uvar Oct 02 '17 at 08:55
  • Can you explain why the second example's locals() is empty? – caffrey Oct 02 '17 at 09:51
  • Because there is no more `x` in the local scope. It now exists solely in the enclosure of the function `inner`, while the locals scope is reset. To see what happens, add the following lines of code to your second function `inner`: `print(x, globals())` `print(inner.func_code.co_freevars, [a.cell_contents for a in inner.func_closure])` @Kasramvd I do not think it is an exact duplicate though. It is related, that is for sure. – Uvar Oct 02 '17 at 13:48
  • I am curious about something . Which step reset the locals scope and why? At the mean time, why `x` exist in the `locals()` in first example? Appreciate your patience! :) – caffrey Oct 02 '17 at 15:35
  • calling on the `exec` statement resets the locals scope. This was disabled in Python 3, where `exec` was remodelled to be a function instead of a statement to enforce unambiguous behaviour. As to why it ever did so in the first place..I cannot answer you that. :( – Uvar Oct 02 '17 at 15:38

0 Answers0