[Python-ideas] Statements vs Expressions... why?
Cliff Wells
cliff at develix.com
Sun Sep 14 11:25:31 CEST 2008
On Sun, 2008-09-14 at 10:08 +0100, Arnaud Delobelle wrote:
> On 14 Sep 2008, at 09:44, Cliff Wells wrote:
> >
> > j = range(3)
> > for i in j: i # evaluates to []
> > for i in j: continue # evaluates to []
> > for i in j: continue i # evaluates to [0,1,2]
> >
> Let's not call it continue, but YIELD for now:
>
> for i in J: YIELD i
>
> Now this won't work for nested loops. E.g. in current python
>
> def flatten(I):
> for J in I:
> for j in J:
> yield j
>
> >>> '-'.join(flatten(['spam', 'eggs']))
> 's-p-a-m-e-g-g-s'
>
> Now say you want to write that inline with a for-expression:
>
> '-'.join(
> for J in I:
> for j in J:
> YIELD j
> )
>
> That won't work because the j's will be accumulated in the inner loop
> and the outer loop won't accumulate anything, therefore returning an
> empty iterable.
How about this way instead (since for-loop is now an expression):
'-'.join(
for j in ( for J in I: YIELD J ): YIELD j
)
> Now compare with the current syntax:
>
> '-'.join(j for J in I for j in J)
Certainly more clear and concise, but since (luckily for me this time)
we're maintaining backwards-compatibility, that form would still be
available.
Cliff
More information about the Python-ideas
mailing list