Dispatching operations to user-defined methods

Michele Simionato michele.simionato at gmail.com
Thu May 4 05:03:01 EDT 2006


Apparently Guido fell in love with generic functions, so (possibly)  in
future Python
versions you will be able to solve dispatching problems in in an
industrial strenght
way. Sometimes however the simplest possible way is enough, and you can
use
something like this :

class SimpleDispatcher(object):
    """A dispatcher is a callable object that looks in a "namespace"
    for callable objects and calls them with the signature

    ``<dispatcher>(<callablename>, <dispatchtag>, <*args>, <**kw>)``

    The "namespace" can be a module, a class, a dictionary, or anything
    that responds to ``getattr`` or (alternatively) to ``__getitem__``.

    Here is an example of usage:

>>> call = SimpleDispatcher(globals())

>>> def manager_showpage():
...    return 'Manager'

>>> def member_showpage():
...     return 'Member'

>>> def anonymous_showpage():
...     return 'Anonymous'

>>> call('showpage', 'anonymous')
'Anonymous'
>>> call('showpage', 'manager')
'Manager'
>>> call('showpage', 'member')
'Member'
    """
    def __init__(self, ns):
        self._ns = ns
    def __call__(self, funcname, classname, *args, **kw):
        try:
            func = getattr(self._ns, '%s_%s' % (classname, funcname))
        except AttributeError:
            func = self._ns['%s_%s' % (class




More information about the Python-list mailing list