diff --git a/IPython/kernel/core/notification.py b/IPython/kernel/core/notification.py new file mode 100644 index 0000000..c7849fc --- /dev/null +++ b/IPython/kernel/core/notification.py @@ -0,0 +1,85 @@ +# encoding: utf-8 + +"""The IPython Core Notification Center. + +See docs/blueprints/notification_blueprint.txt for an overview of the +notification module. +""" + +__docformat__ = "restructuredtext en" + +#----------------------------------------------------------------------------- +# Copyright (C) 2008 The IPython Development Team +# +# Distributed under the terms of the BSD License. The full license is in +# the file COPYING, distributed as part of this software. +#----------------------------------------------------------------------------- + + +class NotificationCenter(object): + """Synchronous notification center""" + def __init__(self): + super(NotificationCenter, self).__init__() + self.registeredTypes = set() #set of types that are observed + self.registeredSenders = set() #set of senders that are observed + self.observers = {} #map (type,sender) => callback (callable) + + + def post_notification(self, theType, sender, **kwargs): + """Post notification (type,sender,**kwargs) to all registered + observers. + + Implementation + -------------- + * If no registered observers, performance is O(1). + * Notificaiton order is undefined. + * Notifications are posted synchronously. + """ + + if(theType==None or sender==None): + raise Exception("NotificationCenter.post_notification requires \ + type and sender.") + + # If there are no registered observers for the type/sender pair + if((theType not in self.registeredTypes) or + (sender not in self.registeredSenders)): + return + + keys = ((theType,sender), (None, sender), (theType, None), (None,None)) + observers = set() + for k in keys: + observers.update(self.observers.get(k, set())) + + for o in observers: + o(theType, sender, args=kwargs) + + + def add_observer(self, observerCallback, theType, sender): + """Add an observer callback to this notification center. + + The given callback will be called upon posting of notifications of + the given type/sender and will receive any additional kwargs passed + to post_notification. + + Parameters + ---------- + observerCallback : callable + Callable. Must take at least two arguments:: + observerCallback(type, sender, args={}) + + theType : hashable + The notification type. If None, all notifications from sender + will be posted. + + sender : hashable + The notification sender. If None, all notifications of theType + will be posted. + """ + assert(observerCallback != None) + self.registeredTypes.add(theType) + self.registeredSenders.add(sender) + self.observers.setdefault((theType,sender), set()).add(observerCallback) + + + +sharedCenter = NotificationCenter() \ No newline at end of file diff --git a/IPython/kernel/core/tests/test_notification.py b/IPython/kernel/core/tests/test_notification.py new file mode 100644 index 0000000..371925f --- /dev/null +++ b/IPython/kernel/core/tests/test_notification.py @@ -0,0 +1,118 @@ +# encoding: utf-8 + +"""This file contains unittests for the notification.py module.""" + +__docformat__ = "restructuredtext en" + +#----------------------------------------------------------------------------- +# Copyright (C) 2008 The IPython Development Team +# +# Distributed under the terms of the BSD License. The full license is in +# the file COPYING, distributed as part of this software. +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- + +from IPython.kernel.core.notification import NotificationCenter,\ + sharedCenter + +# +# Supporting test classes +# + +class Observer(object): + """docstring for Observer""" + def __init__(self, expectedType, expectedSender, **kwargs): + super(Observer, self).__init__() + self.expectedType = expectedType + self.expectedSender = expectedSender + self.expectedKwArgs = kwargs + self.recieved = False + sharedCenter.add_observer(self.callback, + self.expectedType, + self.expectedSender) + + + def callback(self, theType, sender, args={}): + """callback""" + + assert(theType == self.expectedType) + assert(sender == self.expectedSender) + assert(args == self.expectedKwArgs) + self.recieved = True + + + def verify(self): + """verify""" + + assert(self.recieved) + + + +class Notifier(object): + """docstring for Notifier""" + def __init__(self, theType, **kwargs): + super(Notifier, self).__init__() + self.theType = theType + self.kwargs = kwargs + + def post(self, center=sharedCenter): + """fire""" + + center.post_notification(self.theType, self, + **self.kwargs) + + +# +# Test Cases +# + + +def test_notification_delivered(): + """Test that notifications are delivered""" + expectedType = 'EXPECTED_TYPE' + sender = Notifier(expectedType) + observer = Observer(expectedType, sender) + + sender.post() + + observer.verify() + + +def test_type_specificity(): + """Test that observers are registered by type""" + + expectedType = 1 + unexpectedType = "UNEXPECTED_TYPE" + sender = Notifier(expectedType) + unexpectedSender = Notifier(unexpectedType) + observer = Observer(expectedType, sender) + + sender.post() + unexpectedSender.post() + + observer.verify() + + +def test_sender_specificity(): + """Test that observers are registered by sender""" + + expectedType = "EXPECTED_TYPE" + sender1 = Notifier(expectedType) + sender2 = Notifier(expectedType) + observer = Observer(expectedType, sender1) + + sender1.post() + sender2.post() + + observer.verify() + + +def test_complexity_with_no_observers(): + """Test that the notification center's algorithmic complexity is O(1) + with no registered observers (for the given notification type) + """ + + assert(False) #I'm not sure how to test this yet diff --git a/blueprints/notification_blueprint.txt b/blueprints/notification_blueprint.txt new file mode 100644 index 0000000..705053b --- /dev/null +++ b/blueprints/notification_blueprint.txt @@ -0,0 +1,47 @@ +.. Notification: + +========================================== +IPython.kernel.core.notification blueprint +========================================== + +Overview +======== +The IPython.kernel.core.notification module will provide a simple implementation of a notification center and support for the observer pattern within the IPython.kernel.core. The main intended use case is to provide notification of Interpreter events to an observing frontend during the execution of a single block of code. + +Functional Requirements +======================= +The notification center must: + * Provide synchronous notification of events to all registered observers. + * Provide typed or labeled notification types + * Allow observers to register callbacks for individual or all notification types + * Allow observers to register callbacks for events from individual or all notifying objects + * Notification to the observer consists of the notification type, notifying object and user-supplied extra information [implementation: as keyword parameters to the registered callback] + * Perform as O(1) in the case of no registered observers. + * Permit out-of-process or cross-network extension. + +What's not included +============================================================== +As written, the IPython.kernel.core.notificaiton module does not: + * Provide out-of-process or network notifications [these should be handled by a separate, Twisted aware module in IPython.kernel]. + * Provide zope.interface-style interfaces for the notification system [these should also be provided by the IPython.kernel module] + +Use Cases +========= +The following use cases describe the main intended uses of the notificaiton module and illustrate the main success scenario for each use case: + + 1. Dwight Schroot is writing a frontend for the IPython project. His frontend is stuck in the stone age and must communicate synchronously with an IPython.kernel.core.Interpreter instance. Because code is executed in blocks by the Interpreter, Dwight's UI freezes every time he executes a long block of code. To keep track of the progress of his long running block, Dwight adds the following code to his frontend's set-up code:: + from IPython.kernel.core.notification import NotificationCenter + center = NotificationCenter.sharedNotificationCenter + center.registerObserver(self, type=IPython.kernel.core.Interpreter.STDOUT_NOTIFICATION_TYPE, notifying_object=self.interpreter, callback=self.stdout_notification) + + and elsewhere in his front end:: + def stdout_notification(self, type, notifying_object, out_string=None): + self.writeStdOut(out_string) + + If everything works, the Interpreter will (according to its published API) fire a notification via the sharedNotificationCenter of type STD_OUT_NOTIFICAIONT_TYPE before writing anything to stdout [it's up to the Intereter implementation to figure out when to do this]. The notificaiton center will then call the registered callbacks for that event type (in this case, Dwight's frontend's stdout_notification method). Again, according to its API, the Interpreter provides an additional keyword argument when firing the notificaiton of out_string, a copy of the string it will write to stdout. + + Like magic, Dwight's frontend is able to provide output, even during long-running calculations. Now if Jim could just convince Dwight to use Twisted... + + 2. Boss Hog is writing a frontend for the IPython project. Because Boss Hog is stuck in the stone age, his frontend will be written in a new Fortran-like dialect of python and will run only from the command line. Because he doesn't need any fancy notification system and is used to worrying about every cycle on his rat-wheel powered mini, Boss Hog is adamant that the new notification system not produce any performance penalty. As they say in Hazard county, there's no such thing as a free lunch. If he wanted zero overhead, he should have kept using IPython 0.8. Instead, those tricky Duke boys slide in a suped-up bridge-out jumpin' awkwardly confederate-lovin' notification module that imparts only a constant (and small) performance penalty when the Interpreter (or any other object) fires an event for which there are no registered observers. Of course, the same notificaiton-enabled Interpreter can then be used in frontends that require notifications, thus saving the IPython project from a nasty civil war. + + 3. Barry is wrting a frontend for the IPython project. Because Barry's front end is the *new hotness*, it uses an asynchronous event model to communicate with a Twisted engineservice that communicates with the IPython Interpreter. Using the IPython.kernel.notification module, an asynchronous wrapper on the IPython.kernel.core.notification module, Barry's frontend can register for notifications from the interpreter that are delivered asynchronously. Even if Barry's frontend is running on a separate process or even host from the Interpreter, the notifications are delivered, as if by dark and twisted magic. Just like Dwight's frontend, Barry's frontend can now recieve notifications of e.g. writing to stdout/stderr, opening/closing an external file, an exception in the executing code, etc. \ No newline at end of file