Suggestions for good programming practices?

Carl Banks imbosol at vt.edu
Mon Jun 24 14:32:43 EDT 2002


Dianne van Dulken wrote:
> Hi,
> 
> I'm fairly new to python, coming from a perl background, and 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)
> 
> 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.  I
> presume the equivalent in python is the try statement.  Would you suggest
> that this should be used, or would that be redundant here?  Any other tips
> that you would suggest a new python user should be always doing as a good
> programming practice?


Python has relatively few of these.  I've been racking my brain to
think of any, but could only think of one really serious issue we face
in Python.  Python is a cautious language, and if you overlook
something there's a good chance you'll see a stack trace.

Anyways, the really important issue is:

* Do not mix spaces and tabs for indentation.  Choose one or the other
  and stick with it.  It helps to have an editor that indents
  intelligently and does nothing funny with the indents.


There's other stuff, but the same ideas apply to languages other than
Python.

* Avoid exec, execfile, eval, and input.

* Use local variables whenever possible.  Important in Python because
  local variables are much faster than global.  In practice, this
  means that people will often put their main code in a function, and
  call it with the "if __name__=='__main__': main()" cliche.

* Learn how references and the object system work as soon as possible.
  You should not be surprised when you do this:

  a = [1,2,3]
  b = a
  b[0] = 100
  print a

  And it prints "[100,2,3]"


-- 
CARL BANKS                                http://www.aerojockey.com
"Nullum mihi placet tamquam provocatio magna.  Hoc ex eis non est."



More information about the Python-list mailing list