Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a variable's value has changed

If I have a variable:

var = 5

I want to detect and jump to a function when the value of the variable changes, so if var is not equal to the value it was before, I want to jump to a function.

What is the easiest way to do this?

Another example:

from datetime import datetime
import time


def dereferentie():
    currentMinute = datetime.now().minute
    checkMinute(currentMinute)

def checkMinute(currentMinute):

    #if currentMinute has changed do:
        printSomething()

def printSomething():
    print "Minute is updated"


def main():
    while (1):
        dereferentie()


if __name__ == '__main__':
    main()
like image 885
drled Avatar asked Sep 07 '15 23:09

drled


People also ask

How do you know if a variable has changed on Roblox?

There are multiple ways to do it. Use a Value Instance and use the Changed or PropertyChanged event to do it. Use the __newindex metamethod in a metatable to do it.

How do you change a variable's value?

In Variables view, right-click the variable whose value you want to change and select Change Value.

How do you check if a variable has a value?

Answer: Use the typeof operator If you want to check whether a variable has been initialized or defined (i.e. test whether a variable has been declared and assigned a value) you can use the typeof operator.

Can a variable have its value changed?

A variable is a data item whose value can change during the program's execution.


2 Answers

Building on @HelloWorld's answer and @drIed's comment: A nice way would be, to wrap this into a class.

For example:

class Watcher:
    """ A simple class, set to watch its variable. """
    def __init__(self, value):
        self.variable = value
    
    def set_value(self, new_value):
        if self.variable != new_value:
            self.pre_change()
            self.variable = new_value
            self.post_change()
    
    def pre_change(self):
        pass # do stuff before variable is about to be changed
        
    def post_change(self):
        pass # do stuff right after variable has changed
        
like image 172
trophallaxis Avatar answered Sep 21 '22 02:09

trophallaxis


I would go with a setter function which triggers your needed function.

def setValue(val):
    global globalVal
    valueChanged= g_val != val
    if valueChanged:
        preFunction()
    globalVal = val
    if valueChanged:
        postFunction()
like image 29
HelloWorld Avatar answered Sep 20 '22 02:09

HelloWorld