Question

I am monitoring a boolean value in a python-twisted framework. When the boolean value changes I want to execute a function only once. Can this be done in Python?

I am pulling the boolean value in from an IO device serially. The value is polled on some time interval. When the value changes I want to execute a function.

Was it helpful?

Solution

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.

OTHER TIPS

Edge triggering just requires remembering the previous value.

_prev_value = False
def check_value(val):
    global _prev_value
    change = None
    if val and not _prev_value:
        change = 'up'
    elif _prev_value and not val:
        change = 'down'
    _prev_value = val
    return change

And, obviously, this could be implemented in a class instead of using a global.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top