I'm trying to write a single funcion that turn to true when a variable changes. The script should put the variable in a list and check if it changes. Now, i need to call the function in another loop, so the script have to do one cicle when invoked for i in range(0, 1)
Anyway the function doesnt works and the output is always false...any suggestions?
(NOOB)
def change():
v1 = []
for i in range(0, 1):
v1.insert(0, get.value()) #get.value gaves a value when invoked
if len(v1) > 2:
if v1[0] != v1[1]:
v1.clear()
v1.insert(0, get.value())
return True
else:
return False
CodePudding user response:
You've made this harder than it needs to be. Just store the value you know and wait for it to change.
def change():
v1 = get.value()
while get.value() == v1:
time.sleep(0.5)
return True
You need the sleep in there, otherwise this will consume 100% of the CPU and your other code won't run. Remember this ONLY works in a thread, which means it's probably not what you really need.
CodePudding user response:
You can use a decorator factory to freeze values:
from functools import partial
def frozen_args(val):
def my_decorator(wrapped_func):
return partial(wrapped_func, frozenval=val)
return my_decorator
class Get:
def __init__(self):
self.x = 1
def value(self):
return self.x
get = Get()
@frozen_args(get.value())
def change(frozenval: int) -> bool:
return get.value() != frozenval
Testing it:
>>> change()
False
>>> get.x = 3
>>> change()
True
If you ever need to reset the value in testing, remove the decorator from the function definition and use it inline when you need it:
def change(frozenval: int) -> bool:
return get.value() != frozenval
>>> change_now = frozen_args(get.value())(change)
>>> get.x = 2
>>> change_now()
True
>>> change_now = frozen_args(get.value())(change)
>>> change_now()
False