Docstring

From Seo Wiki - Search Engine Optimization and Programming Languages

Jump to: navigation, search

In programming, a docstring is a string literal specified in source code that is used, like a comment, to document a specific segment of code. Unlike conventional source code comments, or even specifically formatted comments like Javadoc documentation, docstrings are not stripped from the source tree when it is parsed, but are retained throughout the runtime of the program. This allows the program to inspect these comments at run time, for instance as an interactive help system, or as metadata.

Among languages that support docstrings are Python, Lisp, and R[citation needed].

Contents

Implementation examples

Lisp

In Lisp, docstrings are known as documentation strings. The Common Lisp standard states that a particular implementation may choose to discard docstrings whenever they want, for whatever reason. When they are kept, docstrings may be viewed (and changed) using the DOCUMENTATION function. For instance,

 (defun foo () "hi there" nil)
 (documentation #'foo 'function) => "hi there"

Python

The common practice of placing a comment at the head of definitions when programming, is captured by the addition of docstring syntax in the Python language.

Python docstrings appear as a string literal, (not an expression), as the first statement following the definition of functions, methods, modules, and classes. Docstrings can be accessed by the __doc__ attribute on objects.

The following Python file shows the declaration of docstrings within a python source file:

'''
Assuming this is file mymodule.py then this string, being the
first statement in the file will become the mymodule modules
docstring when the file is imported
'''
 
class Myclass():
    """The class's docstring"""
 
    def mymethod(self):
        "The method's docstring"
 
 
def myfunction():
    "The function's docstring"

The following is an interactive session showing how the docstrings may be accessed:

>>> import mymodule
>>> help(mymodule)

Assuming this is file mymodule.py then this string, being the
first statement in the file will become the mymodule modules
docstring when the file is imported

>>> help(mymodule.Myclass)
The class's docstring
>>> help(mymodule.Myclass.mymethod)
The methods docstring
>>> help(mymodule.myfunction)
The functions docstring
>>> 

Tools using docstrings

External links


Personal tools

Served in 0.116 secs.