How to use Python well?

Jorgen Grahn grahn+nntp at snipabacken.se
Thu Feb 17 22:44:20 CET 2011


On Wed, 2011-02-16, 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.
>
> If I peeked over a Python expert's shoulder while they developed
> something new, how would their habits differ? Do they start with
> classes from the start?
>
> I guess I'm looking for something similar to "Large Scale C++ Software
> Design" for Python. Or even just a walkthrough of someone competent
> writing something from scratch. I'm not necessarily looking for a
> finished product that is well written. I'm more interested in, "I have
> an idea for a script/program, and here is how I get from point A to
> point B."
>
> 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.

Good questions -- and you got some really good answers already!

What I always do when starting a program is:

- Split it into a 'if __name__ == "__main__":' which does the
  command-line parsing, usage message and so on; and a function
  which contains the logic, i.e. works like the program would have
  if the OS had fed it its arguments as Python types

- Document functions and classes.

- Avoid having functions use 'print' and 'sys.std*', in case I need to
  use them with other files. I pass file-like objects as arguments
  instead.

- Write user documentation and build/installation scripts. Since I'm
  on Unix, that means man pages and a Makefile.

And that's all in the normal case. No need to do anything more fancy
if it turns out I'll never have to touch that program again.

I use classes when I see a use for them. The "see" part comes from
quite a few years' worth of experience with object-oriented design in
Python and C++ ... not sure how to learn that without getting lost in
Design with a capital 'D' for a few years ...

Anyway, I don't feel bad if I don't find any classes at first.

/Jorgen

-- 
  // Jorgen Grahn <grahn@  Oo  o.   .  .
\X/     snipabacken.se>   O  o   .



More information about the Python-list mailing list