[Python-ideas] for/except/else syntax
Rob Cliffe
rob.cliffe at btinternet.com
Wed Oct 7 11:24:56 CEST 2009
I'm coming to this debate rather late but .....
I did find the for ... else syntax confusing when I learned Python, and I
still do a little.
I would favour keeping for-loops exactly the same except allowing a more
intelligible keyword instead of 'else', e.g.
'ifnobreak'. Then moving towards deprecating and ultimately forbidding the
use of 'else'.
Rob Cliffe
----- Original Message -----
From: "Arnaud Delobelle" <arnodel at googlemail.com>
To: "Yuvgoog Greenle" <ubershmekel at gmail.com>
Cc: <python-ideas at python.org>
Sent: Wednesday, October 07, 2009 10:15 AM
Subject: Re: [Python-ideas] for/except/else syntax
2009/10/7 Yuvgoog Greenle <ubershmekel at gmail.com>:
> I don't like your "except" and "else" only because it's not obvious
> when they execute.
>
> btw your example breaks the current "for..else" search idiom. C,
> suite_if_loop_is_not_broken, should be labelled
> suite_if_loop_is_not_broken_and_not_empty in your example code.
>
> As I understand it, pythoneers need a way to know what happened with a
> previous loop. Did it break? Did it execute at all? The answer to both
> questions is either True or False and developers need these answers
> only after the loop finished. If python wasn't in over it's head with
> reserved words I would suggest adding "loop":
>
> for i in SEQ:
> A
> if not loop.broke:
> C # suite_if_loop_is_not_broken
> elif loop.empty:
> B # suite_if_loop_body_is_not_executed
>
> For optimization I would suggest the "loop" variable only be
> instantiated if it's referenced. Also, there may be better names for
> "loop", "broke" and "empty".
>
> Two drawbacks:
> 1. python's in over it's head with reserved words.
> 2. developers might want to use the "loop" variable a mile down from
> the loop which would be ugly but their fault.
>
> I'm writing a summary of the previous for/else thread and hope that by
> the time I finish that (a week+), someone will invent a readable,
> low-cost syntax (optional but awesome if it can handle all 4:
> break/not break/empty/not empty).
Here's an idea with current syntax (python < 3):
class Loop(object):
def __init__(self, iterable):
self.iterable = iterable
def __iter__(self):
self.broken = True
self.empty = True
for i in self.iterable:
self.empty = False
yield i
self.broken = False
# Example:
for string in 'spam', 'bot', '':
loop = Loop(string)
for i in loop:
if i == 'a':
break
print repr(string), ':'
if loop.broken: print 'broken',
if loop.empty: print 'empty',
print
# Output:
'spam' : broken
'bot' :
'' : empty
--
Arnaud
_______________________________________________
Python-ideas mailing list
Python-ideas at python.org
http://mail.python.org/mailman/listinfo/python-ideas
More information about the Python-ideas
mailing list