for / while else doesn't make sense

pavlovevidence at gmail.com pavlovevidence at gmail.com
Sun Jun 12 03:01:48 EDT 2016


On Thursday, May 19, 2016 at 9:43:56 AM UTC-7, Herkermer Sherwood wrote:
> Most keywords in Python make linguistic sense, but using "else" in for and
> while structures is kludgy and misleading. I am under the assumption that
> this was just utilizing an already existing keyword. Adding another like
> "andthen" would not be good.
> 
> But there is already a reserved keyword that would work great here.
> "finally". It is already a known keyword used in try blocks, but would work
> perfectly here. Best of all, it would actually make sense.
> 
> Unfortunately, it wouldn't follow the semantics of try/except/else/finally.
> 
> Is it better to follow the semantics used elsewhere in the language, or
> have the language itself make sense semantically?
> 
> I think perhaps "finally" should be added to for and while to do the same
> thing as "else". What do you think?

I agree it's not the clearest name, but it does behave consistent with if...else.  "finally" has a strong connotation for code that is guaranteed to be executed on the way out regardless of an exception, so it wouldn't be appropriate for this even if it were clearer (though it isn't IMO).

Here's how I make sense of for...else.  Consider this loop:

for item in seq:
    if pred(item):
        use(item)
        break
else:
    not_found()


This particular loop functions as a kind of a dynamic if...elif...else statement.  You can see that if you unroll the loop:


if pred(seq[0]):
    use(seq[0])
elif pred(seq[1]):
    use(seq[1])
elif pred(seq[2]):
    use(seq[2])
else:
    not_found()


You will note that the else block is the same in both the rolled and unrolled versions, and has exactly the same meaning and usage.

As for a more appropriate keyword, I don't like the examples I saw skimming this thread; neither "finally" nor "then" communicates that the block would executed conditionally.

If you want my opinion, you might as well use something explicit and unambiguous, like "if_exhausted", for the block; and you might as well add an "if_broken" block while you're at it (though it's not quite as useful since in most cases you could just put the code before the break).  Since it's only occasionally useful, there's no real need to make the keyword short.

If you really want my opinion, it probably shouldn't be in the language at all, even though I happily use it from time to time, and my code is better for it.  But it's not useful enough that the language would really suffer without it, and it would save some users from something that can be quite confusing.


-- 
Carl Banks


More information about the Python-list mailing list