Saturday, September 27, 2008

Observer pattern for Python



The Observer pattern is mainly used to implement a distributed event handling system. The primary objective of this pattern is to provide a way to handle run-time one-to-many relationships between objects in a loosely coupled arrangement.

In this configuration, the Observable object doesn't know anything more about it's Observers than a very limited interface. The Observable needs to provide a wide interface for allowing other objects to gain access to it's current state.

The event from the observable object's point of view is called notification and the event from the observers' point of view is called update.


class Observable( object ):
def __init__( self, *args, **kwargs ):
super( Observable, self ).__init__( *args, **kwargs )
self.__dirty = False
self.__observers = weakref.WeakKeyDictionary( )

def attach_observer( self, obs ):
if obs not in self.__observers:
self.__observers[obs] = 1
return self

def detach_observer( self, obs ):
if obs in self.__observers:
del self.__observers[obs]
return self

def set_dirty( self, d ):
self.__dirty = d
return self.__dirty

def is_dirty( self ):
return self.__dirty

def notify_all( self ):
for observer in self.__observers.keys( ):
observer.observer_update( self )

def notify_check( self ):
if self.is_dirty( ):
self.notify_all( )
self.set_dirty( False )
attach_observer and detach_observer maintain the list of Observers that are interested in this object. After any change in state, notify_all should be called. If this state change is part of a larger transaction, the combination set_dirty and notify_check should be called.

If you're also using Stackless python, you may want to have notify_all use the event-loop mechanism we've previously discussed.

class Observer( object ):
def __init__(self, *args, **kwargs ):
pass

def observer_update( self, object ):
pass
The Observer object is very easy to implement. Really, only it needs observer_udpate defined since that method is called by Observable during notify_all. The observed object passes itself as the argument to observable_update so that the observer knows which of the objects it currently is observing has been updated.

NewNovelist Review




I stumbled across this software package during a google search on tools for writers. I bought it and installed it after doing some more research about it.

Even though I tend to be a "pantser" when it comes to writing, I went through the dialogs and screens. I won't make any grandiose claims about it, but I found that after I had spent a few hours following the wizards, I had a much better and firmer grasp of where I wanted my last project to end up.

It made me think about things like character arcs and other details of story development that I usually don't spend much time planning. While that tactic worked for me in the past, it was proving difficult on my last project -- the great swamp of the middle of the novel -- that using this software helped me plan my way past.

Its not going to turn you into a novelist without you doing the legwork, but if you really want to write a book and are willing to put in the work to do it, then NewNovelist will help you.

My Rating: A

Friday, September 26, 2008

Weekly Roundup

So, it's Friday, and here we go with a small handful of YouTube clips I watched this week:





Complete with bad-ass jazzy Samurai gonna kick yo butt music.



Yeah, I'm still digging the new Metallica album.

Thursday, September 25, 2008

Event-based Programming for Python


Oftentimes, you need to have objects that communicate with each other via events. This is a very useful setup, for example, in a GUI -- where these events represent things like mouse clicks, key strokes, or button presses. That's not what I developed these classes for, since I was more interested in simulating things and the event system seemed like the most natural fit, but the recipe is still relevant to other event handling needs.

We're going to build upon earlier discussions, most notably about Stackless event loops by adding in some concrete examples of using that recipe.

The Observer pattern strikes again, as I'm defining the relationship between the event generator and the event listener as one of Observable and Observer. We'll make use of the channel_processor function decorator described in Stackless event loops.

class EventObserver( object ):
def __init__( self, *args, **kwargs ):
super( EventObserver, self ).__init__( *args, **kwargs )

@channel_processor
def event_transieve( self, *args, **kwargs ):
evt = kwargs.get( 'data', None )
self.process_event( evt )

def process_event( self, event ):
pass

def event_notify( self, event ):
self.event_transieve( event )

This is straight-forward enough. The only trickery (if you could call it that) is in the event_transieve method. And all that does is take whatever is passed as the keyword argument data and call the method process_event. In this base class implementation, that function does nothing.

One bit of niftiness does occur, however, when the event_transieve method is invoked. Through the use of function decorators (and therefore transparent to the calling client) this method actually spans across tasklets, granting some semblance of concurrency.


class EventObservable( object ):
def __init__( self, *args, **kwargs ):
super( EventObservable, self ).__init__( *args, **kwargs )
self.__event_observers = weakref.WeakKeyDictionary( )
self.__events = [ ]

def attach_event_observer( self, obs, level=1 ):
if obs not in self.__event_observers:
self.__event_observers[obs] = level
return self

