How to use Python well?

Roy Smith roy at panix.com
Thu Feb 17 00:21:09 CET 2011


In article 
<cfdfce2a-a7cd-4174-a3a5-da021e80abff at x21g2000vbn.googlegroups.com>,
 snorble <snorble at hotmail.com> wrote:

> I use Python a lot, but not well. I usually start by writing a small
> script, no classes or modules.

One anti-pattern that I see in my own code is starting out thinking, 
"this is just a little script, I doesn't need any real structure".  That 
almost always turns out to be wrong, but by the time I start to realize 
I'm writing spaghetti code, it's so temping to say, "I don't have the 
time to refactor this now, I'll just hack on it a bit more".  Which, of 
course, makes it even harder to unravel later.

The first step is to break up a monolithic script into a few functions.  
I encourage myself to do that from the git-go by keeping a template 
around:

#!/usr/bin/env python

def main():
    pass

if __name__ == '__main__':
    main()

and I use that whenever I start a new script.  That at least gets me off 
on the right foot.

The next step is to turn my collection of functions (with the inevitable 
collection of global variables that lets them communicate) into a class 
with methods and instance variables.  I can't tell you how many times 
I've started out saying, "this isn't going to be complicated enough to 
justify making it a class".  Inevitably, I'm wrong.

Finally, the next layer of stupid mistake I often make is to start out 
saying, "This isn't going to be complicated enough to justify writing 
unit tests".  Inevitably, I'm wrong about that too.

So far, none of the above is at all specific to Python,  It's equally 
true in any language.

Now, for some Python-specific advice; you can write Fortran in any 
language.  What that means is it's one thing to translate some existing 
script into Python and make it work, but it's another to actually take 
advantage of some of Python's biggest strengths.  Learn to be 
comfortable with list comprehensions, generator expressions, and 
iterators in general.  Learn about Python's advanced data structures 
such as sets, defaultdicts, and named tuples.



More information about the Python-list mailing list