Subhayan Bhattacharya Subhayan Bhattacharya - 24 days ago 19
Python Question

Changing values inside Python Modules

I have a simple Python module file

First.py
:

a = 50
b = [100,200,300]


I try to import this module into another file
Test.py
:

import First
First.a = 420
First.b[0] = 420
print (First.a)


My purpose is to change the list values inside the First module.

Once the script
Test.py
completes when I print the values inside the module , I find that the values have not changed.

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (I
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import First
>>> dir(First)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'a', 'b']
>>> First.a
50
>>> First.b
[100, 200, 300]


What am I missing here? Can someone kindly guide me?

Answer

Once the script Test.py completes when I print the values inside the module , i find that the values have not changed.

If you executed python Test.py, then fired up your interpreter interactively and checked the values, of course, modifications won't be visible. Python just loads First.py when the import is found, executing it and initializing a and b with the values in First.py; previous executions won't affect this.

If you import Test in your interactive interpreter and then import First changes will be reflected:

Python 3.5.2 |Anaconda 4.2.0 (64-bit)| (default, Jul  2 2016, 17:53:06) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import Test
420
>>> import First
>>> First.a
420
>>> First.b
[420, 200, 300]

During the import of Test, First was loaded and executed, then its values modified. When you re-import python will just look in a table of imported modules (sys.modules) and return it without executing its content (and re-initializing a and b)

Comments