Jason Yang
Jason Yang

Reputation: 13057

Why still get old value of variable after update when import a library

Create library test_module as following,

C:\Software\Python\Lib\site-packages\test_module>dir
 Volume in drive C is OS
 Volume Serial Number is BA4B-6BE1

 Directory of C:\Software\Python\Lib\site-packages\test_module

02/24/2021  01:00 PM    <DIR>          .
02/24/2021  01:00 PM    <DIR>          ..
02/24/2021  12:38 PM                74 test_module.py
02/24/2021  01:00 PM                26 __init__.py
02/24/2021  01:00 PM    <DIR>          __pycache__
               2 File(s)            100 bytes
               3 Dir(s)  43,387,817,984 bytes free
# __init__.py
from .test_module import *
# test_module.py
VALUE = 10

def set_value(value):
    global VALUE
    VALUE = value
# main.py
import test_module as tm

print(tm.VALUE)
tm.set_value(50)
print(tm.VALUE)

After run main.py

10
10

My question is why I still get old value of tm.VALUE, 10, after tm.set_value(50) ?

If just file test_module.py and imported, then I will get new value, 50.

10
50

My target is to find what's wrong when I get the value of tm.VALUE after import a library test_moduel. It shown the value changed when I called other functions in this library, but wrong value read by the way of tm.VALUE.

Upvotes: 1

Views: 379

Answers (1)

ghchoi
ghchoi

Reputation: 5156

If you do

# __init__.py
from .test_module import *

it becomes like

# __init__.py
VALUE = 10                         # copied by value

set_value = test_module.set_value  # copied by reference


# test_module.py
VALUE = 10

def set_value(value):
    global VALUE
    VALUE = value

So, if you tm.set_value(50) from main.py, you actucally set test_module.VALUE not __init__.VALUE.

Fix 1

Remove __init__.py and rename test_module.py to __init__.py

Fix 2

Remove the package folder test_module and just keep test_module.py there instead.

Fix 3

If you want to directly access to the variable, simply do:

# main.py
import test_module as tm

print(tm.test_module.VALUE)
tm.set_value(50)
print(tm.test_module.VALUE)

Upvotes: 1

Related Questions