October 18, 2005

Python Tip of the Day: Easy Doctest-ing

Filed under: ResearchAndDevelopment — Ryan Wilcox @ 10:05 pm

In Python you can add a description to any class or function. This description is called a docstring in the Python community.


def addOneToNumber(num):
"""this function adds one to the number parameter passed in.
If not a number will throw InputError"""

if isinstance(num, int) == True:
return num + 1
else:
raise InputError, "Must be a number"

Docstrings document what the function does, just as this docustring does here. Often with a description you want to include an example for future programmers, showing them how to call the function, or what they might expect what happens.

It is a great idea to put examples in your docstrings, but how can you be certain that the examples are up to date? Programmers really hate reading outdated sample code, is there a way to prevent this?

Python provides the doctest module which presents a solution to this problem: docstring will run statements in the docstring, and error if the output is different from what it expected. These docstrings are created by importing your script into a running Python interpreter, running your function, and pasting the command and the results into your docstring.

There’s an easy way to doctest your routines, read on to discover how…

(more…)

October 4, 2005

Dynamic Shopping Cart Example

Filed under: General Information,ResearchAndDevelopment — Ryan Wilcox @ 1:04 pm

I spent a few hours with MochiKit, getting a feel for this neat JavaScript framework, and doing some dynamic HTML (aka: AJAX) programming too.

For a simple example of these technologies I created a demo of a Dynamic Shopping Cart. The sample dynamically recomputes the price of a line item (and the total of the bill) in response to user events.

Check it out!