ドキュメンテーション文字列

出典: フリー百科事典『ウィキペディア(Wikipedia)』

ドキュメンテーション文字列あるいはdocstring英語: documentation string、ドックストリング)はプログラミングにおいてコメントのようにソースコードの特定の部分を文書化するための文字列リテラルのこと。通常のコメントやdocblockのように解析時に構文木から除外されず、プログラムの実行時まで保持されるため対話的なヘルプメタデータとして利用できる。

歴史的にはEmacsの前身のTECOに初めて実装された[1]

docstringをサポートするプログラミング言語にはPythonLispElixirClojure[2]Gherkin英語版[3]Julia[4] and Haskell[5]がある。

実装例[編集]

Elixir[編集]

言語レベルでドキュメンテーションがサポートされており、Markdownがデファクトのマークアップ言語として利用されている。

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

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

Lisp[編集]

Lispではdocstringとして知られる。Common Lisp標準において、処理系は必要に応じてdocstringを理由なくいつでも破棄してよいと定めている。docstringが温存されているとき、DOCUMENTATION関数[6]で表示および変更できる。

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

Python[編集]

Pythonでは定義(defまたはclass)の直後の文に文字列リテラルを記述することでコードオブジェクト(モジュール、クラス、または関数)のdocstringになる。他のタイプの式ではなく、文字列リテラルでなくてはならない。コードオブジェクトのdocstringは、そのオブジェクトの__doc__属性およびhelp関数を介して利用できる。

以下のコードはPythonファイルでdocstringを宣言する。

"""The module's docstring"""

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

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

def my_function():
    """The function's docstring"""

上記のコードをmymodule.pyとして保存したとき、インタラクティブシェルで以下のようにdocstringにアクセスできる。

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

ドキュメンテーション文字列を使ったツール[編集]

関連記事[編集]

参考文献[編集]

  1. ^ EMACS: The Extensible, Customizable Display Editor”. 2022年5月29日閲覧。
  2. ^ Function definition with docstring in Clojure
  3. ^ Step Arguments - Doc Strings”. 2016年1月31日時点のオリジナルよりアーカイブ。2016年6月22日閲覧。
  4. ^ Documentation — Julia Language 0.4.1 documentation”. docs.julialang.org. 2015年11月17日時点のオリジナルよりアーカイブ。2022年5月29日閲覧。
  5. ^ Docstrings”. 2022年5月29日閲覧。
  6. ^ CLHS: Standard Generic Function DOCUMENTATION...

外部リンク[編集]