Is this possible in Python ?

Carel Fellinger carel.fellinger at chello.nl
Thu May 15 11:38:37 EDT 2003


On Thu, May 15, 2003 at 02:13:07PM +0200, Helmut Jarausch wrote:
.. simple solution to monitor access to a var snipped

> Thanks for this reply.
> 
> But it doesn't solve the problem.
> The trick in Simscript was
> 
> You just write
> a= b+c
> d=2*a
> 
> then some time later you want to monitor the variables,
> e.g. for debugging
> and with changing any source line
> you just enter these monitoring functions and
> activate them.

Complain, complain, that's all they do:)

Well as you didn't object to having to encapsulate such behavior in a
class you ought to like this:

    class C(object):
        def __init__(self, a):
            print "init a"
            self.a = a

    def get_a(self):
        print "right-monitor-a"
        return self._a

    def set_a(self, value):
        print "left-monitor-a"
        self._a = value

    # notice that the set/get functions are no longer methods of C
    # but still the monitoring can be switch on and off at any time

    def monitor_on(self, name, getter, setter, deller, doc):
        current = getattr(self, name)
        delattr(self, name)
        C.a = property(getter, setter, deller, doc)
        setter(self, current)

    def monitor_off(self, name):
        current = getattr(self, name)
        delattr(self.__class__, name)
        setattr(self, name, current)


    b = 1
    c = C(2)

    print "begin test 1"
    c.a = b + c.a
    print "end test 1"

    monitor_on(c, "a", get_a, set_a, None, "monitor a")

    print "\nbegin test 2"
    c.a = b + c.a
    print "end test 2"

    monitor_off(c, "a")

    print "\nbegin test 3"
    c.a = b + c.a
    print "end test 3"


The downside of this simple schema is that monitoring is turned on/off
for *all* instances of C at the same time.  If that really bothers you
then you could try some on the fly class juggling.

-- 
groetjes, carel





More information about the Python-list mailing list