[Python-Dev] decorate-sort-undecorate

Peter Norvig pnorvig at google.com
Thu Oct 16 01:04:41 EDT 2003


Yes, you're right -- with generator comprehensions, you can have
short-circuit evaluation via functions on the result, and you can get
at both original element and some function of it, at the cost of
writing f(x), x.  So my proposal would be only a small amount of
syntactic sugar over what you can do with generator comprehensions.
(But you could say the same for list/generator comprehensions over raw
generators.)

-Peter Norvig


On Wed Oct 15 18:36:44 PDT 2003, Phillip J. Eby <pje at telecommunity.com> wrote:
> At 05:27 PM 10/15/03 -0700, Peter Norvig wrote:
> >As it turns out, I have a proposed syntax for something I call an
> >"accumulation display", and with it I was able to implement and test a
> >SortBy in about a minute.  It uses the syntax
> >
> > >>> [SortBy: abs(x) for x in (-2, -4, 3, 1)]
> >[1, -2, 3, -4]
> >
> >where SortBy is an expression (in this case an identifier bound to a
> >class object), not a keyword.  Other examples of accumulation displays
> >include:
> >
> >     [Sum: x*x for x in numbers]
> >     [Product: Prob_spam(word) for word in email_msg]
> >     [Min: temp(hour) for hour in range(24)]
> >     [Top(10): humor(joke) for joke in jokes]
> >     [Argmax: votes[c] for c in candidates]
> 
> +0.  You can do any of these with a function, if you're willing to let the
> entire list be created, and put any needed parameters in as a tuple, e.g.:
>
> Top(10, [(humor(joke),joke) for joke in jokes])
>
> So, if we had generator comprehensions, the proposed mechanism would be
> unnecessary.  Also, note that [] implies the return value is a list or
> sequence of some kind, when it's not.
>
> IMO, it would really be better to have some kind of generator comprehension
> to make inline iterator creation easy, and then put the function or class
> or whatever outside the generator comprehension.  Then, it's clear that
> some function is being applied to a sequence, and that you should look to
> the function to find out the type of the result, e.g.:
>
> Top(10, [yield humor(joke),joke for joke in jokes])
>
>



More information about the Python-Dev mailing list