Does Python have any kind of 'messaging'?

Josiah Carlson jcarlson at uci.edu
Mon May 24 19:42:59 EDT 2004


> I used to like Objective-C and Gnustep, but I gave up for lack of
> support and recognition of the language/platform under Unix.  But it
> did offer NSNotifications, a basic message class that could be posted
> and received by all subscribers.  Other than global variables used to
> share data across threads, does Python have anything similar?

No, but you can write one yourself quite easily, depending on the 
semantics of your messaging system.

  - Josiah


import threading

channels = {}
lock = threading.RLock()

def subscribe(id, funct, channel):
     lock.acquire()
     if channel in channels:
         channels[channel][id] = funct
     else:
         channels[channel] = {id:funct}
     lock.release()

def unsubscribe(id, channel):
     lock.acquire()
     if channel in channels:
         try:
             del channels[channel][id]
         except KeyError:
             pass
     lock.release()

def post(channel, message):
     lock.acquire()
     if channel in channels:
         for funct in channels[channel].itervalues():
             funct(message)
     lock.release()



More information about the Python-list mailing list