[Python-Dev] generator comprehension syntax, was: accumulator display syntax

Aahz aahz at pythoncraft.com
Fri Oct 17 23:54:46 EDT 2003


On Fri, Oct 17, 2003, Raymond Hettinger wrote:
> [GvR]
>>
>> I'd just like to pipe into this discussion saying that while Peter
>> Norvig's pre-PEP is neat, I'd reject it if it were a PEP; the main
>> reason that the proposed notation doesn't return a list.  I agree that
>> having generator comprehensions would be a more general solution.  I
>> don't have a proposal for generator comprehension syntax though, and
>> [yield ...] has the same problem.
> 
> Is Phil's syntax acceptable to everyone?
> 
>      (yield:  x*x for x in roots)

I'm not sure.  Let's try it out:

    for square in (yield: x*x for x in roots):
        print square

That doesn't look *too* bad.  Okay, how about this:

    def grep(pattern, iter):
        pattern = re.compile(pattern)
        for item in iter:
            if pattern.search(str(item)):
                yield item

    for item in grep("1", (yield: x*x for x in roots) ):
        print item

Now that looks disgusting.  OTOH, I doubt any syntax for a generator
comprehension could improve that.  On the gripping hand, I'm concerned
that we're going in Lisp's direction with too many parens.  At least
with the listcomp you have more of a visual cue:

    for item in grep("1", [x*x for x in roots] ):

<shrug>
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan



More information about the Python-Dev mailing list