"also" to balance "else" ?
Andrew Dalke
dalke at dalkescientific.com
Mon Jun 13 22:18:40 EDT 2005
Ron Adam wrote:
> It occurred to me (a few weeks ago while trying to find the best way to
> form a if-elif-else block, that on a very general level, an 'also'
> statement might be useful. So I was wondering what others would think
> of it.
> for x in <iteriable>:
> BLOCK1
> if <condition>: break # do else block
> also:
> BLOCK2
> else:
> BLOCK3
For this specific case you could rewrite the code in
current Python as
for x in <iterable>:
BLOCK1
if <condition>:
BLOCK3
break
else:
BLOCK2
In order for your proposal to be useful you would need an
example more like the following in current Python
for x in <iterable>:
...
if <condition>:
BLOCK3
break
...
if <condition>:
BLOCK3
break
else:
BLOCK2
That is, where "BLOCK3;break" occurs multiple times in
the loop. My intuition is that that doesn't occur often
enough to need a new syntax to simplify it.
Can you point to some existing code that would be improved
with your also/else?
> while <condition1>:
> BLOCK1
> if <condition2>: break # jump to else
> also:
> BLOCK2
> else:
> BLOCK3
>
> Here if the while loop ends at the while <condition1>, the BLOCK2
> executes, or if the break is executed, BLOCK3 executes.
which is the same (in current Python) as
while <condition>:
BLOCK1
if <condition2>:
BLOCK3
break
else:
BLOCK2
> In and if statement...
>
> if <condition1>:
> BLOCK1
> elif <condition2>:
> BLOCK2
> elif <condition3>:
> BLOCK3
> also:
> BLOCK4
> else:
> BLOCK5
>
> Here, the also block would execute if any previous condition is true,
> else the else block would execute.
That is ... funky. When is it useful?
One perhaps hackish solution I've done for the rare cases when
I think your proposal is useful is
while 1:
if <condition1>:
BLOCK1
elif <condition2>:
BLOCK2
elif <condition3>:
BLOCK3
else:
# couldn't do anything
break
BLOCK4
break
> I think this gives Pythons general flow control some nice symmetrical
> and consistent characteristics that seem very appealing to me. Anyone
> agree?
No. Having more ways to do control flow doesn't make for code that's
easy to read.
My usual next step after thinking (or hearing) about a new Python
language change is to look at existing code and see if there's
existing code which would be easier to read/understand and get an
idea if it's a common or rare problem. Perhaps you could point
out a few examples along those lines?
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list