How to use Python well?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed Feb 16 18:00:35 EST 2011
On Wed, 16 Feb 2011 10:35:28 -0800, snorble wrote:
> I use Python a lot, but not well. I usually start by writing a small
> script, no classes or modules. Then I add more content to the loops, and
> repeat. It's a bit of a trial and error learning phase, making sure I'm
> using the third party modules correctly, and so on. I end up with a
> working script, but by the end it looks messy, unorganized, and feels
> hacked together. I feel like in order to reuse it or expand it in the
> future, I need to take what I learned and rewrite it from scratch.
[...]
> Or maybe I'm looking for is best practices for how to organize the
> structure of a Python program. I love Python and I just want to be able
> to use it well.
I don't think best practice for writing Python is that much different
from best practice for other languages. The main difference is that
Python is multi-paradigm: you can mix procedural, functional and object-
oriented code in the one program.
You should read about bottom-up and top-down programming. You'll probably
end up doing some of both, but mostly top-down.
The most important thing is structured programming and modularization.
The debate over structured programming was won so decisively that people
have forgotten that there was ever an argument to be made for spaghetti
code!
You can learn a lot (and lose a lot of time!) reading the c2.com wiki at
http://c2.com/cgi/wiki. These may be useful:
http://c2.com/cgi/wiki?StructuredProgramming
http://c2.com/cgi/wiki?WhatIsRefactoring
Break your code up into small pieces, whether you use functions or
classes doesn't really matter, although for small scripts functions are
simpler and have less mental overhead. Instead of writing one giant
monolithic block of code that does twenty things, write one function for
each thing, and then one extra main function to call them. This
encourages code reuse, ease of testing, and simplifies maintenance.
I find that I've learned more from "things to avoid" than from "things to
do". Something about reading about disasters makes it really clear why
you shouldn't do it that way :)
Avoid:
* GOTO, but Python doesn't have that :)
* Copy-and-paste programming. If you want to do almost the same thing
twice, don't copy the relevant code, paste it, and make a small
modification to it. Write one or more functions that handle the common
code, and call the function.
* Functions that do unrelated things. Functions should do one thing,
although that "thing" can get quite complicated.
* Don't sweep errors under the rug. Don't catch exceptions unless you can
do something about them. "Just ignore it, I'm sure it's not important" is
rarely appropriate.
See also:
http://c2.com/cgi/fullSearch?search=CategoryDevelopmentAntiPattern
--
Steven
More information about the Python-list
mailing list