Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't get the changed global variable

t.py

value = 0

def change_value():
    global value
    value = 10

s.py

import t
from t import value

t.change_value()

print(f'test1: {t.value}')
print (f'test2: {value}')

Output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

test1: 10

test2: 0

Why isn’t it not returning the changed value in the test2 ?

>Solution :

This is how import works in Python. You should read what the documentation says on the import statement carefully.

Specifically, when you use the from import syntax on a module attribute, Python looks up the value of that attribute, and then "a reference to that value is stored in the local namespace".

So, if value is 10, then after from t import value you have a reference to 10. That 10 stays a 10 no matter what happens to t.value.

Just to drive home the point about reference semantics vs. value semantics, consider what would happen if you had this in t.py instead:

value = []

def change_value():
    global value # not actually needed anymore
    value.append(10)

def change_reference():
    global value
    value = value + [10]

Contrast the differences between calling t.change_value() and t.change_reference(). In the first case, both prints would be the same, while in the second, they would be different.

This is because after calling change_value() we only have one list, and the name value in s.py is referring to it. With change_reference() we have two lists, the original (empty) one and a new one, and value in s.py is still referring to the original one.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading