lambda closure question

Karl Anderson kra at monkey.org
Tue Feb 22 17:47:27 EST 2005


"Ted Lilley" <ted.lilley at gmail.com> writes:

> What I want to do is pre-load functions with arguments by iterating
> through a list like so:
> 
> >>>class myclass:
> ...    pass
> >>>def func(self, arg):
> ...    print arg
> >>>mylist = ["my", "sample", "list"]
> >>>for item in mylist:
> ...    setattr(myclass, item, lamdba self: func(self, item))

I just found myself doing something similar to deal with unittest.py's
test loaders/runners, which have to be able to find attributes on a
class before the class is instantiated.

def addItemStateTransTest(klass):
    """
    For each item generator and transition test, add a method to klass
    to test that combo.
    """
    for ig_name in klass.item_generators:
       for tt_name in klass.transition_tests.keys():
           test_name = "test" + ig_name + tt_name
           test_fun = (lambda self,
                       ig_name=ig_name, tt_name=tt_name:
                       self.doTestItemStateTrans(ig_name, tt_name))
           setattr(klass, test_name, test_fun)

-- 
Karl Anderson      kra at monkey.org           http://monkey.org/~kra/



More information about the Python-list mailing list