[Python-Dev] Re: accumulator display syntax

Alex Martelli aleaxit at yahoo.com
Mon Oct 20 10:01:08 EDT 2003


On Monday 20 October 2003 03:22 pm, Nick Coghlan wrote:
   ...
> >>  sum of x*x for x in xvalues
> >>  average of g for g in grades
> >>  maximum of f(x, y) for x in xrange for y in yrange
> >>  top(10) of humour(joke) for joke in comedy
   ...
> > "from __future__ import").  It's SO beautiful, SO pythonic, the only
> > risk I can see is that we'd have newbie people coding:
> >     sum of the_values
> > rather than:
> >     sum(the_values)
> > or:
> >     sum of x for x in the_values
>
> Except, if it was defined such that you wrote:
>    sum of [x*x for x in the_values]
>
> then:
>    sum of the_values
>
> would actually be a valid expression, and Greg's examples would become:

Yes, you COULD extend the syntax from Greg's

    NAME 'of' listmaker

to _also_ accept

    NAME 'of' test

or thereabouts (in the terms of dist/src/Grammar/Grammar of course), I don't
think it would have any ambiguity.  As to whether it's worth it, I dunno.

>    sum of xvalues

Nope, he's summing the _squares_ --
      sum of x*x for x in xvalues
it says.

>    average of grades

Yes, this one would then work.

>    maximum of [f(x, y) for x in xrange for y in yrange]

Yes, you could put brackets there, but why?

>    top(10) of [humour(joke) for joke in comedy]

Ditto -- and it doesn't do the job unless the magic becomes even blacker.
top(N) is supposed to return jokes, not their humor values; so it needs to
get an iterable or iterator of (humor(joke), joke) PAIRS -- I think it would
DEFINITELY be better to have this spelled out, and in fact I'd prefer:

top(10, key=humour) of comedy

or

top(10, key=humour) of joke for joke in comedy

using the same neat syntax "key=<callable>" just sprouted by lists' sort 
method.

> Either way, that's some seriously pretty executable psuedocode he has
> happening! And a magic method "__of__" that takes a list as an argument
> might be enough to do the trick, too.

Agreed on the prettiness.  I would prefer to have the special method be 
defined to receive "an iterator or iterable" -- so we can maybe put together
a prototype where we just make and pass it a list, BUT keep the door open to
passing it an "iterator comprehension" in the future.  Or maybe make it always
an iterator (in the prototype we can just build the list and call iter on it 
anyway... so it's not any harder to get started playing with it).

Oh BTW, joining another still-current thread --

for x in sorted_copy of mylist:
    ...

now doesn't THAT read just wonderfully, too...?-)


Alex




More information about the Python-Dev mailing list