### Navigation

- index
- modules |
- next |
- previous |
- Phatch 0.2 documentation »
- other »

# pubsub

This module provides a publish-subscribe component that allows listeners to subcribe to messages of a given topic. Contrary to the original wxPython.lib.pubsub module (which it is based on), it uses weak referencing to the subscribers so the lifetime of subscribers is not affected by Publisher. Also, callable objects can be used in addition to functions and bound methods. See Publisher class docs for more details.

Thanks to Robb Shecter and Robin Dunn for having provided the basis for this module (which now shares most of the concepts but very little design or implementation with the original wxPython.lib.pubsub).

The publisher is a singleton instance of the PublisherClass class. You access the instance via the Publisher object available from the module:

    from wx.lib.pubsub import Publisher
    Publisher().subscribe(...)
    Publisher().sendMessage(...)
    ...

Author: | Oliver Schoenborn
Since: | Apr 2004
Version: | $Id: pubsub.py,v 1.8 2006/06/11 00:12:59 RD Exp $
Copyright: | (c) 2004 Oliver Schoenborn
License: | wxWidgets

class `other.pubsub.``Message`(topic, data)

  A simple container object for the two components of a message: the topic and the user data. An instance of Message is given to your listener when called by Publisher().sendMessage(topic) (if your listener callback was registered for that topic).

class `other.pubsub.``PublisherClass`(singletonKey)

  The publish/subscribe manager. It keeps track of which listeners are interested in which topics (see subscribe()), and sends a Message for a given topic to listeners that have subscribed to that topic, with optional user data (see sendMessage()).

  The three important concepts for Publisher are:

  - listener: a function, bound method or callable object that can be called with one parameter (not counting ‘self’ in the case of methods). The parameter will be a reference to a Message object. E.g., these listeners are ok:

        class Foo:
            def __call__(self, a, b=1): pass # can be called with only one arg
            def meth(self,  a):         pass # takes only one arg
            def meth2(self, a=2, b=''): pass # can be called with one arg

        def func(a, b=''): pass

        Foo foo
        Publisher().subscribe(foo)           # functor
        Publisher().subscribe(foo.meth)      # bound method
        Publisher().subscribe(foo.meth2)     # bound method
        Publisher().subscribe(func)          # function

    The three types of callables all have arguments that allow a call with only one argument. In every case, the parameter ‘a’ will contain the message.

  - topic: a single word, a tuple of words, or a string containing a set of words separated by dots, for example: ‘sports.baseball’. A tuple or a dotted notation string denotes a hierarchy of topics from most general to least. For example, a listener of this topic:

        ('sports','baseball')

    would receive messages for these topics:

        ('sports', 'baseball')                 # because same
        ('sports', 'baseball', 'highscores')   # because more specific

    but not these:

         'sports'      # because more general
        ('sports',)    # because more general
        () or ('')     # because only for those listening to 'all' topics
        ('news')       # because different topic

  - message: this is an instance of Message, containing the topic for which the message was sent, and any data the sender specified.

  Note : | This class is visible to importers of pubsub only as a Singleton. I.e., every time you execute ‘Publisher()’, it’s actually the same instance of PublisherClass that is returned. So to use, just do’Publisher().method()’.

  `getAssociatedTopics`(listener)

    Return a list of topics the given listener is registered with. Returns [] if listener never subscribed.

    Attention : | when using the return of this method to compare to expected list of topics, remember that topics that are not in the form of a tuple appear as a one-tuple in the return. E.g. if you have subscribed a listener to ‘topic1’ and (‘topic2’,’subtopic2’), this method returns: associatedTopics = [(‘topic1’,), (‘topic2’,’subtopic2’)]

  `getDeliveryCount`()

    How many listeners have received a message since beginning of run

  `getMessageCount`()

    How many times sendMessage() was called since beginning of run

  `isSubscribed`(listener, topic=None)

    Return true if listener has subscribed to topic specified. If no topic specified, return true if subscribed to something. Use topic=getStrAllTopics() to determine if a listener will receive messages for all topics.

  `isValid`(listener)

    Return true only if listener will be able to subscribe to Publisher.

  `sendMessage`(topic='', data=None, onTopicNeverCreated=None)

    Send a message for given topic, with optional data, to subscribed listeners. If topic is not specified, only the listeners that are interested in all topics will receive message. The onTopicNeverCreated is an optional callback of your choice that will be called if the topic given was never created (i.e. it, or one of its subtopics, was never subscribed to by any listener). It will be called as onTopicNeverCreated(topic).

  `subscribe`(listener, topic='')

    Subscribe listener for given topic. If topic is not specified, listener will be subscribed for all topics (that listener will receive a Message for any topic for which a message is generated).

    This method may be called multiple times for one listener, registering it with many topics. It can also be invoked many times for a particular topic, each time with a different listener. See the class doc for requirements on listener and topic.

    Note :

    The listener is held by Publisher() only by weak reference. This means you must ensure you have at least one strong reference to listener, otherwise it will be DOA (“dead on arrival”). This is particularly easy to forget when wrapping a listener method in a proxy object (e.g. to bind some of its parameters), e.g.:

        class Foo:
            def listener(self, event): pass
        class Wrapper:
            def __init__(self, fun): self.fun = fun
            def __call__(self, *args): self.fun(*args)
        foo = Foo()
        Publisher().subscribe( Wrapper(foo.listener) ) # whoops: DOA!
        wrapper = Wrapper(foo.listener)
        Publisher().subscribe(wrapper) # good!

    Note :

    Calling this method for the same listener, with two topics in the same branch of the topic hierarchy, will cause the listener to be notified twice when a message for the deepest topic is sent. E.g. subscribe(listener, ‘t1’) and then subscribe(listener, (‘t1’,’t2’)) means that when calling sendMessage(‘t1’), listener gets one message, but when calling sendMessage((‘t1’,’t2’)), listener gets message twice.

  `unsubAll`(topics=None, onNoSuchTopic=None)

    Unsubscribe all listeners subscribed for topics. Topics can be a single topic (string or tuple) or a list of topics (ie list containing strings and/or tuples). If topics is not specified, all listeners for all topics will be unsubscribed, ie. the Publisher singleton will have no topics and no listeners left. If onNoSuchTopic is given, it will be called as onNoSuchTopic(topic) for each topic that is unknown.

  `unsubscribe`(listener, topics=None)

    Unsubscribe listener. If topics not specified, listener is completely unsubscribed. Otherwise, it is unsubscribed only for the topic (the usual tuple) or list of topics (ie a list of tuples) specified. Nothing happens if listener is not actually subscribed to any of the topics.

    Note that if listener subscribed for two topics (a,b) and (a,c), then unsubscribing for topic (a) will do nothing. You must use getAssociatedTopics(listener) and give unsubscribe() the returned list (or a subset thereof).

  `validate`(listener)

    Similar to isValid(), but raises a TypeError exception if not valid

`other.pubsub.``getStrAllTopics`()

  Function to call if, for whatever reason, you need to know explicitely what is the string to use to indicate ‘all topics’.

`other.pubsub.``test`()

### Navigation

- index
- modules |
- next |
- previous |
- Phatch 0.2 documentation »
- other »