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 ?
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With