Event triggering and weak references

Bernhard Herzog herzog at online.de
Sun Apr 16 20:33:49 CEST 2000


"Ricardo Nogueira" <rnog2438 at mail.usyd.edu.au> writes:

[...]
> 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).
> 
> Smalltalk implements this with:
> 
> The widget would register interest in one aspect of the car  (on opening
> over aCar):
>   aCar when:#speedChanged send: #updateSpeedDisplay to: self
> 
> And the car would just notify who is interested, if any (when its speed
> changes):
>   self trigger: #speedChanged

I've implemented something like that in Sketch. In that scheme, classes
that trigger events are usually derived from a Publisher class which
implementes two methods Subscribe and Unsubscribe to connect to events
and events are identified by strings and may have additional parameters.
You example would look like this (only the relevant methods):

class Car(Publisher):

	def set_speed(self, speed):
		if self.speed != speed:
			self.speed = speed
			# now issue a speed message. This will call all 
			# callbacks subscribed to "speedChanged"
			self.issue("speedChanged")

class Speedometer:

	def __init__(self, car):
		self.car = car
		# subscribe the update method to the "speedChanged" messages
		self.car.Subscribe("speedChanged", self.update)

	def update(self):
		speed = self.car.Speed()
		# update the display...


> But if any of this windows is not referenced anymore or crashes I would like
> the garbage collector clear it (the car would not be notified and his
> pointer to the window shouldn't keep the garbage collector form freeing the
> window memory).
> 
> Again, Smalltalk implements this with weak references, that doesn't count
> for the garbage collector.

In this particular case the displays are probably connected to some
specific widget, so its probably enough to have a callback for the
widget's "destroy" or "delete" event or whatever it's called in your
widget set and disconnect the event handlers there.
 
> Is there support for this in Python?

Not directly.

> Any suggestions?

The implementation of this in Sketch is pure Python and it has already
been used outside of Sketch in pybliographer with practically no changes
(the only changes were to get rid of some Sketch specific error
reporting).

The current version of this connector module is in GNOME CVS:
http://cvs.gnome.org/lxr/source/sketch/Sketch/Base/connector.py

It's only slightly different from the one in Sketch 0.6.5 or 0.7.6. (for
a URL see my .sig)

-- 
Bernhard Herzog   | Sketch, a drawing program for Unix
herzog at online.de  | http://sketch.sourceforge.net/



More information about the Python-list mailing list