Curried class methods?

Antoon Pardon apardon at forel.vub.ac.be
Thu Aug 17 07:51:35 EDT 2006


On 2006-08-17, Scott Lamb <srlamb at gmail.com> wrote:
> I'm trying to dynamically generate class methods which have access to
> some state passed in at creation time. (Basically as a workaround to
> twisted's trial not having a way to dynamically add stuff. Plain
> unittest seems to have TestSuite, but the trial runner doesn't know
> about it.)
>
> My first attempt might better illustrate this -
>
>     class Foo:
>         def generalized(self, ctx):
>             print 'my ctx is %r' % ctx
>
>     for i in ['a','b','c']:
>         setattr(Foo, i, lambda self: self.generalized(i))
>
>     foo = Foo()
>     foo.a()
>     foo.b()
>     foo.c()
>
> but this prints "my ctx is c" three times; I'd hoped for a, b, c, of
> course. After reading
><http://mail.python.org/pipermail/python-list/2004-July/229478.html>, I
> think I understand why this is - "i" doesn't actually get added to each
> new function's context; they just reference the global one. Even if I
> do this:

Try this instead as the for loop

    for i in ['a','b','c']:
        setattr(Foo, i, lambda self, a=i: self.generalized(a))

-- 
Antoon Pardon



More information about the Python-list mailing list