1.5.2 for: else:

William Tanksley wtanksle at dolphin.openprojects.net
Thu Jul 29 22:40:42 EDT 1999


On Wed, 28 Jul 1999 16:38:24 -0500, Gordon McMillan wrote:
>William Tanksley wrote:
>> On Tue, 27 Jul 1999 21:43:00 -0500, Gordon McMillan wrote:

>[snip Billy's silly error and his entirely insufficient embarassment 
><wink>]

:)

>> However, you're wrong about the best way to detect a 2 in the list
>> using this style.  To steal the same example:

>> try:
>>  for x in [1,2,3]:
>>   print x
>>   if x == 2: raise neverMind
>>  print "modern else clause here"
>> except neverMind: print "found two"
>> else:
>>  print "another place to put the modern else clause"

>> Of course, by demonstrating both ways to do it, I'm making the code
>> more complex; but you can see that this solution solves the problem
>> quite elegantly.

>WIth an extra class, and 3 or 4 more lines of code, not to mention 
>treading on the toes of all who think exceptions should only be used 
>for exceptional conditions (or maybe it _is_ exceptional when 
>something you wrote works <1e3 wink>).

You don't need the extra class -- you can raise a string if somebody's
linecounting you.  But who really cares?  The result is pretty darn clear.
There are no common misconceptions to fight when you're writing or reading
it (I count three people who have posted to say nothing more than "gee,
that wasn't what I expected!" about the current behavior).  This code just
works!

And as for exceptions -- anyone who uses break together with else-loop but
shuns exceptions is in serious need of psychological help.  That's WAY
tweaked.  Exceptions are a wonderful tool; break is a useful hack.

Oh, and if you REALLY like the current behavior of else-loop, you can
still have it if else-loop were gone -- like this:

try:
 for x in list:
   if iffers(x): raise "no!"
   yadda(x)
except "no!": pass
else:
 twiddle()

That's two extra lines, and one level of nesting -- for the _exact_ same
functionality, only much more likely to be comprehended.

>> The place to use MY definition of 'else', OTOH, is when you're
>> building a structure during the iteration, but the result of an
>> empty loop is different than the initial value the variable has to
>> have when going through the loop.

>> Here you go.  This example might convert a Python list into a Lisp
>> tree-list -- but to imitate Lisp (okay, it's a toy problem, I'm
>> cheating) an empty list produces NIL ~= None.

>> var = Node(None,None)
>> for x in pyList:
>>   var.car = x
>>   var.cdr = Node()
>> else:
>>   var = None

>Not a Lisper, but isn't what you're doing better done thusly:

No no no!  Don't be silly -- I was giving an example of how my idea of
else should work.  I don't have time to design a system which NEEDS to be
done this way.

but-I-do-have-time-to-whine-about-something-that-isn't-going-to-change-ly
yr's,

-- 
-William "Billy" Tanksley




More information about the Python-list mailing list