"if {negative}" vs. "if {positive}" style (was: New to Python)

Roy Smith roy at panix.com
Wed Feb 10 08:38:18 EST 2010


In article <mailman.2269.1265773024.28905.python-list at python.org>,
 Tim Chase <python.list at tim.thechases.com> wrote:

> 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?
> 
> -tkc

In general, I try to avoid negation, because it makes things harder to 
understand.  When you write:

if not foo:
   blah
else:
   blah-blah

the else clause is executed if "not foo is not true".  That quickly gets 
confusing.

As for the code blocks being so large that the else becomes distant from 
the condition, that smells like the two codeblocks want to be refactored 
into distinct functions:

if foo:
   do_one_thing()
else:
   do_something_else()

It's not always practical, but my first reaction would be to try that and 
see if it works.



More information about the Python-list mailing list