Why functional Python matters
Jack Diederich
jack at performancedrivers.com
Tue Apr 15 22:23:22 EDT 2003
On Tue, Apr 15, 2003 at 08:45:37PM -0400, Jp Calderone wrote:
> reduce(int.__add__, [1, 2, 3])
>
> Unfortunately, this breaks when ints get promoted to longs, because you
> can't pass longs to int.__add__!
Or when the passed in list is empty.
Why is the 3rd argument to reduce optional again?
>
> map(ClassObj.method, [x, y, z])
>
> works, so long as x, y, and z are instances of ClassObj. But if they are
> instances of different types, all of which merely happen to implement
> method, you're out of luck! This is resolved with list comprehensions:
>
> [i.method(foo) for i in [x, y, z]]
>
> But what I'd like to see is a way to do:
>
> map(message("method", foo), [x, y, z])
>
> Of course, you could easily implement this as:
>
> def message(name, *args, **kwarg):
> return lambda o: getattr(o, name)(*args, **kwargs)
>
> But this is stupendously inefficient. It'd be really great if there were
> some built-in MessageType that could be used this way and also managed to
> carry out the work in an efficient manner.
this adds 3 extra function calls, 1 for message(), 1 for lambda, and 1 for
the getattr.
doing plane-jane
map(lambda x:x.method(foo), [x, y, z])
just has one extra level of function call overhead and does what you want
I was a little disapointed that the implementaion in bltinmodule.c doesn't
special case lambdas but instead does a regular function call. I don't think
it is possible to change the lambda since they are anonymous, so they could be
speical cased like list comps (which generate the bytecode for a for loop
during compile)
If lambdas were special-cased in this way the message("method", foo) could
only be _as efficient_ as lambdas even if it were made as core a part of the
language as list comps. And the message() syntax is harder to read to boot.
-jack
More information about the Python-list
mailing list