"also" to balance "else" ?

Ron Adam rrr at ronadam.com
Mon Jun 13 22:57:59 EDT 2005


Eloff wrote:
> My first reaction was that this is terrible, else clauses on loops are
> confusing enough. But if I think about it more, I'm warming up to the
> idea. Also/Else for loops is clear, symmetrical, and would be useful.
 >
> Reversing the meanign of else will break code, but it's not used that
> frequently, and it was a confusing thing to begin with, nothing wrong
> in breaking something (slowly!) if it was 'broken' to begin with.
> 
> Alifs look evil, I couldn't deduce the control flow very easily, but
> then they are a new idea. I'll keep an open mind on that one.

Yes, it's probably because it's new.  Alifs would be used where you want 
to test for multiple possible values, and need to respond differently 
depending on the values.  They probably wouldn't be used as often as elifs.

alifs is a way to string if's together as a group.  The following would 
be equivalent to if-alif-also-else.

didif = False
if val == condition1:
     didif = True
     BLOCK1
if val == condition2:
     didif = True
     BLOCK2
if val == condition3:
     didif = True
if didif:
     BLOCK3
else:
     BLOCK4


The if-alif-also-else version doesn't need the extra name to mark if any 
of the conditions were true.

if val == condition1:
     BLOCK1
alif val == condition2:
     BLOCK2
alif val == condition3:
     BLOCK3
also:
     BLOCK4
else:
     BLOCK5

But I think we will need to find some real use case's to make it 
convincing.


> I think the best thing would be to compare the also/else syntax to what
> identical functionality looks like in python now [hint to someone with
> more time than me right now ;)]. I'd vote for whichever is the more
> concise and readable of the two.
> 
> -Dan
> 

In cases of if-also,  the equivalent code needs an extra local variable 
and an additional if statement.

iftest = False
if <condition>:
     iftest = True
     BLOCK1
elif <condition>:
     iftest = True
     BLOCK2
if iftest:
     BLOCK3

This is the pattern that caused me to think of having an also.  I was 
parsing and formatting doc strings at the time, and also would allow it 
to become.

if <condition>:
     BLOCK1
elif <condition>:
     BLOCK2
also:
     BLOCK3

Which is much easier to read.


Ron



More information about the Python-list mailing list