mlpy.modules.patterns.Observable

class mlpy.modules.patterns.Observable(mid=None)[source]

Bases: mlpy.modules.UniqueModule

The observable base class.

The observable keeps a record of all listeners and notifies them of the events they have subscribed to by calling Listener.notify.

The listeners are notified by calling dispatch. Listeners are notified if either the event that is being dispatched is None or the listener has subscribed to a None event, or the name of the event the listener has subscribed to is equal to the name of the dispatching event.

An event is an object consisting of the source; i.e. the observable, the event name, and the event data to be passed to the listener.

Parameters:

mid : str

The module’s unique identifier

Examples

>>> from mlpy.modules.patterns import Observable
>>>
>>> class MyObservable(Observable):
>>>     pass
>>>
>>> o = MyObservable()

This defines the observable MyObservable and creates an instance of it.

>>> from mlpy.modules.patterns import Listener
>>>
>>> class MyListener(Listener):
>>>
>>>     def notify(self, event):
>>>         print "I have been notified!"
>>>
>>> l = MyListener(o, "test")

This defines the listener MyListener that when notified will print the same text to the console regardless of which event has been thrown (as long as the listener has subscribed to the event). Then an instance of MyListener is created that subscribes to the event test of MyObservable.

When the event test is dispatched by the observable, the listener is notified and the text is printed on the stdout:

>>> o.dispatch("test", **{})
I have been notified!

Attributes

mid The module’s unique identifier.

Methods

dispatch(name, **attrs) Dispatch the event to all listeners.
load(filename) Load the state of the module from file.
save(filename) Save the current state of the module to file.
subscribe(listener[, events]) Subscribe to the observable.
unsubscribe(listener) Unsubscribe from the observable.