Five python tips

Thu 22 September 2011 by Thomas Van Doren

I have been using python at work for the last year, and had fooled around with it for five years prior to that. I am by no means an encyclopedia of python knowledge, but here are a few pointers that were not obvious to me when I was getting started.

  1. Use contextlib.closing to avoid leaking file pointers.

2. Use OptionParser (< 2.7) or ArgumentParser (>= 2.7) for easy access to command line options and arguments.

3. Use pickle to write/read data structures to/from file for easy persistent storage.

4. Use subprocess to make shell calls. This is especially useful when writing utility scripts that need to make bash calls (for example)!

5. Simplify unittesting with mock objects. Be careful about using the built in methods on Mock objects, though. A spelling error will get invoked as a 'mock' call to the object instead of throwing an AttributeError.

There are tons of other useful modules and third party libraries out there. Feel free to suggest them in the comments!