Docstrings in Python

Docstrings in Python

Docstrings are documentation strings that are placed at the beginning of a function, class, or module. We can write a docstring in a few lines. The first line has a bold letter in the beginning, and it’s ended with a period. The  second line is empty. The third one should include more details about described object. It’s a convention. The first line of the docstring is a summary of our function. This is followed by a blank line and more detailed information. We should remember that the one-line summary should be a complete sentence. This is a typical example:

def oblicz( a, b ):
     “””oblicz( number, number ) -> number
Returns the sum of two numbers.”””
return a+ b

We have the result:

>>> print(oblicz.__doc__)
oblicz(number, number) -> number
Returns the sum of two numbers.

>>>

In Unix/Linux, we use it in this way:

#!/usr/bin/python
# -*- coding: utf-8 -*-
# File name: func.py

def func():
     “””YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
“””
     pass #Our function does nothing

Let’s try to see our docstrings. We have the result:

>>> print(func.__doc__)
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
>>>

We use the print statement to make the output easier to read, because docstrings often contain embedded newlines (\n):

Automatic tools can get the docstrings for us from our code. What should we include in a docstring? Even one-line docstring is helpful. You should write if your function returns something or not. What our function does, all its restrictions, and conditions for its working. It’s especially important for libraries. We can include the example of using our function. It will be very professional. This is a very good example of docstring:

“””

This is the “example” module.

The example module supplies one function, factorial(). For example,

>>> factorial(5)

120

“””

def factorial(n):

“””Return the factorial of n, an exact integer >= 0.

>>> [factorial(n) for n in range(6)]

[1, 1, 2, 6, 24, 120]

>>> factorial(30)

265252859812191058636308480000000

>>> factorial(-1)

Traceback (most recent call last):

ValueError: n must be >= 0

Factorials of floats are OK, but the float must be an exact integer:

>>> factorial(30.1)

Traceback (most recent call last):

ValueError: n must be exact integer

>>> factorial(30.0)

265252859812191058636308480000000

It must also not be ridiculously large:

>>> factorial(1e100)

Traceback (most recent call last):

OverflowError: n too large

“””

We can read the docstring of our object using __doc__. It’s an attribute. We can write help(object) too. The q key ends help. To get a help about any object, just use pydoc.

>>> import pydoc
>>> dir(pydoc)
[‘Doc’, ‘ErrorDuringImport’, ‘HTMLDoc’, ‘HTMLRepr’, ‘Helper’, ‘ModuleScanner’, ‘
Repr’, ‘Scanner’, ‘TextDoc’, ‘TextRepr’, ‘_PlainTextDoc’, ‘__all__’, ‘__author__
‘, ‘__builtins__’, ‘__cached__’, ‘__credits__’, ‘__date__’, ‘__doc__’, ‘__file__
‘, ‘__initializing__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘_is_some_method
‘, ‘_re_stripid’, ‘_split_list’, ‘_start_server’, ‘_url_handler’, ‘allmethods’,
‘apropos’, ‘browse’, ‘builtins’, ‘classify_class_attrs’, ‘classname’, ‘cli’, ‘cr
am’, ‘deque’, ‘describe’, ‘doc’, ‘extract_tb’, ‘format_exception_only’, ‘getdoc’
, ‘getpager’, ‘help’, ‘html’, ‘imp’, ‘importfile’, ‘importlib’, ‘inspect’, ‘io’,
 ‘isdata’, ‘ispackage’, ‘ispath’, ‘locate’, ‘os’, ‘pager’, ‘pathdirs’, ‘pipepage
r’, ‘pkgutil’, ‘plain’, ‘plainpager’, ‘plaintext’, ‘platform’, ‘re’, ‘render_doc
‘, ‘replace’, ‘resolve’, ‘safeimport’, ‘source_synopsis’, ‘splitdoc’, ‘stripid’,
 ‘synopsis’, ‘sys’, ‘tempfilepager’, ‘text’, ‘time’, ‘tokenize’, ‘ttypager’, ‘vi
siblename’, ‘warnings’, ‘writedoc’, ‘writedocs’]
>>>

 >>> pydoc
<module ‘pydoc’ from ‘D:\\Python33\\lib\\pydoc.py’>
>>>

>>> help(pydoc)
Help on module pydoc:

NAME
    pydoc – Generate Python documentation in HTML or text for interactive use.

DESCRIPTION
    In the Python interpreter, do “from pydoc import help” to provide
    help.  Calling help(thing) on a Python object documents the object.

    Or, at the shell command line outside of Python:

    Run “pydoc <name>” to show documentation on something.  <name> may be
    the name of a function, module, package, or a dotted reference to a
    class or function within a module or module in a package.  If the
    argument contains a path segment delimiter (e.g. slash on Unix,
    backslash on Windows) it is treated as the path to a Python source file.

    Run “pydoc -k <keyword>” to search for a keyword in the synopsis lines
    of all available modules.

    Run “pydoc -p <port>” to start an HTTP server on the given port on the
    local machine.  Port number 0 can be used to get an arbitrary unused port.

    Run “pydoc -b” to start an HTTP server on an arbitrary unused port and
    open a Web browser to interactively browse documentation.  The -p option
    can be used with the -b option to explicitly specify the server port.

    Run “pydoc -w <name>” to write out the HTML documentation for a module
    to a file named “<name>.html”.

    Module docs for core modules are assumed to be in

        http://docs.python.org/X.Y/library/

    This can be overridden by setting the PYTHONDOCS environment variable
    to a different URL or to a local directory containing the Library
    Reference Manual pages.

DATA
    __all__ = [‘help’]
    help = <pydoc.Helper instance>

