watching mutables?

Anton Vredegoor anton at
Mon Sep 30 12:48:03 EDT 2002

On 30 Sep 2002 01:05:17 GMT, bokr at (Bengt Richter) wrote:

<good explanation deleted>

I have slightly adjusted your code to result in the code below, this
works if imported by Idle like this:

Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> from watcher import Watcher
>>> w = Watcher('m',locals())
>>> m = 1
"m" is bound to new object: 1

So this seems to be ok. However if the script below is executed
itself, nothing happens. Also importing the module in another script
and then executing a test script gives no output. The watch function
isn't called at all. I guess the tracer has to know more about the
other arguments in:

    def watch(self, frame, event, arg):

Could this please be elucidated.

Thanks for your insightful remarks and code.

from sys import settrace, modules
from marshal import dumps

class Watcher:

    def __init__(self, name, namespace):
   = name
            self.ns = namespace
            obj = namespace.get(name)
            self.objid = id(obj)
            self.objs = dumps(obj)

    def watch(self, frame, event, arg):
            obj = self.ns.get(
            objid = id(obj)
            if objid != self.objid:
                self.objid = objid
                what = 'new'
                what = 'same but mutated'
            objs = dumps(obj)
            if self.objs != objs:
                print '"%s" is bound to %s object: %s' % (,
what, `obj`)
                self.objs = objs
            elif what == 'new':
                what = 'new but equivalent'
                print '"%s" is bound to %s object: %s' % (,
what, `obj`)

    def finished(self):

def test():
    # huh ?
    w = Watcher('m', locals())
    m = 1

if __name__=='__main__':

More information about the Python-list mailing list