Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

Delegating Messages to Multiple Objects

Credit: Eduard Hiti

Problem

You need to multiplex messages (attribute requests) to several objects that share the same interface.

Solution

As usual, this task is best wrapped in a class:

import operator

# faster in Python 2.2, but we also handle any release from 2.0 and later
try: dict
except: from UserDict import UserDict as dict

class Multiplex(dict):
    """ Multiplex messages to registered objects """
    def _ _init_ _(self, objs=[]):
        dict._ _init_ _(self)
        for alias, obj in objs: self[alias] = obj

    def _ _call_ _(self, *args, **kwargs):
        """ Call registered objects and return results through another
        Multiplex. """
        return self._ _class_ _( [ (alias, obj(*args, **kwargs))
            for alias, obj in self.items(  ) ] )

    def _ _nonzero_ _(self):
        """ A Multiplex is true if all registered objects are true. """
        return reduce(operator.and_, self.values(  ), 1)

    def _ _getattr_ _(self, name):
        """ Wrap requested attributes for further processing. """
        try: return dict._ _getattr_ _(self, name)
        except:
            # Return another Multiplex of the requested attributes
            return self._ _class_ _( [ (alias, getattr(obj, name) )
                for alias, obj in self.items(  ) ] )

As usual, this module is also invokable as a script, and, when run that way, supplies a self-test (or, here, a demo/example):

if _ _name_ _ == "_ _main_ _": import StringIO file1 = StringIO.StringIO( ) file2 = StringIO.StringIO( ) delegate = Multiplex( ) delegate[id(file1)] = file1 delegate[id(file2)] = file2 assert not delegate.closed ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata