Thoughts on PEP284

Stephen Horne $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk
Tue Sep 23 02:51:54 CEST 2003


Some more looping thoughts - this time on integer for loops...

There may be some hint towards PEP284 (integer for loops) in a review
of ideas from other languages, but I'm damned if i can figure it out.
I spent some time thinking about it and couldn't find anything that
would cover the issue.

All I came up with was the recognition that some other languages have
'for' and 'foreach' loops. But Python went down the route of using
'for' for looping over lists/iterators a long time ago. Maybe a new
keyword or combination could help, such as...

  for range i in 0 <= i < 10 :

or...

  for range 0 <= i < 10 :

or dropping the PEP284 concept in favor of something C based...

  for i yield i = 0; i < 10; i += 1 :

but I don't much like any of those, to be honest.


I did come up with something, though...

I doubt the need for exclusive ranges in integer for loops. I also
doubt the need for switching between different range systems
(inclusive, exclusive, half-open). IMO there is more confusion than
anything down those routes.

Although I haven't had problems with inclusive loops (Basic, Ada) my
preference is toward half-open loops if a choice needs to be made. And
it occurs to me that Python programmers do specify integer ranges in a
half-open way on a regular basis - when doing slicing on lists and
strings.

Perhaps the 'int' and 'long' types could support a slicing to generate
a list or iterator over the range?

If so, we could write...

  for i in int[0:10] :
    ...

If the syntax creates an iterator rather than a list, it could even be
used as follows...

  for i in long[0:] :
    ...
  break if <condition> :
    ...

We could have some basic in-step looping with...

  for i, j in zip(int[0:], int[len(list)-1::-1] :
    ...
  break if i > l :
    ...

but this is probably an argument against.

What would be good, however, is that it can be useful outside of
looping for free - list comprehensions, for instance...

  [i*i for i in int[0:10]]

It would need some slight restrictions compared with normal slicing
(it needs to know the value to start at, even if not where to stop)
but what the hell. At least I'm not going to be accused of trying to
turn Python into another language - AFAIK this slice-of-a-type idea is
original. This could be my first time being accused of trying to turn
Python into a language that doesn't exist yet, of course ;-)


-- 
Steve Horne

steve at ninereeds dot fsnet dot co dot uk




More information about the Python-list mailing list