Checking Examples in Source Code

The doctest module allows you to check examples in your source code.

Consider the following code fib.py:

def fib(n):
    """Returns Fibonacci series up to n:
    >>> fib(100)
    [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
    """
    res, a, b = [], 1, 1
    while b <= n:
        res.append(b)
        a, b = b, a+b
    return res

if __name__ == "__main__":
    import doctest
    doctest.testmod()

When you run

$ python fib.py

the example inside the source code will be verified.

>>> from fib import *
>>> fib(100)
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89]