What is a method for updating a class member in Python while it is still being used by other methods in the class?
I want the rest of the class to continue processing using the old version of the member until it is fully updated and then switch all processing to the new version once the update is complete.
Here is a toy example to illustrate my use case, where self.numbers
is the class member that needs safely threaded periodic updating using the logic in updateNumbers()
, which I want called in a non-blocking way by runCounter()
.
from time import sleep, time
class SimpleUpdater(object):
def __init__(self):
self.i = 5
self.numbers = list(range(self.i))
self.lastUpdate = time()
self.updateDelta = 10
def timePast(self):
now = time()
delta = self.lastUpdate - now
return (delta > self.updateDelta)
def updateNumbers(self):
print('Starting Update', flush=True)
self.numbers = list(range(self.i))
# artificial calculation time
sleep(2)
print('Done Updating', flush=True)
def runCounter(self):
for j in self.numbers:
print(j, flush=True)
sleep(0.5)
self.i += 1
if self.timePast:
## Spin off this calculation!! (and safely transfer the new value)
self.updateNumbers()
if __name__ == '__main__':
S = SimpleUpdater()
while True:
S.runCounter()
The desired behavior is that if self.numbers
is being iterated on in the loop, it should finish the loop with the old version before switching to the new version.