Simple if-else question

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed Sep 30 02:12:16 EDT 2009


On Tue, 29 Sep 2009 22:29:10 -0700, John Yeung wrote:

> On Sep 29, 1:15 pm, Carl Banks <pavlovevide... at gmail.com> wrote:
>> Hmm, I wonder if Python should emit a warning if an else is used on a
>> for block with no break inside.  I don't think the else can be invoked
>> in any other way.  As a bonus it could catch some cases where people
>> mistakenly use it thinking it will execute [only] when there are no
>> iterations.
> 
> [Edit from Duncan Booth]
> 
> I would definitely be in favor of a warning.  Yes, people should read
> the docs more carefully, and yes, it would cost a certain amount of
> annoyance to implement this.  But I don't think it would get in people's
> way if they do know how to use else, 

Of course it would. It would mean that everybody who knows how to use 
for...else correctly would have to deal with a totally useless warning.


> and I think it would cut down on
> the number of questions from mystified beginners, some of whom are much
> more aggressive than this particular OP about claiming that Python is
> broken (when it's actually behaving as designed).

By raising a warning, you are implying that the behaviour is broken, or 
at least suspicious. Warnings mean something needs to be warned against 
-- "don't do this". Warnings shouldn't be perfectly legitimate behaviours 
on the off-chance that the user is confused. "Warning, are you sure you 
want to put the car into reverse? Perhaps you meant neutral?"

What would the warning say?

"Warning, you have used a legitimate Python control structure but you 
might be confused by it."

"Warning, did you mean if...else instead of for...else?"

Then we can add a whole lot of extra warnings to protect newbies who 
don't read docs (and probably won't read the warnings either) from 
themselves:

"Warning, did you mean obj(1) instead of obj[1]?"

"Warning, did you mean def f(object) instead of class f(object)?"

"Warning, did you mean class f(object) instead of def f(object)?"

"Warning, did you mean 2*3 instead of 2**3?"

"Warning, did you mean %s instead of %x?"

"Warning, we think you're helpless and don't know what you want, perhaps 
you should be programming in PHP?"



I'm sympathetic to the desire to educate the n00bs, and in fact I've even 
suggested similar warnings myself. But I've been convinced that this is 
the wrong approach. Certainly the language shouldn't assume the 
programmer is confused. If this sort of warning belongs anywhere (and 
that's a big if), it belongs in an IDE.



-- 
Steven



More information about the Python-list mailing list