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()
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.
In Variables view, right-click the variable whose value you want to change and select Change 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.
A variable is a data item whose value can change during the program's execution.
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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With