[Tutor] Exchanging window data

Magnus Lycka magnus@thinkware.se
Fri, 11 Oct 2002 00:58:04 +0200


At 14:44 2002-10-10 -0700, Glen Barnett wrote:
>I'm writing a script to use any number of windows and I'm interested in
>exchanging data among them.

You can use a number of different ways to exchange data. In
a wxPython application I'm using the Publish/Subscribe
or Observer pattern.

The central handler for this looks like this:
(It's more or less directly from the GoF book,
but uses Alex Martelli's Borg pattern.)

# Publish-Subscribe pattern (alias Observer)
class Publisher:
     __shared_state =3D {'observers' : {},  'message' : {}}
     def __init__(self):
         self.__dict__ =3D self.__shared_state
     def attach(self, observer, event):
         if not self.observers.has_key(event):
             self.observers[event] =3D []
         if observer not in self.observers[event]:=20
self.observers[event].append(observer)
     def detach(self, observer, event):
         try: self.observers[event].remove(observer)
         except (KeyError, ValueError), e:
             print e
     def notify(self, event):
         try:
             for o in self.observers[event]:
                 o.update(event)
         except KeyError:
             pass
     def getMessage(self, event):
         try:
             return self.message[event]
         except:
             m =3D "Tried to get message for nonexisting event %s" % event
             print m
             return m
     def setMessage(self, event, message):
         self.message[event] =3D message
         self.notify(event)

A class that is listening to a kind of event (this has
nothing to do with GUI events) needs to call the attach()
method of the Publisher, and it must have a update()
method which is called to notify the sunscriber of the
event. On notification, it might call getMessage().

The class that is sending the information will call the
SetMessage method.

So, to be a subscriber (or observer)...

class X:
     def __init__(self,...):
         ...
         Publisher().attach(self, 'QUOTES')
         ...
     def __del__(self):
         Publisher().detach(self, 'QUOTES')
     def update(self, event):
         # Handle an observation
         msg =3D Publisher().GetMessage(event)
         ...

And the class sending the message...

class Y:
     def xyz(self, ...):
         ...
         Publisher().SetMessage('QUOTES', 'MSFT $0.55')
         ...

I'm using strings here, but both events and messages could
be arbitrary objects, as long as the sender and rceiver
agrees. I often use classes as events.



--=20
Magnus Lyck=E5, Thinkware AB
=C4lvans v=E4g 99, SE-907 50 UME=C5
tel: 070-582 80 65, fax: 070-612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se