Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dectecting a value change in Python loop

Tags:

python

Here is a pattern I often use:

last_value = None

while <some_condition>:
    <get current_value from somewhere>
    if last_value != current_value:
       <do something>

    last_value = current_value

One application example would be to print headings in a report when, say, a person's last name changes.

The whole last_value/current_value thing has always seemed clumsy to me. Is there a better way to code this in Python?

like image 775
Dan Avatar asked Dec 25 '22 22:12

Dan


1 Answers

I agree that your pattern makes a lot of sense.

But for fun, you could do something like:

class ValueCache(object):
    def __init__(self, val=None):
        self.val = val

    def update(self, new):
        if self.val == new:
            return False
        else:
            self.val = new
            return True

Then your loop would look like:

val = ValueCache()
while <some_condition>:    
    if val.update(<get current_value from somewhere>):
        <do something>

For example

import time
t = ValueCache()
while True:
    if t.update(time.time()):
        print("Cache Updated!")

If you changed time.time() to some static object like "Foo", you'd see that "Cache Updated!" would only appear once (when it is initially set from None to "Foo").

Obligatory realistic programmer's note: Don't do this. I can't easily find a good reason to do this in practice. It not only adds to the line count but to the complexity.

(Inspired by Alex Martelli's Assign and Test Recipe)

like image 50
jedwards Avatar answered Dec 27 '22 10:12

jedwards