Wednesday, April 7, 2010

Python - event programming example

# Event programming in python

# Python doesn't have a standard 'only' way
# of doing events.  You can create your own
# pythonic events like so.
#

# In the example you'll notice that the Musician
# handles all the recieved events.  You could
# have just as easily created specific event
# handlers for the reacting classes.  Whatever

# makes sense for your application is good.
# Python is flexible!
#
# This would be a way that
# python could implement events or delegates.

import time

# Important class that will raise events
class Orchestrator(object):
    def __init__(self):
        # You'll notice that the events instances

        # of the subscribers are stored in these
        # lists.  Having a list allows multiple
        # subscribers to the event.
        self.armsRaise = []
        self.pointsAtMe = []
    def subscribeToArmRaiseEvent(self, event):
        # we append the instance methods to the

        # event lists
        self.armsRaise.append(event)
    def subscribeToPointsAtMeEvent(self, event):
        # we append the instance methods to the
        # event lists

        self.pointsAtMe.append(event)
    def raiseArmRaiseEvent(self):
        # iterating through the lists we call
        # each of the instance methods
        for i in self.armsRaise:
            i("Arms Raised")
    def raisePointsAtMeEvent(self):
        # iterating through the lists we call

        # each of the instance methods
        for i in self.pointsAtMe:
            i("Points at me")
    def raiseArms(self):
        self.raiseArmRaiseEvent()
    def pointAtMusician(self):
        self.raisePointsAtMeEvent()


# class that reacts to events
class Musician(object):
    def __init__(self, name):
        self.name = name
    def receiveEvent(self, msg):
        if msg == "Arms Raised":
            print self.name + " hold up instrument"

        if msg == "Points at me":
            print self.name + " play instrument"

# players

o = Orchestrator()
m = Musician("trumpet")
m2 = Musician("clarinet")

# Subscribe to the Orchestrator events:
# We're really just assigning instance methods
# of our Musician objects to the Orchestra object.

o.subscribeToArmRaiseEvent(m.receiveEvent)
o.subscribeToPointsAtMeEvent(m.receiveEvent)
o.subscribeToArmRaiseEvent(m2.receiveEvent)
o.subscribeToPointsAtMeEvent(m2.receiveEvent)

# Concert begins
o.raiseArms()
# ... other actions and events
# represented by:
print "do bee doo be dooo be do do do"

time.sleep(4)
# finally gets to your part of the song
o.pointAtMusician()

# my output:
#   trumpet hold up instrument
#   clarinet hold up instrument

#   do bee doo be dooo be do do do
#   trumpet play instrument
#   clarinet play instrument


1 comment: