July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: Eduard Hiti
You need to multiplex messages (attribute requests) to several objects that share the same interface.
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 ...