Capricorn
Capricorn

Reputation: 33

How to update a list from an imported module once imported?

test.py

import threading

a_list = []
def a():
    while True:
        a_list.append("A")

threading.Thread(target=a).start()

test1.py

import test
from test import a_list
import time

while True:
    print(a_list)
    time.sleep(1)

if I import the file "test" and infinitely append "A" into a list and use "test1" to print the values, for some reason the values WILL NOT update for test1

How can I make test1 recognise that the list has been updated from file "test" and print it out using the file "test1"

I rushed this code to share in here, I am sorry about that. Some help would be nice. I tried googling it but I couldn't find anything

Upvotes: 0

Views: 72

Answers (1)

Alex Yu
Alex Yu

Reputation: 3537

You forgot global in your function:

import threading

 a_list = []
 def a():
      global a_list
      while True:
         a_list.append("A")

 threading.Thread(target=a).start()

Althougth I recommend against such code.

Beware: "Here be dragons"

Upvotes: 1

Related Questions