[docs] [issue20606] Operator Documentation Example doesn't work

Gareth Rees report at bugs.python.org
Wed Feb 12 13:38:32 CET 2014

Gareth Rees added the comment:

The failing example is:

    d = {}
    keys = range(256)
    vals = map(chr, keys)
    map(operator.setitem, [d]*len(keys), keys, vals)   

which works in Python 2 where map returns a list, but not in Python 3 where map returns an iterator.

Doc/library/operator.rst follows the example with this note:

    .. XXX: find a better, readable, example

Additional problems with the example:

1. It's poorly motivated because a dictionary comprehension would be simpler and shorter:

    d = {i: chr(i) for i in range(256)}

2. It's also unclear why you'd need this dictionary when you could just call the function chr (but I suppose some interface might require a dictionary rather than a function).

3. To force the map to be evaluated, you need to write list(map(...)) which allocates an unnecessary list object and then throws it away. To avoid the unnecessary allocation you could use the "consume" recipe from the itertools documentation and write collections.deque(map(...), maxlen=0) but this is surely too obscure to use as an example.

I had a look through the Python sources, and made an Ohloh Code search for "operator.setitem" and I didn't find any good examples of its use, so I think the best thing to do is just to delete the example.


nosy: +Gareth.Rees

Python tracker <report at bugs.python.org>

More information about the docs mailing list