def detach_event_observer( self, obs ):
if obs in self.__event_observers:
del self.__event_observers[obs]
return self

@channel_processor
def dispatcher( self, *args, **kwargs ):
data = kwargs.get( 'data', None )
wlist = []
for key in self.__event_observers.keys( ):
val = self.__event_observers[key]
seok = SortableEventObserverKey( key, val )
heapq.heappush( wlist, seok )
while len( wlist ):
obs = heapq.heappop( wlist )
obs( evt )

def dispatch_event( self, event ):
self.dispatcher( event )
return event
Now, we can safely ignore the attach_event_observer and methods -- they only exist to implement the Observer pattern. The only method we really care about at the moment is dispatcher.

In this method we simply loop over all the currently registered observers, invoking (ultimately) their event_notify method. If you don't see how that happens, just be patient and wait until we look at the SortableEventObserverKey helper class and it's definition of the __call__ method.

class SortableEventObserverKey( object ):
def __init__( self, kval, weight, *args, **kwargs ):
super( SortableEventObserverKey, self ).__init__( *args, **kwargs )
self.__value = kval
self.__weight = weight

def __cmp__( self, other ):
return cmp( self.__weight, other.__weight )

def __call__( self, event ):
return self.__value.event_notify( event )

def __repr__( self ):
return "%s, %s" % ( self.__value, self.__weight )

Now, I hate that I had to throw something like that into the discussion. The helper class only exists to make the comparison functions easier when using the heap queue. For anyone unfamiliar with heaps, a heap ensures that the highest weighted object is at the front of the queue and will be the first one taken out of the structure.

class EventParticipant( EventObservable, EventObserver ):
def __init__( self, *args, **kwargs ):
super( EventParticipant, self ).__init__( *args, **kwargs )
event_manager = kwargs.get( "event_manager", "events" )
self.event_manager = pytypes.get_event_manager( event_manager )

def generate_event( self, event_type, *data, **kwargs ):
evt = self.event_manager.create_event( self, event_type, *data, **kwargs )
return self.dispatch_event( evt )

Here's the easy class to implement. It defines the EventParticipant, which is both the Observable and the Observer. This is, utlimately, the class that I extend for my simulations since my program domain requires for the objects to both generate events and be interested in other object's events. Simply extending from this class gives you that ability in a nice, clean, and concurrent fashion (or, at least as concurrent as Stackless gets you).

Wednesday, September 24, 2008

Things on my living room floor...

To continue with the theme of "Stuff in Steve's Apartment", I'm now going to survey items found in my living room. To qualify, they must in some way or another, be in contact with the floor (which, by the way, is a nice hardwood floor that just cries out for you to slide on when wearing socks).

1. Kramer electric guitar: I don't know the model number, as it was a gift from a friend when he was moving out of his ex-girlfriend's place. He didn't know how to play it very well, so he handed it off to me; not that I'm really any better at it. I know some scales, and a bunch of chords though. And I can play a mean "Bad to the Bone" and "Creeping Death". Yes, I know the songs aren't related to each other, but my musical tastes are all over the place. Rating: B+ (has an electrical fault in one of the pickups, so the sounds fades at times)

2. Yamaha FG720SL acoustic guitar: Got this one as a Christmas present. Originally a left-handed guitar, I restrung it as a right-handed guitar. I'm sure that's against some rule in the guitarist's rule book. On this I usually just exercise my knowledge of chords, and play "Horse with No Name" and/or "Wish You Were Here". I'm sure my neighbors are sick to death of those songs by now. Rating: A+

3. Peavey TKO 80 amplifier: Something else that my neighbors must really love. I try to keep the output level low. Really, I do. My daughter occasionally will play with the dials when I'm not paying attention though, and then, at some point, later I'll turn it on and it's reverb and distortion city. Rating: B+ (don't use it enough to get a higher rating)

4. La-z-boy Couch: I love this thing. The end seats recline. It's very comfortable, and I can fit on it when I lay on it and stretch out. Rating: A+

5. Dell PowerEdge 400SC: This is my web server, mail server, and FTP server. It runs Linux (an older version of Fedora actually) and a whole bunch of custom-build packages and programs. It's the outlet for my inner computer geek. Rating: A

Unlike with the stuff on my bookshelf, I didn't move these items in anyway before reviewing them -- some were too big (the couch) and others, well, moving them would have made writing this entry difficult (the Linux server).

Later in the week, I'll be reviewing stuff in my rerigerator. (I actually have to go food shopping first, as there's nothing to review at the moment.)