Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get the changed global variable

Tags:

python

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

test1: 10

test2: 0

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

like image 320
ABHIJITH EA Avatar asked Oct 11 '25 09:10

ABHIJITH EA


2 Answers

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.

like image 147
cha0site Avatar answered Oct 13 '25 21:10

cha0site


I think the main point of confusion is that with from t import value you are not importing a complex module or another reference to a mutable object, but a simple immutable int (in this case). In a way, from t import value is about the same as value = t.value (assuming you already imported t before), storing the value of t.value in another variable (also called value). Assigning a new value to t.value won't change the value assigned to value.

like image 29
tobias_k Avatar answered Oct 13 '25 22:10

tobias_k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!