reduce() anomaly?

Alex Martelli aleax at aleax.it
Wed Nov 5 19:23:59 CET 2003


Stephen C. Waterbury wrote:

> This seems like it ought to work, according to the
> description of reduce(), but it doesn't.  Is this
> a bug, or am I missing something?

the latter.

> Python 2.3.2 (#1, Oct 20 2003, 01:04:35)
> [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> d1 = {'a':1}
>  >>> d2 = {'b':2}
>  >>> d3 = {'c':3}
>  >>> l = [d1, d2, d3]
>  >>> d4 = reduce(lambda x, y: x.update(y), l)

the update method returns None.

> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
>    File "<stdin>", line 1, in <lambda>
> AttributeError: 'NoneType' object has no attribute 'update'

right.

>  >>> d4 = reduce(lambda x, y: x.update(y), l, {})
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
>    File "<stdin>", line 1, in <lambda>
> AttributeError: 'NoneType' object has no attribute 'update'

same issue.

If you want to abuse reduce at all costs for this purpose,
reduce(lambda x, y: x.update(y) or x, l) might work.


Alex





More information about the Python-list mailing list