[Python-ideas] Variations on a loop

Bruce Leban bruce at leapyear.org
Fri Aug 29 19:26:05 CEST 2008

On Fri, Aug 29, 2008 at 6:19 AM, Mathias Panzenböck <
grosser.meister.morti at gmx.net> wrote:

> Bruce Frederiksen wrote:
> > We already have statements that only apply within loops (break and
> > continue), how about some expressions that only apply in for loops:
> > 'last' and 'empty':
> I don't know. I don't like either. What about named loops/loop objects?
> Using
> this you have no need for new keywords:
> myloop = for x in items:
>        result += str(x)
>        if not myloop.last:
>                result += ', '
> if myloop.empty:
>        result = 'no data'

This is interesting. I don't like the fact that you have the loop variable
scope extending past the end of the loop and it's not clear what we can do
with that. It occurs to me that we can do something like this without
changes to the language but it's clumsy:

for x in funky(items):
    result += str(x.value)
    if not x.last():
        result += ', '
    if x == funky_empty:
        result = 'no data'

> However, how to calculate the last property for generators where it might
> depend
> on some side effects if it's really the last item?

 Note that I wrote x.last() not x.last: when you check last, it pre-fetches
the next value. That's not an issue in the above code but could be in other
cases, so you have to be careful when you use it.

This could also provide other things like automatic counting of loop

for x in funky(items):
    foo(x.index, x.value)

It wouldn't provide the ability to do nested breaks and continues which I'd
like to see.

--- Bruce
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20080829/fd311c73/attachment.html>

More information about the Python-ideas mailing list