Importing global variables in python in two ways

I came across a situation I don't understand. I have three files:

one.py (runnable):

import two
import three

three.init()
two.show()

two.py:

import three

def show():
    print(three.test)

three.py:

test = 0

def init():
    global test
    test = 1

The outcome is 1, as I expected. Now let's modify two.py:

from three import test

def show():
    print(test)

The outcome is 0. Why?

1 answer

  • answered 2017-10-11 10:28 scriptmonster

    It's all about scope. If you change your one.py as follows you would see better.

    import three
    from three import test
    
    three.init()
    
    print(test)
    print(three.test)
    

    it will print:

    0        <== test was imported before init()
    1        <== three.test fetches the current value
    

    When you import only variable it will create a local variable which is an immutable integer.

    But if you change order of the import statement like following you would get a different result:

    import three
    
    three.init()
    print(three.test)
    
    from three import test
    print(test)
    

    it will print:

    1        <== three.test fetches the current value
    1        <== test was imported after init()