Wednesday, November 05, 2008

Document With Examples

I've found out that a lot of times when I have a parsing code, it's best to document the methods with examples of the input.

A small example:
#!/usr/bin/env python
'''Simple script showing how to document with examples'''

__author__ = "Miki Tebeka <miki.tebeka@gmail.com>"

import re

# HTTP/1.1 200 OK
# HTTP/1.1 301 Moved Permanently
def http_code(line):
return line.split()[1]

if __name__ == "__main__":
print http_code("HTTP/1.1 301 Moved Permanently")

2 comments:

  1. Good point, however I found out that too much doctest tend to clutter the code.
    Also IMO docstring are for *what* the function does, not much for examples.

    For this example it'll move from 2 lines to 6 lines of documentation:

    def http_code(line):
    '''
    >>> http_code("HTTP/1.1 200 OK")
    '200'
    >>> http_code("HTTP/1.1 301 Moved Permanently")
    '301'
    '''
    return line.split()[1]

    ReplyDelete