Detecting changes to a dict

Simon Forman sajmikins at gmail.com
Sun Sep 27 17:28:55 CEST 2009


On Sun, Sep 27, 2009 at 5:36 AM, Steven D'Aprano
<steve at remove-this-cybersource.com.au> wrote:
> I'm pretty sure the answer to this is No, but I thought I'd ask just in
> case...
>
> Is there a fast way to see that a dict has been modified? I don't care
> what the modifications are, I just want to know if it has been changed,
> where "changed" means a key has been added, or deleted, or a value has
> been set. (Modifications to mutable values aren't important.) In other
> words, any of these methods count as modifying the dict:
>
> __setitem__
> __delitem__
> clear
> pop
> popitem
> setdefault
> update
>
> Of course I can subclass dict to do this, but if there's an existing way,
> that would be better.
>
>
> --
> Steven


Depending on what you're doing you could use something like this:

(Note that it doesn't work on empty dicts, and you'd have to "reset
it" if your dict ever became empty after processing.)

def f(d):
    while True:
        i = iter(d).next
        try:
            while True:
                try:
                    i()
                except RuntimeError:
                    yield True
                    break
                else:
                    yield False
        except StopIteration:
            if not d:
                break # else we'd enter an infinite loop.


In [1]: d = {23: 18}

In [2]: check = f(d).next

In [3]: check()
Out[3]: False

In [4]: d['cats'] = 'lol'

In [5]: check()
Out[5]: True

In [6]: check()
Out[6]: False

In [7]: d.clear()

In [8]: check()
Out[8]: True

In [9]: check()
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)

/home/sforman/<ipython console> in <module>()

StopIteration:



HTH,
~Simon



More information about the Python-list mailing list