Event triggering and weak references

Darrell darrell at dorb.com
Sun Apr 16 16:22:36 CEST 2000


"Ricardo Nogueira"
> This is what I would like to do:
> Imagine I could have two or more Widgets open displaying a car speed
value,
> say a numerical and a graphic display, if this car speed changes (ex. some
> one pushes the break), I would like to have any open widget on this value
> updated (on opening each window would register interest with this car
> speed).
>
Here's an approach that requires changes to the watched class.
Maybe some of Robert's method wrappers would be nice.
Being able to hook a method from the outside is a powerful way to decouple
code. But wouldn't it be harder to understand? Sometimes I think C++ is
difficult because only when you trace though it do you realize where it's
going. Having the watched thing provide an explicit signal seems easier to
understand.

Don't know if you can call this weak references but they can't cause cycles.
The use of strings to avoid cycles may not be required soon with the new GC
stuff.

uthreads.py might be cool for this sort of thing, somehow?

Thanks for the Sunday morning puzzle.
--Darrell Gallion


class Watches:
        # Only strings are stored
    _Obs={}

    def regWatch(self, obs, watch):
        """
        obs     : observer name string
        watch   : string name of thing to watch
        """
        Watches._Obs[watch].append(obs)

    def unregWatch(self, obs, watch):
        l=Watches._Obs[watch]
        x=l.index(obs)
        del l[x]

    def regWatchAble(self, watch):
        Watches._Obs[watch]=[]

    def unregWatchAble(self, obs, watch):
        del Watches._Obs[watch]

    def signal(self,watch):
        l=Watches._Obs[watch]
        w=eval(watch)
        for i in l:
            i=eval(i)
            i(w)

    def clean(self):
        for k in Watches._Obs.keys():
            try:
                w=eval(watch)
            except:
                del Watches._Obs[k]
                print 'Cleaned:',k

watches=Watches()

class W1:
    """Something to watch"""
    def __init__(self, watches,name):
        self._var1=0
        self._watches=watches
        self._name=name
        watches.regWatchAble(name)

    def setVar(self,v):
        self._var1=v
        self._watches.signal(self._name)

    # 'w1' would be more like 'moduleName.w1'
w1=W1(watches, 'w1')

def obs1(w):
    print "Signaled:",w

watches.regWatch('obs1','w1')

w1.setVar(6)
del w1
watches.clean()

############ Output
Signaled: <__main__.W1 instance at 895b48>
Cleaned: w1







More information about the Python-list mailing list