Yes, Rob,

I keep wondering how many decades it will take before people here understand 
how I make a point with an example that is not intended in any way to be 
complete or the way I would do it.

No, I would not normally use the exception method, let alone in this case. This 
one practically screams for the method you suggest and iterate on a list of 
directories made from splitting the PATH variable. And, yes that method would 
likely use a for loop with a break if it is found and is a candidate for using 
the ELSE clause to note it has not been found.

But it is not an unusual idiom these days to use exceptions in places I never 
dreamed of in my earlier programming languages. A common example is always 
testing before accidentally dividing by zero and now code that depends on 
throwing the right exception and dealing with it, especially if the exception 
happens rarely.

So in situations where almost all programs are found in the first component of 
PATH, perhaps the exception approach is not horrible. It may even at times be 
done with less coding effort than other alternatives. Not my preferred way, of 
course.

-----Original Message-----
From: Rob Cliffe via Python-list <python-list@python.org>
To: python-list@python.org
Sent: Fri, Mar 4, 2022 5:22 pm
Subject: Re: Behavior of the for-else construct




On 04/03/2022 20:52, Avi Gross via Python-list wrote:
>
> I have an observation about exception handling in general. Some people use 
> exceptions, including ones they create and throw, for a similar idea. You 
> might for example try to use an exception if your first attempt fails that 
> specifies trying the next attempt. In my example of the PATH variable, you 
> might use something like calling a function and giving it what you are 
> looking for as well as a local copy of the PATH variable content and the 
> exception would be to call the function again with the first component of 
> PATH removed until you fail with an empty PATH. Yes, this is similar to just 
> having a recursive function.
That sounds neither readable nor efficient compared with using split() 
plus a loop.  Maybe you mean this to be a toy, unrealistic example?
> So the example tossed at us looks a bit more like this and it does run the 
> ELSE not because the loop is not done but because  the loop never calls a 
> break:
>
> for x in range(0):
>    print(x)
> else:
>    print("Finally finished!")
This would be more readable with a `zeroiterations` keyword, which 
accurately describes both the semantics and the intent.
> Which leads me right back to wondering why the sentinel approach is so bad!
>
>
It's not that bad, but it's more convenient and readable if it can be 
avoided.
Best wishes
Rob Cliffe

-- 
https://mail.python.org/mailman/listinfo/python-list

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to