Ajit
Ajit

Reputation: 281

Python global list not being updated

I have a global list and it seems that it doesn't update the list in the file it is declared. I have seen several question similar to my issue which I can use to fix my issue. But I was trying to understand why it does not work in my case.

HelloWorld.py

import TestFile

store_val = ["10", "20"]

def main():
    store_val.append("30")
    print store_val
    TestFile.list_val()

if __name__ == '__main__':
    main()

TestFile.py

import HelloWorld

def list_val():
    HelloWorld.store_val.append("40")
    print "Store Value : ", HelloWorld.store_val
    HelloWorld.store_val.append("60")
    print "Updated Value : ", HelloWorld.store_val

The problem that I see is that I am able to append a value to the list in TestFile.py but can't seem to add a value to the list in HelloWorld.py even though it is declared there. What is the best way to rectify this issue so that I can append the value from HelloWorld.py

Result of running HelloWorld

['10', '20', '30']
Store Value :  ['10', '20', '40']
Updated Value :  ['10', '20', '40', '60']

Upvotes: 2

Views: 887

Answers (1)

Akshay Hazari
Akshay Hazari

Reputation: 3267

Should be this way instead . In your case only the store_val list and main function gets imported from HelloWorld in TestFile.py but the main function is not run in TestFile.py

HelloWorld.py

import TestFile

store_val = ["10", "20"]

def main(n=1):
    store_val.append("30")
    print store_val
    if n>0:
        TestFile.list_val(n)

if __name__ == '__main__':
    main()

TestFile.py import HelloWorld

def list_val(n):
    if (n>=0):
        HelloWorld.main(n-1)

    HelloWorld.store_val.append("40")
    print "Store Value : ", HelloWorld.store_val
    HelloWorld.store_val.append("60")
    print "Updated Value : ", HelloWorld.store_val

if __name__ == '__main__':
    list_val()

Run Code:

python HelloWorld.py
['10', '20', '30']
['10', '20', '30']
Store Value :  ['10', '20', '30', '40']
Updated Value :  ['10', '20', '30', '40', '60']

Upvotes: 1

Related Questions