Search code examples
pythonpython-importpython-datamodel

imported variable update is not reflecting in the parent module


i have two modules, main and update.

in main, i declare a dictionary of references and a list for each value. In update i update the age, but i do not see the update reflecting in the main module again.

main module

candidates = {'goutham': {'Age': 30}, 'teja':{'Age': 27}}

for s in candidates:
    portfolio[s] = [0,0] # some value which i use for other calculations

update module
from main import *

portfolio['goutham'][0] = 32

Now when i come back to main and print the portfolio['goutham']. It still shows the values as [0,0]


Solution

  • E.g. this should work print {'goutham': [32, 0], 'teja': [0, 0]} when you run run.py which I added:

    main.py

    candidates = {'goutham': {'Age': 30}, 'teja':{'Age': 27}}
    portfolio = {candidate:[0, 0] for candidate in candidates.keys()}
    

    update.py

    from main import *
    portfolio['goutham'][0] = 32
    

    run.py

    import update
    from main import *
    print(portfolio)
    

    As a side comment: right now you have in your modules that is being executed when the module is imported. If it is your main logic, consider putting it in some main() function instead of relying on implicit execution on import.