0

I am very puzzled by this strange behavior. I have a file called test.py containing the following:

X={}

def fun():
    global X
    X = {'a':1,'b':2}

then I import the file as a module from the console and call the function

from test import *
fun()

I would expect X to be updated but it is still an empty dictionary. I am using

Python 3.8.2 (default, Jul 16 2020, 14:00:26)

is anybody able to reproduce this? Do you know why it happens?

Thanks.

arsenio
  • 21
  • 2
  • See also: https://stackoverflow.com/questions/15959534/visibility-of-global-variables-in-imported-modules – Mark Oct 01 '20 at 13:54

1 Answers1

0

In the second file, the X object is imported and bound to a name at the time import runs. The X in the second file is a second name attached to the original {}. Or, in other words, it's a separate variable that just happens to have the same name as the X in the original file.

Changing the X label in the original file won't change what object the X in the second file is looking at, because they're distinct labels (with the same name).

It's similar to how this doesn't change Y:

X = {}
Y = X  # Y is the "imported X"
X = {'a':1,'b':2}
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117