Getting a set of lambda functions

Denis Kasak denis.kasak2718281828 at gmail.com
Sun May 25 18:36:49 EDT 2008


On Sun, May 25, 2008 at 1:43 PM, Martin Manns <mmanns at gmx.net> wrote:
 > Hi,
 >
 > I try to get a set of lambda functions that allows me executing each
 > function code exactly once. Therefore, I would like to modify the set
 > function to compare the func_code properties (or the lambda
 > functions to use this property for comparison).
 >
 > (The reason is that the real function list is quite large (> 1E5), there
 > are only few functions with non-equal code and the order of execution
 > is not important.)
 >
 > How can I achieve this?
 >
 > >>> func_strings=['x', 'x+1', 'x+2', 'x']
 > >>> funclist = [eval('lambda x:' + func) for func in func_strings]
 > >>> len(funclist)
 >  4
 > >>> len(set(funclist))
 >  4
 > >>> funclist[0].func_code == funclist[3].func_code
 >  True
 > >>> funclist[0] == funclist[3]
 >  False

Isn't this a bug? Shouldn't it be possible to create a set of
different lambda functions via a loop? At first I thought it was just
a quirk of list comprehensions, but the following example also yields
incorrect (or at least unintuitive) results:

 >>> spam = []
 >>> for i in range(10):
...   spam.append(lambda: i)
 >>> spam[0]()
9
 >>> spam[1]()
9

Manually creating the lambdas and appending them to a list works as
expected, naturally; I don't see a good reason why it wouldn't work
with a loop. Am I missing something?

--
Denis Kasak



More information about the Python-list mailing list