Better to do it with a class than with globals.
class EdgeTrigger(object):
def __init__(self, callback):
self.value = None
self.callback = callback
def __call__(self, value):
if value != self.value:
self.callback(self.value, value)
self.value = value
To use this code, create an object with the function that should be called:
def my_callback(oldVal, newVal):
print "Value changed from {0} to {1}.".format(oldVal, newVal)
detector = EdgeTrigger(my_callback)
Then "call" the object with each new value as you get it:
with open("infile.txt") as f:
for line in f:
detector(line.strip())
This will read lines from a file and print a message when two consecutive lines are not the same.
$ cat infile.txt
1
1
1
2
2
1
1
2
2
5
$ python edgedetect.py
Value changed from None to 1.
Value changed from 1 to 2.
Value changed from 2 to 1.
Value changed from 1 to .
Value changed from to 1.
Value changed from 1 to 2.
Value changed from 2 to 5.