scoping problem with lambda

Courageous jkraska1 at san.rr.com
Fri Jun 2 21:59:37 EDT 2000


> class trying_it:
>     def __init__(self):
>         self.tmp = [[['a'],['one','two','three','four']],
>                 [['b'],['one','two','four','five']],
>                 [['c'],['one','two','three','six']],
>                 [['d'],['one','two','two','four']],
>                 [['e'],['one','ten','three','four']]]
> 
>         self.kformat = ['one','two','three','four']
> 
>     def try_it(self):
>         tmp2 = self.tmp[:]
>         for i in (0,2,3):
>             tmp2 = filter(lambda x:x[1][i] in (self.kformat[i],),tmp2)
>         return tmp2


Python lambdas don't have the lexical closure you might expect,
but you can build it. To wit:

             tmp2 = filter(lambda x,i=i,self=self:x[1][i] in (self.kformat[i],),tmp2)

% py test.py

[[['a'], ['one', 'two', 'three', 'four']], [['e'], ['one', 'ten', 'three', 'four']]]


C/



More information about the Python-list mailing list