One of the banes of software development is writing the documentation. Most development teams would prefer to rally around the cry: "Let the technical writers of the world unite (and write our manuals)!" However, Python is designed to be self-documenting, and one should use that aspect of the language. The code you debug tomorrow may be your own. Or, in a karmic sense, the code you document today may grace your screen with well-documented code in the future.
While not a perfect substitute for full-fledged technical documentation, Python's self-documentation system is far more convenient. Consider the following function:
def fibo_gen():
x, y = 0, 1
while True:
yield x
x, y = y, x + y
This is a basic function Fibonacci for generating Fibonacci numbers. You can tell this from its use of the yield statement. Such functions merely return an iterator which returns the next in a sequence whenever it is called but does not contain a set, static set [More on iterators can be found in Max Hetland's Beginning Python ]. If you call the function with a range of 15 (as below), you will get the following output:
set = fibo_gen()
for x in range(15):
print set.next()
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
But what if you did not know what it did? What if the programmer who reads the code in 6 months does not know what it does? You can include documentation in the function itself for anyone who imports this function.
Do this by adding a docstring to the function. A docstring is a bit of documentation which immediately follows the function declaration line and precedes all of the function code. It is always offset with a set of three quotes, but whether you use single quotation marks or double quotation marks is your decision. Python recognises both. Consider the same function with the docstring:
def fibo_gen():Now, anyone who imports this function can access your brief documentation with Python's built-in help() function:
'''Generate Fibonacci numbers; return an iterator'''
x, y = 0, 1
while True:
yield x
x, y = y, x + y
>>> help(fibo_gen)
Help on function fibo_gen in module __main__:
fibo_gen()
Generate Fibonacci numbers; return an iterator.
