Good code patterns in Python

Michael Chermside mcherm at mcherm.com
Tue Jul 1 19:13:50 CEST 2003


Will Stuyvesant writes:
> If you know that your source code is going to be used
> later by others, then I feel that code with the pattern:
> 
>     if some_condition:
>         some_name = some_value
>     else:
>         some_name = other_value
> 
> is often a mistake.  Much better, safer, would be:
> 
>     some_name = some_value
>     if not some_condition:
>         some_name = other_value

I disagree with you... I think that the first form is superior
to the second. Here are two reasons.

My number one reason is readability. Seeing "some_name = some_value"
when some_name is ACTUALLY going to take on other_value is very
misleading to the reader. Particularly in Python, I strive to make
my code very readable -- it's typically more important to me to be
readable than it is to be fast. Furthermore, if the code is easily
understood, then that maintanence programmer or re-user of your
code that you mentioned is less likely to make a mistake like leaving
some_name undefined.

My second reason is the danger of this maintanence programmer. You
are concerned that they might "change or adapt the 'if' part".
Frankly, I don't find this to be much of a worry. After all, the
use of an if with an else clause CLEARLY indicates that you expect
one of these two branches to be taken, and that if they change it
so neither is taken, they'd better be sure they know what they're
doing. On the other hand, I'm QUITE worried about the maintanence
programmer modifying your second example. If they somehow fail to set 
some_name it would result in "NameError: name 'some_name' is not 
defined" the first time that it used -- a pretty clear error message.
But (unlike modifying the if-else), a maintanence programmer is quite
likely to simply add some new lines of code... perhaps (foolishly)
between the first assignment and the if statement. If this happened,
the resulting error would be that some_name DID have a value, but
it was the WRONG value. This could result in some peculiar exception
at an arbitrary time, or (much worse) perhaps NO exception at all...
the program would proceed, producing incorrect data with no warning.

Finally, I'd like to make reference to the wonderful world of unit
tests. If the code has no unit tests, then either error is possible.
But if there are unit tests, then the person who re-uses that code
and modifies it so that some_name is no longer set properly will
find a test failing. This will immediately alert them that their
change is causing problems... they will examine the situation and
either fix the problem or change the test ("now I WANT some_name to
be undefined in some cases").

-- Michael Chermside






More information about the Python-list mailing list