Thursday, January 21, 2010

Doctest in Python

As part of my mission to learn a new thing each day I've ended up learning about the doctest python module today. It let's you add intepreter commands and responses as docstrings for each function and let's you run them, giving you feedback if anything is amiss. Here's an example:
def fib(x):
    """
    >>> fib(0)
    0
    >>> fib(1)
    1
    >>> fib(2)
    1
    >>> fib(3)
    2
    >>> fib(4)
    4
    """
    if x == 0:
        return 0
    elif x == 1:
        return 1
    else:
        return fib(x-1) + fib(x-2)


if __name__ == '__main__':
    import doctest
    doctest.testmod()
Would return:
**********************************************************************
File "fib.py", line 11, in __main__.fib
Failed example:
fib(4)
Expected:
4
Got:
3
**********************************************************************
1 items had failures:
1 of   5 in __main__.fib
***Test Failed*** 1 failures.
It's worth noting that python doesn't handle tail recursion very well, so we wouldn't like to try running fib() on very large numbers, but it's ok for this example

No comments:

Post a Comment