"also" to balance "else" ?

Ron Adam rrr at ronadam.com
Wed Jun 15 18:56:03 EDT 2005


Terry Hancock wrote:
> On Wednesday 15 June 2005 03:57 am, Fredrik Lundh wrote:
> 
>>where your "abnormal behaviour" is, of course, the expected
>>behaviour.  if you insist on looking at things the wrong way,
>>things will look reversed.
>  
> Unfortunately, the converse is true, too: no matter how twisted
> an idea is, you can make it seem logical with the right point
> of view. ;-)
> 
> I think the OP is correct in saying that for-else is non-intuitive.

Although it took me a while to verbalize it, My motivation for 
suggesting 'also' was/is that it might enable writing code that better 
matches the context it's written in.  Code that's more intuitive and as 
a result more readable.

There are 4 possible outcomes to a loop.

1. Not Entered.  Nothing done.  (current possible for-else behavior)

2. Entered.  Some loops may have completed.

3. Not finished.  (break) Some loops may have completed.

4. Finished (no break) All possible loops completed.
      (current for-else behavior)

(This doesn't include exit by return statements.)


One possibility may be to use a keyword that parallels the except in 
try-except blocks which will accept a test designator. (building on your 
refernce to finally)

(This is probably a definite after 3k item I think, or more likely just 
academic discussion, but I enjoy that too.)

So use loop as the new keyword with the above conditions and have the 
else as the alternative to any of them.

(Feel free to suggest different words)


      for item in collection:
          if <condition>:
               print "item found"
               break
      loop Finished:
          print "item was not found."
          return


      for item in collection:
          if <condition>:
              print "bad item"
              break
      loop Finished:
          print "The Collection pass's the test"
      else:
          print "The Collection is invalid"


      for item in collection:
          <do something>
      loop NotEntred:
          print "The Collection was empty"


      for line in textbuffer:
          print line
      loop Entered:
          print time.date()
      else:
          print "The buffer was empty"


      while <condition>:
          <do something>
          if <condition>:
              break
      loop Entered:
          <do something>


I think these are sufficiently explicit as to avoid being non-intuitive. 
  The endloop might be generalized into a endblock or endsuite statement 
possibly.  I'm not sure if that would have any uses's in the proposed 
"with" statements or not.  (?)

Regards,
Ron






More information about the Python-list mailing list