[Python-Dev] [rfc] map enhancement

Duncan Booth duncan@rcp.co.uk
Tue, 18 Feb 2003 13:22:26 +0000


[posted and mailed]

Ludovic Aubry <Ludovic.Aubry@logilab.fr> wrote in 
news:20030218111844.GA10112@logilab.fr:

> Using map you always end up using lambda functions to pass constant
> arguments to the mapping function like this:
> 
> map( lambda x,y=K: f(x,y), L )

You can also write this as:

    map(lambda x: f(x,K), L)

which is arguably cleaner although these days I would probably use a list 
comprehension.

> 
> What I propose in this patch is to have map recognize its keyword
> arguments like this:
> 
> map( f, L , y=K )
> 
> The result would be:
> def map( f, L, **kw ): # accepts only one list for simplicity
>    l=[]
>    for i in L:
>       l.append( f(i,**kw) )
>    return l

Or in the general case:

def map(f, *L, **kw):
	return [ f(*i, **kw) for i in L]

> 
> While it doesn't solve every problem (passing a value to the first arg)
> it could help remove many uses of lambda functions.
> 
Have you looked at any code using map to see what proportion of calls this 
would help. In particular how often do all the fixed arguments match this 
pattern so they could be passed as keywords?

I do have a problem with this. It looks as though it ought to work in some 
situations where it doesn't. For example, searching my lib directory for 
occurences of map, I only found one place where it looks as though this new 
form could be used. That is in win32comext\mapi\mapiutil.py which contains:

    return map(lambda(v): v[1], data)

It appears as though you ought to be able to write this as:

   return map(operator.getitem, data, b=1)

except that operator.getitem, in common with many builtin functions doesn't 
accept any keyword arguments.

This is a pity as it cripples most of the situations where you might 
otherwise want to use this. e.g. add a constant to elements of a list, or 
multiply by a constant.

-- 
Duncan Booth                                             duncan@rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?