{"id":219,"date":"2019-05-30T11:12:31","date_gmt":"2019-05-30T11:12:31","guid":{"rendered":"http:\/\/askpython.com\/?p=219"},"modified":"2023-02-16T19:57:22","modified_gmt":"2023-02-16T19:57:22","slug":"python-docstring","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/python-docstring","title":{"rendered":"Python Docstring"},"content":{"rendered":"\n<p>Python Docstring (Document String) is a string literal that is the first statement in a module, function, class, or method. <\/p>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">How to Write a Python Docstring?<\/h2>\n\n\n\n<p>Python docstring is surrounded by a pair of triple double-quotes (&#8220;&#8221;&#8221;). Let&#8217;s look at some examples of writing docstrings in Python.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">1. Python Function Docstring Example<\/h3>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndef multiply(a, b):\n    &quot;&quot;&quot;This method multiplies the given two numbers.\n\n    Input Arguments: a, b must be numbers.\n    Returns: Multiplication of a and b.\n    &quot;&quot;&quot;\n    return a * b\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-css-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">2. Python Class Docstring Example<\/h3>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nclass Employee:\n    &quot;&quot;&quot;Employee class is used to hold employee object data.\n\n    Methods:\n        __init__(self, emp_id, emp_name)\n        print()\n    &quot;&quot;&quot;\n\n    def __init__(self, emp_id, emp_name):\n        &quot;&quot;&quot;Employee Class Constructor to initialize the object.\n\n        Input Arguments: emp_id must be int, emp_name must be str\n        &quot;&quot;&quot;\n        self.id = emp_id\n        self.name = emp_name\n\n    def print(self):\n        &quot;&quot;&quot;This method prints the employee information in a user friendly way.&quot;&quot;&quot;\n        print(f&#039;Employee&#x5B;{self.id}, {self.name}]&#039;)\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-css-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">3. Python Module Docstring Example<\/h3>\n\n\n\n<p>Let&#8217;s say we have defined the above function and class in <code>docstrings.py<\/code> file. Every Python script is also a module. We can define this module docstring as:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&quot;&quot;&quot;\nThis module shows some examples of Python Docstrings\n\nClasses: Employee\nFunctions: multiply(a, b)\n&quot;&quot;&quot;\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-css-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">How to Access Python Docstrings?<\/h2>\n\n\n\n<p>We can access the docstring value from a special attribute __doc__. Let&#8217;s see how to access docstring values defined above.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"> 1. Accessing Python Function Docstring<\/h3>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nprint(multiply.__doc__)\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"930\" height=\"888\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/05\/python-docstring-example-function.png\" alt=\"Python Docstring Example Function\" class=\"wp-image-220\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/05\/python-docstring-example-function.png 930w, https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/05\/python-docstring-example-function-300x286.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/05\/python-docstring-example-function-768x733.png 768w, https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/05\/python-docstring-example-function-24x24.png 24w\" sizes=\"auto, (max-width: 930px) 100vw, 930px\" \/><figcaption>Python Docstring Example<\/figcaption><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">2. Accessing Python Class and Method Docstrings<\/h3>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nprint(Employee.__doc__)\n\nprint(Employee.__init__.__doc__)\n\nprint(Employee.print.__doc__)\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"1008\" height=\"1024\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/05\/python-class-method-docstring-example-1008x1024.png\" alt=\"Python Class Method Docstring Example\" class=\"wp-image-221\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/05\/python-class-method-docstring-example-1008x1024.png 1008w, https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/05\/python-class-method-docstring-example-295x300.png 295w, https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/05\/python-class-method-docstring-example-768x780.png 768w, https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/05\/python-class-method-docstring-example-24x24.png 24w, https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/05\/python-class-method-docstring-example-48x48.png 48w, https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/05\/python-class-method-docstring-example.png 1360w\" sizes=\"auto, (max-width: 1008px) 100vw, 1008px\" \/><figcaption>Python Class and Methods Docstring Example<\/figcaption><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">3. Accessing Python Module Docstring<\/h3>\n\n\n\n<p>We will have to import the docstrings module. Then we can access its Docstring value using the __doc__ attribute. We have commented above print statements before importing the docstrings module to avoid executing the print() statements. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n$  python ls\ndocstrings.py\n$  python \n$  python python3.7\nPython 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21) \n&#x5B;Clang 6.0 (clang-600.0.57)] on darwin\nType &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.\n&gt;&gt;&gt; \n&gt;&gt;&gt; import docstrings\n&gt;&gt;&gt; \n&gt;&gt;&gt; docstrings.__doc__\n&#039;\\nThis module shows some examples of Python Docstrings\\n\\nClasses: Employee\\nFunctions: multiply(a, b)\\n&#039;\n&gt;&gt;&gt; \n&gt;&gt;&gt; docstrings.Employee.__doc__\n&#039;Employee class is used to hold employee object data.\\n\\n    Methods:\\n        __init__(self, emp_id, emp_name)\\n        print()\\n    &#039;\n&gt;&gt;&gt; \n&gt;&gt;&gt; \n&gt;&gt;&gt; docstrings.multiply.__doc__\n&#039;This method multiplies the given two numbers.\\n\\n    Input Arguments: a, b must be numbers.\\n    Returns: Multiplication of a and b.\\n    &#039;\n&gt;&gt;&gt; \n&gt;&gt;&gt; \n&gt;&gt;&gt; docstrings.Employee.print.__doc__\n&#039;This method prints the employee information in a user friendly way.&#039;\n&gt;&gt;&gt; \n<\/pre><\/div>\n\n\n<figure class=\"wp-block-image aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"383\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/05\/python-module-docstring-example-1024x383.png\" alt=\"Python Module Docstring Example\" class=\"wp-image-223\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/05\/python-module-docstring-example-1024x383.png 1024w, https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/05\/python-module-docstring-example-300x112.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/05\/python-module-docstring-example-768x287.png 768w, https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/05\/python-module-docstring-example-1536x574.png 1536w, https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/05\/python-module-docstring-example-2048x766.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption>Python Module Docstring<\/figcaption><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Python One-liner Docstring<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>When the python docstring is defined in a single line, it&#8217;s called a one-line docstring. <\/li><li>The opening quotes and closing quotes are on the same line.<\/li><li>There is no blank line before or after the docstring value.<\/li><li>The best practice is to end the docstring with a period.<\/li><li>It&#8217;s best suited for small utility functions where we don&#8217;t need to specify many things.<\/li><li>Provide meaningful docstring to specify the function details and the output. For example:<\/li><\/ul>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndef reverse_str(s):\n    &quot;&quot;&quot;Reverses the input string and returns it.&quot;&quot;&quot;\n    pass\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-css-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Python Multi-line Docstring<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>When the Docstring value spans into multiple lines, it&#8217;s called multi-line docstring.<\/li><li>The best practice for multi-line docstring is to start with a summary line, then a blank line followed by a more detailed explanation.<\/li><li>The summary line can be on the same line as the opening quotes or the next line.<\/li><li>The entire multi-line docstring is indented the same as the quotes in its first line.<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Python Docstring Best Practices<\/h2>\n\n\n\n<ol class=\"wp-block-list\"><li>The docstring of a Python script should specify how to use it. It should be printed when the script is executed with missing or wrong parameters.<\/li><li>Python module docstring should list all the classes, functions, exceptions, and dependencies on other modules. <\/li><li>Python function docstring should specify the behavior, input arguments, return types, and exceptions. If there are specific restrictions when the function can be called, it should be specified in the function docstring.<\/li><li>The docstring of a class should list all the methods and attributes. If it&#8217;s inheriting from a superclass, the details should be provided.<\/li><li>If a class method is overriding the superclass method, it should be specified.<\/li><li>Python is case-sensitive. So keep the function argument names exactly the same as in the function definition.<\/li><\/ol>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Python Docstring Format<\/h2>\n\n\n\n<p>There are no rules associated with the format of the docstring. But, following a specific style will make your code look good. There are two popular docstring formats.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1. Epytext format<\/h3>\n\n\n\n<p>This is very similar to javadoc style comments. It contains method description, params, return, and details about exceptions raised.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndef multiply(a, b):\n    &quot;&quot;&quot;This method multiplies the given two numbers.\n\n   @param a: this is the first param\n   @param b: this is the second param\n   @return: returns after multiplying a with b\n   @raise TypeError: raised when any of the params is not a number\n    &quot;&quot;&quot;\n\n    return a * b\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">2. <strong>reStructuredText<\/strong>&nbsp;(reST) format<\/h3>\n\n\n\n<p>This is a new style and it&#8217;s recommended in <a href=\"https:\/\/peps.python.org\/pep-0287\/\" target=\"_blank\" rel=\"noopener\">PEP-287<\/a>. This style is used by Sphinx to generate documentation.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndef multiply(a, b):\n    &quot;&quot;&quot;This method multiplies the given two numbers.\n\n   :param a: this is the first param\n   :param b: this is the second param\n   :return: returns after multiplying a with b\n   :raise TypeError: raised when any of the params is not a number\n    &quot;&quot;&quot;\n\n    return a * b\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">PyCharm docstring shortcut<\/h3>\n\n\n\n<p>PyCharm IDE auto-generates docstring in reST format for methods, just type triple double-quotes after the method declaration and hit enter.<\/p>\n\n\n\n<p>Since PyCharm IDE supports auto-generation of reST style docstring and it&#8217;s also recommended by PEP-287, you should write docstring in this format.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why You Should Follow Python Docstring Guidelines?<\/h2>\n\n\n\n<p>Python docstrings can be accessed with the __doc__ attribute. It&#8217;s very easy to build a system to parse the docstring and generate documentation of the project modules, classes, and functions. That&#8217;s why you should follow the docstring guidelines laid out in <a label=\"PEP-257 (opens in a new tab)\" href=\"https:\/\/peps.python.org\/pep-0257\/\" target=\"_blank\" rel=\"noreferrer noopener\">PEP-257<\/a>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Can we use Docstring for Multiline Comment?<\/h2>\n\n\n\n<p>I have seen many instances where the docstring is abused to provide multiline comments. Python doesn&#8217;t support multiline comments. If you want the comment to spread into multiple lines, start each line with the hash character. Don&#8217;t Abuse Python Docstrings.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<p>Python docstring provides useful information about the function, class, or module. We can access the docstring value with the __doc__ variable. We should use the reST format for writing docstring for methods.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s Next?<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/www.askpython.com\/python\/python-functions\">Functions in Python<\/a><\/li><li><a href=\"https:\/\/www.askpython.com\/python\/oops\/python-classes-objects\" data-type=\"post\" data-id=\"712\">Python Classes<\/a><\/li><li><a href=\"https:\/\/www.askpython.com\/python-modules\/python-modules\" data-type=\"post\" data-id=\"1222\">Modules in Python<\/a><\/li><li><a href=\"https:\/\/www.askpython.com\/python\/python-exception-handling\" data-type=\"post\" data-id=\"411\">Python Exception Handling<\/a><\/li><li><a href=\"https:\/\/www.askpython.com\/python\/oops\/object-oriented-programming-python\" data-type=\"post\" data-id=\"798\">OOPS in Python<\/a><\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Resources<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/peps.python.org\/pep-0287\/\" target=\"_blank\" rel=\"noopener\">PEP 287 \u2013 reStructuredText Docstring Format<\/a><\/li><li><a href=\"https:\/\/peps.python.org\/pep-0257\/\" target=\"_blank\" rel=\"noopener\">PEP 257 \u2013 Docstring Conventions<\/a><\/li><\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Python Docstring (Document String) is a string literal that is the first statement in a module, function, class, or method. How to Write a Python Docstring? Python docstring is surrounded by a pair of triple double-quotes (&#8220;&#8221;&#8221;). Let&#8217;s look at some examples of writing docstrings in Python. 1. Python Function Docstring Example 2. Python Class [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-219","post","type-post","status-publish","format-standard","hentry","category-python"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/219","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=219"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/219\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=219"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=219"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=219"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}