DATE
    26 February 2001

AUTHOR
    Ka-Ping Yee <ping@lfw.org>

CREDITS
    Guido van Rossum, for an excellent programming language.
    Tommy Burnette, the original creator of manpy.
    Paul Prescod, for all his work on onlinehelp.
    Richard Chamberlain, for the first implementation of textdoc.

FILE
    d:\python33\lib\pydoc.py

>>>

We see the module pydoc in the Python interpreter, but now let’s use that. We should write in the command prompt:

python  the path for our pydoc.py module in our operating system and the module we wish to get help

Microsoft Windows XP [Wersja 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\Documents and Settings\Admin> python D:\Python33\Lib\pydoc.py math
Help on built-in module math:

NAME
    math

DESCRIPTION
    This module is always available.  It provides access to the
    mathematical functions defined by the C standard.

FUNCTIONS
    acos(…)
        acos(x)

        Return the arc cosine (measured in radians) of x.

  

        Return the arc tangent (measured in radians) of x.

    atan2(…)
        atan2(y, x)

        Return the arc tangent (measured in radians) of y/x.
        Unlike atan(y/x), the signs of both x and y are considered.

 

DATA
    e = 2.718281828459045
    pi = 3.141592653589793

FILE
    (built-in)

The pydoc module automatically generates documentation form the Python modules installed in our operating system. The documentation can be text on the console, we can have it in a web browser, or we can save it to HTML files. For example help() presents the online help system in the interactive interpreter. It uses the pydoc module to generate its documentation as text on the console. We can also view the documentation from outside the Python interpreter with running pydoc as a script on the console. We saw that above. As an argument, we can use the name of a function within a module or module in a package.

pydoc imports the module the documentation of which we wish to know. That’s why, any code on module level will be executed. We should use

if __name__ == ‘__main__’:

to execute the code when a file is invoked as a script and not just imported.

Now, let’s look at the flags:

pydoc.py -w flag before the argument will cause HTML documentation to be written out to a file in the current directory, instead of displaying text on the console.

C:\Documents and Settings\Admin> python D:\Python33\Lib\pydoc.py -w math
wrote math.html

pydoc.py -k flag before the argument will search the synopsis lines of all available modules for the keyword given as the argument, again in a manner similar to the Unix man command. The synopsis line of a module is the first line of its documentation string.

C:\Documents and Settings\Admin> python D:\Python33\Lib\pydoc.py -k “string”
_string – string helper module
ctypes.test.test_stringptr
ctypes.test.test_strings
distutils.versionpredicate – Module for parsing and testing package version pred
icate strings.
doctest – Module doctest — a framework for running examples in docstrings.
lib2to3.fixes.fix_basestring – Fixer for basestring -> str.
lib2to3.pgen2.literals – Safely evaluate Python string literals without using ev
al().
string – A collection of string constants.
stringprep – Library that exposes various tables found in the StringPrep RFC 345
4.
test.json_tests.test_encode_basestring_ascii
test.json_tests.test_scanstring
test.string_tests – Common tests shared by test_str, test_unicode, test_userstri
ng and test_string.
test.test_string
test.test_stringprep
test.test_strlit – Test correct treatment of various string literals by the pars
er.
test.test_userstring
django.utils.baseconv – Convert numbers from base 10 integers to base X strings
and back again.
django.utils.safestring – Functions for working with “safe strings”: strings tha
t can be displayed safely
win32com.client.CLSIDToClass – Manages a dictionary of CLSID strings to Python c
lasses.

C:\Documents and Settings\Admin>

You can also use pydoc to start an HTTP server on the local machine that will serve documentation to visiting Web browsers. pydoc -p 1230 will start a HTTP server on port 1230.

C:\Documents and Settings\Admin> python D:\Python33\Lib\pydoc.py -p 1230
Server ready at http://localhost:1230/
Server commands: [b]rowser, [q]uit
server>

Let’s try to type ‘b’:

server> b
server>

After some seconds, we will see the documentation in our web browser. In other words, we can browse the documentation at

http://localhost:1230/

in your web browser. Specifying 0  as the port number will select an arbitrary unused port.

When we see what we want, we can quit:

server> q
Server stopped

C:\Documents and Settings\Admin>

pydoc.py -g will start the server and additionally bring up a small thinter-based graphical interface to help you search for documentation pages. This option is deprecated, since the server can now be controlled directly from HTTP clients. Since Python 3.2 we have -b option, the -g option is deprecated.

pydoc.py -b will start the server and additionally open a web browser to a module index page. Without -p, the port is arbitrary.

C:\Documents and Settings\Admin> python D:\Python33\Lib\pydoc.py -b
Server ready at http://localhost:12248/
Server commands: [b]rowser, [q]uit
server>

When pydoc generates documentation, it uses the current environment and path to locate modules. Thus, invoking pydoc math documents precisely the version of the module you would get if you started the Python interpreter and typed import math.

Module docs for core modules are assumed to reside in

http://docs.python.org/X.y/library/

where X and Y are the major and minor version numbers of the Python interpreter. This can be overridden by setting the PYTHONDOCS environment variable to a different URL or to a local directory containing the Library Reference Manual pages.

2 thoughts on “Docstrings in Python

    1. tomaszzackiewicz Post author

      Thanks for your comment. I improved the formatting somewhat and I will be watching that in the future, but it isn’t easy to write rich documents in WordPress. I don’t want spend much time on formatting with tags – I have no time to play with that. I wish to transfer my knowledge to other people only. There are many things to do. My convention is: Blue color text is for code and red color is for more important things in code that should be noticed by readers. Which color is better than red one? Yellow? Green?

      Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s