All pastes #737954 Raw Edit

Thread proxy class decorator

public python v1 · immutable
·published 2007-10-15 21:41 UTC
rendered paste body
def threaded_proxy(klass):        class proxytype(object):                __doc__ = klass.__doc__                @wraps(klass.__init__)                def __init__(self, *args):                        self.input, self.output = Queue(), Queue()                        db_prog = Thread(target = self._run, args = (self.input, self.output, args, klass))                        db_prog.setDaemon(True)                        db_prog.start()                @staticmethod                def _run(input, output, args, klass):                        instance = klass(*args)                        while True:                                command = input.get()                                try:                                        output.put(getattr(instance, command[0])(*command[1:]))                                except Exception, e:                                        output.put(e)                def __getattr__(self, key):                        def wrapper(*args):                                self.input.put((key,) + args)                                results = self.output.get()                                if isinstance(results, Exception):                                        raise results                                else:                                        return results                        return wrapper        proxytype.__name__ = klass.__name__        return proxytype