0

I'm trying to write a single function 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 doesn't work 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 gave 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
2
  • Why? Are you expecting this to run in a separate thread? Otherwise, how can this possibly work? Do you expect this to loop forever until the variable changes? Commented Jun 15, 2022 at 21:36
  • yes, the second loop works until the function turns to true. Commented Jun 15, 2022 at 21:39

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.