If it won't be simple, it simply won't be. [Hire me, source code] by Miki Tebeka, CEO, 353Solutions

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")


Unknown said...

Why not use doctests?

Miki Tebeka said...

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")
>>> http_code("HTTP/1.1 301 Moved Permanently")
return line.split()[1]

Blog Archive