Kepoor Hampond Kepoor Hampond -4 years ago 115
Python Question

Live detect of variable change

Is it possible to set up a loop with live variable changes? I'm using threading, and the variables can change very often in between lines.

I'm looking for something like this:

length = len(some_list)
while length == len(some_list):
if check_something(some_list):
# The variable could change right here for
# example, and the next line would still be called.
do_something(some_list)


So far I've had no luck, is this something that's possible in python?

EDIT: More what I'm looking for is something so that the loop restarts if
some_list
changes.

Answer Source

If its just a single changing list, you can make a local copy.

def my_worker():
    my_list = some_list[:]
    if check_something(my_list):
        do_something(my_list)

UPDATE

A queue may work for you. The thing that modifies needs to post to the queue, so its not an automatic thing. There is also the risk that the background thread falls behind and processes old stuff or ends up crashing everything if memory is exhausted by the queue.

import threading
import queue
import time

def worker(work_q):
    while True:
        some_list = work_q.get()
        if some_list is None:
            print('exiting')
            return
        print(some_list)

work_q = queue.Queue()
work_thread = threading.Thread(target=worker, args=(work_q,))
work_thread.start()

for i in range(10):
    some_list.append(i)
    work_q.put(some_list[:])
    time.sleep(.2)
work_q.put(None)

work_thread.join()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download