"if {negative}" vs. "if {positive}" style (was: New to Python)
Carl Banks
pavlovevidence at gmail.com
Wed Feb 10 16:47:44 EST 2010
On Feb 9, 7:36 pm, Tim Chase <python.l... 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'
[pass]
> Any thoughts on how others make the choice?
I almost always arrange it as follows, regardless of the size of the
blocks or whether the condition is negated or not:
if (typical-condition):
typical-case
else:
exceptional-case
In particular I almost always test if something is not None, because
being None is almost always the exceptional case:
if x is not None:
...
else:
...
However, whenever the exceptional case action is to break, return,
continue, or raise an exception, I'll test for it and leave the
typical case unnested:
if (exceptional-condition):
exceptional-case
typical-case
No, it deosn't bother me in the least that I sometimes test for the
exceptional case and sometimes for the typical.
Whenever there is no typical case or exceptional case I'll go for the
simpler condition.
Carl Banks
More information about the Python-list
mailing list