Suggestions for good programming practices?

Peter Hansen peter at engcorp.com
Tue Jun 25 03:08:58 CEST 2002


Dianne van Dulken wrote:
> 
> if anyone has a list of things that they consider as good programming
> practice in Python (I thought this might be an interesting topic for
> discussion, anyway)

I'll amend my previous claim to point to testing as a very useful
part of Python development.  I don't mean running your code manually
after the fact, either.  I mean proper unit testing, which exercises
as much of the code in small pieces as you possibly can.

Unlike with statically typed languages, Python cannot check that
you are not, for example, trying to pass an integer into a routine
that can only accept a string until you actually execute the code.
You don't get the error on compilation as with C for example.
It can become frustrating if you have to run the code manually
each time you make a change and possibly go through a large
sequence of steps before you get to the part you want to test.

Therefore, learn to make your code testable.  Write it in small
modular pieces and have good tests for each.  When you make
a change, run the tests again and they will tell you whether
you've screwed up anything.  If something slips through and 
you find a bug, go back and write another test that fails
on the same problem, then fix the code (making the test 
pass).

No, not many people actually do this.  I've found it highly
effective, however, and it more than makes up for any 
limitations that might exist because of the dynamic nature
of Python compared to statically typed languages.  This
all comes from Extreme Programming, of course, but you can
easily benefit from proper unit testing even without other
changes to your development process.

And most of this advice actually applies to any language, 
but I think Python can take advantage of it even more than most.

-Peter



More information about the Python-list mailing list