Sometimes I need a class that is constantly updated by the workflow that it spawns when it is created. Mostly like this:
class MyWidget:
def __init__(self):
self.blah = None
self.thread = MyThread(self)
self.thread.start()
def update(self, blah):
self.blah = blah
class MyThread(threading.Thread):
def __init__(self, widget):
self.widget = widget
def run(self):
while True:
time.sleep(1)
blah = poll()
self.widget.update(blah)
I want to create a safe way for this so that I am sure that the thread dies when it is MyWidgetno longer needed. The problem with the above code is that it MyWidgetwill never die, because it is supported in mode MyThread. I can fix this by pointing MyThreada weakref.refto MyWidgetand breaking the loop when this link dies, but I made a mistake without doing this in the past.
, . . , , , . ? ?