[Python-ideas] Add "while" clauses to generator expressions
Gerald Britton
gerald.britton at gmail.com
Sun Jan 11 00:20:40 CET 2009
Hmmm. I can't really see what you are saying. Your example doesn't
quite get the intention. The "while" clause in the example would
translate like this:
def gen():
for i in range(100):
if i <= 50:
yield i
else:
break
Also, I think that for a new python user,
(n for n in range(100) while n*n < 50)
is easier to understand and use than:
(n for n in takewhile(lambda n:n*n < 50, range(100)))
My proposed version is shorter (less chance for typos), has one less
set of parentheses (always a good thing) and reads naturally. Also,
it is directly analogous to:
(n for n in range(100) if n*n < 50)
except that the "while" version stops when n reaches 8. The "if"
version doesn't stop until n reaches 99.
On Sat, Jan 10, 2009 at 5:45 PM, Steven Bethard
<steven.bethard at gmail.com> wrote:
> [Fixing the top-posting. Note that only Guido is allowed to top-post
> around here. ;-)]
>
> On 1/10/09, Steven Bethard <steven.bethard at gmail.com> wrote:
>> I think this could end up being confusing. Current generator
>> expressions turn into an equivalent generator function by simply
>> indenting the clauses and adding a yield, for example:
>>
>> (i for i in range(100) if i % 2 == 0)
>>
>> is equivalent to:
>>
>> def gen():
>> for i in range(100):
>> if i % 2 == 0:
>> yield i
>>
>> Now you're proposing syntax that would no longer work like this.
>> Taking your example:
>>
>> (i for i in range(100) while i <= 50)
>>
>> I would expect this to mean:
>>
>> def gen():
>> for i in range(100):
>> while i <= 50:
>> yield i
>
> On Sat, Jan 10, 2009 at 2:34 PM, Gerald Britton
> <gerald.britton at gmail.com> wrote:
>> I guess I don't think it would be confusing. On the contrary, I
>> believe that the expressions would read naturally and be a nice
>> simplification. Of course it won't work just like "if" but that is
>> just the point! I can (and do) accomplish the same thing with
>> "takewhile", but if the same thing can be sone with a little addition
>> to the generator expression, why not do it?
>
> I'm probably just repeating myself here, but the reason not to do it
> is that the current generator expressions translate almost directly
> into the corresponding generator statements. Using "while" in the way
> you've suggested breaks this symmetry, and would make Python harder to
> learn.
>
> Steve
> --
> I'm not *in*-sane. Indeed, I am so far *out* of sane that you appear a
> tiny blip on the distant coast of sanity.
> --- Bucky Katt, Get Fuzzy
>
More information about the Python-ideas
mailing list