1

I have written the below program wherein I am trying to modify the dictionary values present in local symbol table:

def modify_locals():
    str = True
    print(locals())
    locals()['str'] = False
    print(locals())

modify_locals()

Output:

{'str': True}
{'str': True}

Please let me know why locals()['str'] = False is not updating the local symbol table?

meallhour
  • 13,921
  • 21
  • 60
  • 117

1 Answers1

0

globals() returns an actual reference to the dictionary that contains the global namespace.

locals(), on the other hand, returns a dictionary that is a current copy of the local namespace, not a reference to it. So you can’t modify objects in the actual local namespace using the return value from locals().

This is fully explained in this article: https://realpython.com/python-namespaces-scope/#the-locals-function

Ali Hejazizo
  • 198
  • 5