Python's war on lambda

2011-11-18

When reading documentation on defaultdict, I saw this example:

def constant_factory(value):
    return itertools.repeat(value).next
d = defaultdict(constant_factory('<missing>'))
d.update(name='John', action='ran')
'%(name)s %(action)s to %(object)s' % d

What is it? Argument to defaultdict should be a constant function, such that when called without arguments it returns a default value. Well, is itertools.repeat(value).next the True Python Way to write constant functions?

What happened to:

Simple is better than complex.
Flat is better than nested.
Readability counts.
If the implementation is hard to explain, it's a bad idea.

As for me, I find lambda: value much more readable, simpler, flat and easier to explain:

d = defaultdict(lambda: "<missing>")
d.update(name='John', action='ran')
'%(name)s %(action)s to %(object)s' % d

Funny, but it is seems to be equally fast:

In [44]: dcf = defaultdict(constant_factory(42))

In [45]: %timeit -n1 for i in xrange(100000): dcf[i]
1 loops, best of 3: 12.5 ms per loop

In [46]: dlambda = defaultdict(lambda: 42)

In [47]: %timeit -n1 for i in xrange(100000): dlambda[i]
1 loops, best of 3: 12.4 ms per loop

Is there a reason not to use lambda?