Suggestions for good programming practices?

François Pinard pinard at iro.umontreal.ca
Mon Jun 24 00:33:20 EDT 2002


[Dianne van Dulken]

> I [...] was wondering 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've seen many ideas expressed on this list.  Being rather maniacal on
details, I surely gave many programming rules to myself which I try to
follow.  Maybe I should take the time and formalise these into some Web page.
On the other hand, style may always be the source of heated debates!

Despite Python is simple, I try to _not_ even use all of it.  For example,
`print' is strictly reserved for debugging purposes, I never use `print'
for production scripts.  I also completely avoided `input' so far.  It is
exceptional that I use `exec' or `eval', and I almost never use `global'.

Python has evolved fastly in recent times.  You might also want to decide
for which Python version you aim your code, and choose to _not_ take
advantage of all the features of the latest Python available.  This is
especially useful if you move between machines, or have a user base.

> For example, in perl you obviously are always encouraged to use strict, and
> we always use eval around our main code to pick up any unexpected errors.

Python is pretty exceptional in that it catches and reports errors
automatically, unless you do take special action to prevent it of doing so.
In C or Perl, this is a constant burden for any programmer who takes style
seriously.  I see this as one of the important reliefs brought by Python.

I also much like `assert' as an expedient way to report consistency
errors, and even usage errors.  I do not mind tracebacks in such cases,
even if they are not much useful in case of usage errors.  With `assert',
the second argument is often a tuple containing all variables which are
meaningfully dumped to understand why the `assert' was triggered.

> Any other tips that you would suggest a new python user should be always
> doing as a good programming practice?

Peter Hansen already suggested the Guido style guide, which hold many
good ideas.

All my executable scripts use similar conventions about how to organise
calling of the main function, decoding options, providing help, etc.
My projects are also structured in similar ways (`Makefile', `setup.py',
etc.) and installable without having to be `root'.  I gave a fair amount
of thought before deciding how those things are best done.  My co-workers
adopted very similar conventions, so we can more easily share development.

The key point of all this is that it pays being consistent between all
one's Python works.  My suggestion is that you should actively develop a
style that suits you, and reasonably be faithful to your own style. :-)

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard





More information about the Python-list mailing list