Docstring

From Wikipedia, the free encyclopedia
Jump to navigation Jump to search

A docstring is a string literal that annotates an associated section of source code. It provides for the same utility as a comment, but unlike a comment is a string literal and is retained as part of the running program. Some development tools display docstring information as part of an interactive help system.

Programming languages that support docstring include Python, Lisp, Elixir, Clojure,[1] Gherkin,[2] Julia[3] and Haskell.[4] Tools that leverage docstring text include cobra-doc (Cobra), doctest (Python), Pydoc (Python), Sphinx (Python).

Examples

[edit | edit source]

Elixir

[edit | edit source]

Documentation is supported at language level, in the form of docstrings. Markdown is Elixir's de facto markup language of choice for use in docstrings:

def module MyModule do
  @moduledoc """
  Documentation for my module. With **formatting**.
  """

  @doc "Hello"
  def world do
    "World"
  end
end

In Lisp, a docstring is known as a documentation string. The Common Lisp standard states that a particular implementation may choose to discard docstrings. When they are kept, docstrings may be viewed and changed using the DOCUMENTATION function.[5] For instance:

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

Python

[edit | edit source]

In Python, a docstring is a string literal that follows a module, class or function definition. It must be nothing but a string literal, not any other kind of expression. The docstring is accessible via the associated code element's __doc__ attribute and the help function.

The following Python code declares docstrings for each program element:

"""The module's docstring"""

class MyClass:
    """The class's docstring"""

    def my_method(self):
        """The method's docstring"""

If saved as mymodule.py, the following is an interactive session showing how the docstrings may be accessed:

>>> import mymodule
>>> help(mymodule)
The module's docstring
>>> help(mymodule.MyClass)
The class's docstring
>>> help(mymodule.MyClass.my_method)
The method's docstring

See also

[edit | edit source]

References

[edit | edit source]
  1. ^ Lua error in Module:Citation/CS1/Configuration at line 2172: attempt to index field '?' (a nil value).
  2. ^ Lua error in Module:Citation/CS1/Configuration at line 2172: attempt to index field '?' (a nil value).
  3. ^ Lua error in Module:Citation/CS1/Configuration at line 2172: attempt to index field '?' (a nil value).
  4. ^ Lua error in Module:Citation/CS1/Configuration at line 2172: attempt to index field '?' (a nil value).
  5. ^ CLHS: Standard Generic Function DOCUMENTATION...
[edit | edit source]