How to check if a variable value has changed

If I have a variable:

var = 5

I want to detect and move to a function when the variable value changes, so if it vardoes not match the value that was before, I want to go to the 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()
+4
source share
2 answers

I would go with a setter function that runs your required function.

def setValue(val):
    global globalVal
    valueChanged= g_val != val
    if valueChanged:
        preFunction()
    globalVal = val
    if valueChanged:
        postFunction()
+3
source

Based on @HelloWorld answer and @drIed's comment: A good way would be to turn 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.value != new_value:
            self.pre_change()
            self.variable = new_value
            self.post_change()

    def pre_change(self):
        # do stuff before variable is about to be changed

    def post_change(self):
        # do stuff right after variable has changed
+2
source

Source: https://habr.com/ru/post/1606324/


All Articles