problem with closure arguments and *args in mock object

Peter Otten __peter__ at web.de
Fri Nov 7 23:07:24 CET 2003


John J. Lee wrote:

> I forgot to say, I'm trying to do this with 1.5.2.  Is this possible?
> Any ideas for best alternative if not?

The following will most probably not work as I have zero experience with
Python < 2.x.

class Method:
    def __init__(self, instance, name):
        self.instance = instance
        self.name = name
    def __call__(self, *args):
        apply(self.instance.handle, ((self.name,) + args,))

class Test:
    def __init__(self):
        self.log = []
    def handle(self, args):
        self.log.append(args)
    def define(self, methods):
        for name in methods:
            setattr(self, name, Method(self, name))

t = Test()
t.define("alpha beta gamma".split())

t.alpha("entteufelter")
t.beta("nu")
t.gamma(1,2,3,4,5)

for record in t.log:
    print record

The last resort would probably be code generation, but I'm sure someone who
has been around longer than me will come up with a better idea.


Peter




More information about the Python-list mailing list