"if {negative}" vs. "if {positive}" style

Alf P. Steinbach alfps at start.no
Tue Feb 9 23:09:37 EST 2010


* Tim Chase:
> Larry Hudson wrote:
>> But a minor rearrangement is simpler, and IMHO clearer:
>>
>> if 'mystring' not in s:
>>      print 'not found'
>> else:
>>      print 'foundit'
>>      print 'processing'
> 
> I've always vacillated on whether that would better be written as Larry 
> does, or as
> 
>   if 'mystring' in s
>     print 'foundit'
>     print 'processing'
>   else:
>     print 'not found'
> 
> removing the "not" from the condition.  I admit I choose one over the 
> other based on some gut-feeling aesthetic that I can't really nail 
> down.  I think one of my major influencing factors revolves around the 
> negative "not" portion having one or two lines and the  positive portion 
> having a large block of code.  If the code-blocks are more equal in 
> size, I tend to use "if {positive}", but if the negative "not" section 
> is only 1-2 lines, I tend to do as Larry writes and make it harder to 
> miss by using "if {negative}".  Otherwise the "if {positive}...else" can 
> end up sufficiently distant from the "if" that it's easy to miss.
> 
> Any thoughts on how others make the choice?

I think it spills over from the practice of checking preconditions first, e.g. 
returning or raising exceptions or whatever.

This avoids silly n-level nesting of the main "normal case" part.


Cheers,

- Alf



More information about the Python-list mailing list