Hacking/debug python unexpected dictionary modification

A small code snippet to help debugging when you have an unexpected modification in your python code. In short, you replace the dictionary by a proxy that will trigger "intelligently" when the unexpected modification occurs.

Original code

Let's say your original code is as follow:

theDict = { ... }
dothings...
theDict['foo'] = 'bar'
doMoreThings...
# theDict shouldn't change after this point
doOtherThings...
#At this point, I realize that (for example) theDict['foo'] as disappeared.

Now the question is: how to find when the value was deleted ?

Modified:

_theDict = { ... }
theDict = _DictProxy(_theDict)

Where _DictProxy is:


class _DictProxy:

    def __init__(self, d):
        self.d = d

    def get(self, k, default=None):
        return self.d.get(k, None)

    def __setitem__(self, k, v):
        if k == '<key not expected to be modified>': raise Exception('here')
        self.d[k] = v

Comments

<comments/>