Document you code using docstrings.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bartonc
    Recognized Expert Expert
    • Sep 2006
    • 6478

    #1

    Document you code using docstrings.

    You will be rewarded sooner than you think when you use docstrings to document your classes and functions. Whether you ever intend to publish your work or not, docstrings will help you in several ways. First, let me show you the syntax:
    Code:
    def Add(a, b):
        """Return the sum of two addable types.
           This is a very simple example of docstring usage."""
        return a + b
    If you get into the habit of jotting down a short description of a function that you are writing (even before any of the body has taken shape), the first thing that you will be able to identify is whether you have factored the problem adaquately. If you can't describe the function in a line or two sentances, you may want to look at the problem again and see it you are not, in fact, trying to stuff too much into one function and should consider refactoring.
    Secondly, docstrings are available in the Python shell via help() and dir(). So, if it's been a while since you have used one of your function you can import your library module and type
    help(myLibModul e.myFunc)
    and your docstrings will be printed (this works for compiled modules, also).
    Lastly, there are a few really cool automatic documentation tools that will read your module and make basic (but nice looking) documetation for you (but only if you use docstrings).
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Good advice Barton. You can also access the documentation with the __doc__ variable and attribute.
    Code:
    """
    This is a test of reading a documentation string.
    """
    def factorial(n):
        """
        This function returns the factorial of a number.
        The factorial of 6 is 6*5*4*3*2.
        This function uses recursion.
        """
        if n == 0 or n == 1:
            return 1
        else:
            f = (n*factorial(n-1))
        return f
    
    print factorial(6)
    print factorial.__doc__
    print __doc__
    
    >>> 720
    
        This function returns the factorial of a number.
        The factorial of 6 is 6*5*4*3*2.
        This function uses recursion.
        
    
    This is a test of reading a documentation string.

    Comment

    Working...