### Configure admonition for examples Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/sphinxcontrib.napoleon.md Comparison of how example sections are rendered based on the napoleon_use_admonition_for_examples setting. ```default Example ------- This is just a quick example ``` ```default .. admonition:: Example This is just a quick example ``` ```default .. rubric:: Example This is just a quick example ``` -------------------------------- ### Document Functions with Google Style Source: https://context7.com/sphinx-contrib/napoleon/llms.txt Example of a Python function documented using the Google style guide. ```python def module_level_function(param1, param2=None, *args, **kwargs): """This is an example of a module level function. Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and description is optional, but should be included if not obvious. Args: param1 (int): The first parameter. param2 (:obj:`str`, optional): The second parameter. Defaults to None. Second line of description should be indented. *args: Variable length argument list. **kwargs: Arbitrary keyword arguments. Returns: bool: True if successful, False otherwise. The ``Returns`` section supports any reStructuredText formatting, including literal blocks:: { 'param1': param1, 'param2': param2 } Raises: AttributeError: The ``Raises`` section is a list of all exceptions that are relevant to the interface. ValueError: If `param2` is equal to `param1`. """ if param1 == param2: raise ValueError('param1 may not be equal to param2') return True ``` -------------------------------- ### NumPy Style Docstring Example Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/example_numpy.md A comprehensive example demonstrating the structure of a NumPy style docstring, including sections for parameters, returns, and examples. ```python def func(arg1, arg2): """Summary line. Extended description of function. Parameters ---------- arg1 : int Description of arg1 arg2 : str Description of arg2 Returns ------- bool Description of return value """ return True ``` -------------------------------- ### Google Style Python Docstring Example Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/example_google.md A comprehensive example demonstrating the structure and syntax of Google style docstrings in Python. ```python """Example Google style docstrings. This module demonstrates documentation as specified by the `Google Python Style Guide`_. Docstrings may extend over multiple lines. Sections are created with a section header and a colon followed by a block of indented text. Example: Examples can be given using either the ``Example`` or ``Examples`` sections. Sections support any reStructuredText formatting, including lists:: $ python example_google.py Section breaks are created by resuming unindented text. Section headers are case-insensitive and must be underlined with dashes. Attributes: module_level_variable1 (int): Module level variables may be documented in either the ``Attributes`` section of the module docstring, or in an inline docstring immediately following the variable. Todo: * For module TODOs. * You have to also use ``sphinx.ext.todo`` extension. .. _Google Python Style Guide: http://google.github.io/styleguide/pyguide.html """ module_level_variable1 = 12345 class ExampleClass(object): """The summary line for a class docstring should fit on one line. If the class has public attributes, they may be documented here in an ``Attributes`` section and follow the same formatting as a function's ``Args`` section. Alternatively, attributes may be documented inline with the attribute's declaration. Properties created with the ``@property`` decorator should be documented in the class's docstring. Attributes: attr1 (str): Description of `attr1`. attr2 (:obj:`int`, optional): Description of `attr2`. """ def __init__(self, param1, param2, param3=None): """Example of constructor docstring. Args: param1 (str): Description of `param1`. param2 (:obj:`int`, optional): Description of `param2`. Multiple lines are supported. param3 (:obj:`list` of :obj:`str`): Description of `param3`. """ self.attr1 = param1 self.attr2 = param2 self.attr3 = param3 #: Doc comment inline with attribute @property def readonly_property(self): """str: Properties should be documented in their getter method.""" return "readonly_content" def example_method(self, param1, param2): """The summary line for a method docstring should fit on one line. If a method's docstring has limited length, the summary and description can be combined. Args: param1 (int): The first parameter. param2 (str): The second parameter. Returns: bool: The return value. True for success, False otherwise. """ return True def __special__(self): """By default special members with docstrings are not included. These are ``__init__``, ``__str__``, etc. unless the ``napoleon_include_special_with_doc`` configuration option is set to True. """ pass def __undocumented__(self): """Undocumented members are excluded.""" pass def example_generator(n): """Generators have a ``Yields`` section instead of a ``Returns`` section. Args: n (int): The upper limit of the range to be generated. Yields: int: The next integer in the range of 0 to `n-1`. """ for i in range(n): yield i def example_raises(param1): """Raises sections should list all exceptions that are relevant. Args: param1 (int): The parameter to check. Raises: ValueError: If `param1` is equal to 42. """ if param1 == 42: raise ValueError("42 is the answer to everything!") ``` -------------------------------- ### POST /sphinxcontrib.napoleon.setup Source: https://github.com/sphinx-contrib/napoleon/blob/master/tests/docs/source/sphinxcontrib.napoleon.md The setup function called by Sphinx when the extension is loaded. ```APIDOC ## POST /sphinxcontrib.napoleon.setup ### Description Notifies Sphinx of the extension's capabilities during the initialization process. ### Method POST ### Endpoint sphinxcontrib.napoleon.setup ### Parameters #### Request Body - **app** (sphinx.application.Sphinx) - Required - The application object representing the current Sphinx process. ### Response #### Success Response (200) - **result** (Dict[unicode, Any]) - The configuration dictionary returned by the setup process. ``` -------------------------------- ### Install Sphinx Napoleon Source: https://context7.com/sphinx-contrib/napoleon/llms.txt Use pip to install the extension package. ```bash pip install sphinxcontrib-napoleon ``` -------------------------------- ### Google Style Docstring Example Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/index.md An example of a docstring formatted using the Google Python Style Guide, which is more legible than reStructuredText. ```text Args: path (str): The path of the file to wrap field_storage (FileStorage): The :class:`FileStorage` instance to wrap temporary (bool): Whether or not to delete the file when the File instance is destructed Returns: BufferedFileStorage: A buffered writable file descriptor ``` -------------------------------- ### Execute Python script via command line Source: https://github.com/sphinx-contrib/napoleon/blob/master/tests/docs/source/example_numpy.md Literal block example for running a Python script. ```text $ python example_numpy.py ``` -------------------------------- ### Include __init__ docstrings Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/sphinxcontrib.napoleon.md Example of how docstrings are treated when napoleon_include_init_with_doc is enabled. ```default def __init__(self): """ This will be included in the docs because it has a docstring """ def __init__(self): # This will NOT be included in the docs ``` -------------------------------- ### Sphinx Extension Setup Function Source: https://github.com/sphinx-contrib/napoleon/blob/master/tests/docs/source/sphinxcontrib.napoleon.md The setup function for the Napoleon Sphinx extension. It is executed when the extension is loaded by Sphinx to notify Sphinx of the extension's capabilities. ```python def setup(app: Sphinx) -> Dict[unicode, Any]: """Sphinx extension setup function.""" pass ``` -------------------------------- ### Exception Class Documentation Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/example_google.md This example shows how to document custom exception classes, similar to documenting regular classes. The __init__ method can be documented either at the class level or on the method itself. ```python class ExampleError(Exception): """Exceptions are documented in the same way as classes. The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself. Either form is acceptable, but the two should not be mixed. Choose one ``` -------------------------------- ### Google and NumPy Style Docstring Examples Source: https://github.com/sphinx-contrib/napoleon/blob/master/README.rst Comparison of function docstring formatting between Google and NumPy styles. ```python def func(arg1, arg2): """Summary line. Extended description of function. Args: arg1 (int): Description of arg1 arg2 (str): Description of arg2 Returns: bool: Description of return value """ return True ``` ```python def func(arg1, arg2): """Summary line. Extended description of function. Parameters ---------- arg1 : int Description of arg1 arg2 : str Description of arg2 Returns ------- bool Description of return value """ return True ``` -------------------------------- ### Demonstrate generator usage Source: https://github.com/sphinx-contrib/napoleon/blob/master/tests/docs/source/example_numpy.md Example of using a generator function in a doctest format. ```python >>> print([i for i in example_generator(4)]) [0, 1, 2, 3] ``` -------------------------------- ### NumPy Style Docstring Example Source: https://github.com/sphinx-contrib/napoleon/blob/master/tests/docs/source/example_numpy.md Demonstrates the NumPy style for Python docstrings. Ensure all parameters, return values, and raised exceptions are documented. ```python def example_numpy(param1, param2): """Example function with NumPy style docstring. Parameters ---------- param1 : int Description of parameter 1. param2 : str, optional Description of parameter 2. Defaults to 'default'. Returns ------- bool True if successful, False otherwise. Raises ------ ValueError If param1 is negative. """ if param1 < 0: raise ValueError('param1 cannot be negative') return True ``` -------------------------------- ### Install and Configure Napoleon Source: https://github.com/sphinx-contrib/napoleon/blob/master/README.rst Commands and configuration settings to enable the Napoleon extension in a Sphinx project. ```bash $ pip install sphinxcontrib-napoleon ``` ```python # conf.py # Add napoleon to the extensions list extensions = ['sphinxcontrib.napoleon'] ``` ```bash $ sphinx-apidoc -f -o docs/source projectdir ``` -------------------------------- ### Install Napoleon Extension Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/index.md Install the napoleon extension using pip. This command is used to add the extension to your Python environment. ```bash $ pip install sphinxcontrib-napoleon ``` -------------------------------- ### Define return value documentation format Source: https://github.com/sphinx-contrib/napoleon/blob/master/tests/docs/source/example_numpy.md Example of a literal block within a Returns section. ```text { 'param1': param1, 'param2': param2 } ``` -------------------------------- ### Python Exception Class with Docstring Source: https://github.com/sphinx-contrib/napoleon/blob/master/tests/docs/source/example_numpy.md Example of documenting a Python exception class using Google style docstrings. Includes parameters and attributes. ```python class ExampleError(Exception): """Exceptions are documented in the same way as classes. The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself. Either form is acceptable, but the two should not be mixed. Choose one convention to document the __init__ method and be consistent with it. Note ---- Do not include the `self` parameter in the ``Parameters`` section. Parameters ---------- msg : str Human readable string describing the exception. code : :obj:`int`, optional Numeric error code. Attributes ---------- msg : str Human readable string describing the exception. code : int Numeric error code. """ def __init__(self, msg, code): self.msg = msg self.code = code ``` -------------------------------- ### Example Google Style Python Docstrings Source: https://github.com/sphinx-contrib/napoleon/blob/master/tests/docs/source/example_google.md This snippet demonstrates the basic structure and common elements of Google style Python docstrings. It includes sections for arguments, return values, and raised exceptions. ```python def example_google_docstring(param1, param2): """Example function with Google style docstring. Args: param1 (str): The first parameter. param2 (int): The second parameter. Returns: bool: True if successful, False otherwise. Raises: ValueError: If param1 is empty. """ if not param1: raise ValueError("param1 cannot be empty") return True ``` -------------------------------- ### ExampleClass.__init__ Method Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/example_google.md Documentation for the __init__ method of ExampleClass, showing how to document parameters and attributes. ```APIDOC ## Method __init__ ### Description Example of docstring on the __init__ method. The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself. Either form is acceptable, but the two should not be mixed. Choose one convention to document the __init__ method and be consistent with it. Note: Do not include the `self` parameter in the ``Args`` section. ### Args - **param1** (str) - Description of `param1`. - **param2** (:obj:`int`, optional) - Description of `param2`. Multiple lines are supported. - **param3** (:obj:`list` of :obj:`str`) - Description of `param3`. ### Attributes - **attr1** (str) - Description of `attr1`. - **attr2** (:obj:`int`, optional) - Description of `attr2`. - **attr3** (str) - Doc comment *inline* with attribute - **attr4** (list of str) - Doc comment *before* attribute, with type specified - **attr5** (str) - Docstring *after* attribute, with type specified. ``` -------------------------------- ### ExampleClass.example_method Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/example_google.md Documentation for the example_method of ExampleClass. ```APIDOC ## Method example_method ### Description Class methods are similar to regular functions. Note: Do not include the `self` parameter in the ``Args`` section. ### Args - **param1** - The first parameter. - **param2** - The second parameter. ### Returns - **bool** - True if successful, False otherwise. ``` -------------------------------- ### ExampleClass API Documentation Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/example_numpy.md Documentation for the ExampleClass, its initialization parameters, properties, and methods. ```APIDOC ## ExampleClass ### Description Example of a class structure with attributes, properties, and methods documented using Napoleon-style docstrings. ### Parameters - **param1** (str) - Required - Description of param1. - **param2** (list of str) - Required - Description of param2. - **param3** (int) - Optional - Description of param3. ### Attributes - **attr1** (str) - Description of attr1. - **attr2** (int) - Optional - Description of attr2. ## example_method ### Description Class method example demonstrating parameter documentation and return values. ### Parameters - **param1** (unknown) - Required - The first parameter. - **param2** (unknown) - Required - The second parameter. ### Response - **return** (bool) - True if successful, False otherwise. ``` -------------------------------- ### Define Class with Attributes and Methods Source: https://github.com/sphinx-contrib/napoleon/blob/master/tests/docs/source/example_google.md Demonstrates documenting class attributes, __init__ parameters, and properties. ```python class ExampleClass(object): """The summary line for a class docstring should fit on one line. If the class has public attributes, they may be documented here in an ``Attributes`` section and follow the same formatting as a function's ``Args`` section. Alternatively, attributes may be documented inline with the attribute's declaration (see __init__ method below). Properties created with the ``@property`` decorator should be documented in the property's getter method. Attributes: attr1 (str): Description of `attr1`. attr2 (:obj:`int`, optional): Description of `attr2`. """ def __init__(self, param1, param2, param3): """Example of docstring on the __init__ method. The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself. Either form is acceptable, but the two should not be mixed. Choose one convention to document the __init__ method and be consistent with it. Note: Do not include the `self` parameter in the ``Args`` section. Args: param1 (str): Description of `param1`. param2 (:obj:`int`, optional): Description of `param2`. Multiple lines are supported. param3 (:obj:`list` of :obj:`str`): Description of `param3`. """ self.attr1 = param1 self.attr2 = param2 self.attr3 = param3 #: Doc comment *inline* with attribute #: list of str: Doc comment *before* attribute, with type specified self.attr4 = ['attr4'] self.attr5 = None """str: Docstring *after* attribute, with type specified.""" @property def readonly_property(self): """str: Properties should be documented in their getter method.""" return 'readonly_property' @property def readwrite_property(self): """:obj:`list` of :obj:`str`: Properties with both a getter and setter should only be documented in their getter method. If the setter method contains notable behavior, it should be mentioned here. """ return ['readwrite_property'] @readwrite_property.setter def readwrite_property(self, value): value def example_method(self, param1, param2): """Class methods are similar to regular functions. Note: Do not include the `self` parameter in the ``Args`` section. Args: param1: The first parameter. param2: The second parameter. Returns: True if successful, False otherwise. """ return True ``` -------------------------------- ### ExampleClass Documentation Source: https://github.com/sphinx-contrib/napoleon/blob/master/tests/docs/source/example_numpy.md Demonstrates the documentation of a Python class, its attributes, and its constructor using Google style docstrings. ```APIDOC ## Class ExampleClass ### Description The summary line for a class docstring should fit on one line. If the class has public attributes, they may be documented here in an ``Attributes`` section and follow the same formatting as a function's ``Args`` section. Alternatively, attributes may be documented inline with the attribute's declaration (see __init__ method below). Properties created with the ``@property`` decorator should be documented in the property's getter method. ### Attributes #### attr1 (str) - Description of `attr1`. #### attr2 (:obj:`int`, optional) - Description of `attr2`. ### Methods #### __init__(param1, param2, param3) ##### Description Example of docstring on the __init__ method. The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself. Either form is acceptable, but the two should not be mixed. Choose one convention to document the __init__ method and be consistent with it. ##### Parameters ###### param1 (str) - Description of `param1`. ###### param2 (:obj:`list` of :obj:`str`) - Description of `param2`. Multiple lines are supported. ###### param3 (:obj:`int`, optional) - Description of `param3`. ##### Attributes - **attr1** (str) - Description of `attr1`. - **attr2** (:obj:`int`, optional) - Description of `attr2`. - **attr3** - Doc comment *inline* with attribute - **attr4** (list of str) - Doc comment *before* attribute, with type specified - **attr5** (str) - Docstring *after* attribute, with type specified. #### readonly_property() ##### Description str: Properties should be documented in their getter method. ##### Returns - **str** - readonly_property #### readwrite_property() ##### Description :obj:`list` of :obj:`str`: Properties with both a getter and setter should only be documented in their getter method. If the setter method contains notable behavior, it should be mentioned here. ##### Returns - **list of str** - readwrite_property #### readwrite_property(value) ##### Description Setter for the readwrite_property. #### example_method(param1, param2) ##### Description Class methods are similar to regular functions. ##### Parameters ###### param1 - The first parameter. ###### param2 - The second parameter. ##### Returns - **bool** - True if successful, False otherwise. #### __special__() ##### Description By default special members with docstrings are not included. Special members are any methods or attributes that start with and end with a double underscore. Any special member with a docstring will be included in the output, if ``napoleon_include_special_with_doc`` is set to True. This behavior can be enabled by changing the following setting in Sphinx's conf.py:: napoleon_include_special_with_doc = True #### _private() ##### Description By default private members are not included. Private members are any methods or attributes that start with an underscore and are *not* special. By default they are not included in the output. This behavior can be changed such that private members *are* included by changing the following setting in Sphinx's conf.py:: napoleon_include_private_with_doc = True ``` -------------------------------- ### ReStructuredText Docstring Example Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/index.md An example of a docstring formatted using reStructuredText, which is visually dense and harder to read. ```text :param path: The path of the file to wrap :type path: str :param field_storage: The :class:`FileStorage` instance to wrap :type field_storage: FileStorage :param temporary: Whether or not to delete the file when the File instance is destructed :type temporary: bool :returns: A buffered writable file descriptor :rtype: BufferedFileStorage ``` -------------------------------- ### Python Generator Function Example Source: https://github.com/sphinx-contrib/napoleon/blob/master/tests/docs/source/example_numpy.md A simple Python generator function. ```python for i in range(n): yield i ``` -------------------------------- ### ExampleClass Documentation Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/example_google.md Documentation for the ExampleClass, demonstrating various docstring conventions for attributes, properties, and methods. ```APIDOC ## Class ExampleClass ### Description The summary line for a class docstring should fit on one line. If the class has public attributes, they may be documented here in an ``Attributes`` section and follow the same formatting as a function's ``Args`` section. Alternatively, attributes may be documented inline with the attribute's declaration (see __init__ method below). Properties created with the ``@property`` decorator should be documented in the property's getter method. ### Attributes - **attr1** (str) - Description of `attr1`. - **attr2** (:obj:`int`, optional) - Description of `attr2`. ``` -------------------------------- ### Include special members with docstrings Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/sphinxcontrib.napoleon.md Example of how special members are treated when napoleon_include_special_with_doc is enabled. ```default def __str__(self): """ This will be included in the docs because it has a docstring """ return unicode(self).encode('utf-8') def __unicode__(self): # This will NOT be included in the docs return unicode(self.__class__.__name__) ``` -------------------------------- ### Include private members with docstrings Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/sphinxcontrib.napoleon.md Example of how private members are treated when napoleon_include_private_with_doc is enabled. ```default def _included(self): """ This will be included in the docs because it has a docstring """ pass def _skipped(self): # This will NOT be included in the docs pass ``` -------------------------------- ### ExampleError Documentation Source: https://github.com/sphinx-contrib/napoleon/blob/master/tests/docs/source/example_numpy.md Demonstrates the documentation of a Python exception class, its parameters, and attributes using Google style docstrings. ```APIDOC ## Exception ExampleError ### Description Exceptions are documented in the same way as classes. The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself. Either form is acceptable, but the two should not be mixed. Choose one convention to document the __init__ method and be consistent with it. ### Parameters #### msg (str) - Human readable string describing the exception. #### code (:obj:`int`, optional) - Numeric error code. ### Attributes #### msg (str) - Human readable string describing the exception. #### code (int) - Numeric error code. ``` -------------------------------- ### ExampleClass._private Method Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/example_google.md Documentation for the _private method of ExampleClass, explaining its inclusion criteria. ```APIDOC ## Method _private ### Description By default private members are not included. Private members are any methods or attributes that start with an underscore and are *not* special. By default they are not included in the output. This behavior can be changed such that private members *are* included by changing the following setting in Sphinx's conf.py:: napoleon_include_private_with_doc = True ``` -------------------------------- ### Define Class with Attributes and Methods Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/example_google.md Shows how to document class attributes, __init__ parameters, and properties using Napoleon syntax. ```python class ExampleClass(object): """The summary line for a class docstring should fit on one line. If the class has public attributes, they may be documented here in an ``Attributes`` section and follow the same formatting as a function's ``Args`` section. Alternatively, attributes may be documented inline with the attribute's declaration (see __init__ method below). Properties created with the ``@property`` decorator should be documented in the property's getter method. Attributes: attr1 (str): Description of `attr1`. attr2 (:obj:`int`, optional): Description of `attr2`. """ def __init__(self, param1, param2, param3): """Example of docstring on the __init__ method. The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself. Either form is acceptable, but the two should not be mixed. Choose one convention to document the __init__ method and be consistent with it. Note: Do not include the `self` parameter in the ``Args`` section. Args: param1 (str): Description of `param1`. param2 (:obj:`int`, optional): Description of `param2`. Multiple lines are supported. param3 (:obj:`list` of :obj:`str`): Description of `param3`. """ self.attr1 = param1 self.attr2 = param2 self.attr3 = param3 #: Doc comment *inline* with attribute #: list of str: Doc comment *before* attribute, with type specified self.attr4 = ['attr4'] self.attr5 = None """str: Docstring *after* attribute, with type specified.""" @property def readonly_property(self): """str: Properties should be documented in their getter method.""" return 'readonly_property' @property def readwrite_property(self): """:obj:`list` of :obj:`str`: Properties with both a getter and setter should only be documented in their getter method. If the setter method contains notable behavior, it should be mentioned here. """ return ['readwrite_property'] @readwrite_property.setter def readwrite_property(self, value): value def example_method(self, param1, param2): """Class methods are similar to regular functions. Note: Do not include the `self` parameter in the ``Args`` section. Args: param1: The first parameter. param2: The second parameter. Returns: True if successful, False otherwise. """ return True def __special__(self): """By default special members with docstrings are not included. Special members are any methods or attributes that start with and end with a double underscore. Any special member with a docstring will be included in the output, if ``napoleon_include_special_with_doc`` is set to True. This behavior can be enabled by changing the following setting in Sphinx's conf.py:: napoleon_include_special_with_doc = True """ pass def __special_without_docstring__(self): pass def _private(self): """By default private members are not included. Private members are any methods or attributes that start with an underscore and are *not* special. By default they are not included in the output. This behavior can be changed such that private members *are* included by changing the following setting in Sphinx's conf.py:: napoleon_include_private_with_doc = True """ pass def _private_without_docstring(self): pass ``` -------------------------------- ### Function: example_generator Source: https://github.com/sphinx-contrib/napoleon/blob/master/tests/docs/source/example_numpy.md Demonstrates a generator function that yields values based on an input limit. ```APIDOC ## example_generator ### Description Generators have a Yields section instead of a Returns section to provide the next number in a range. ### Parameters - **n** (int) - Required - The upper limit of the range to generate, from 0 to n - 1. ### Response #### Success Response (200) - **yielded_value** (int) - The next number in the range of 0 to n - 1. ``` -------------------------------- ### ExampleClass.readwrite_property Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/example_google.md Documentation for the readwrite_property of ExampleClass, including getter and setter information. ```APIDOC ## Property readwrite_property ### Description Properties with both a getter and setter should only be documented in their getter method. If the setter method contains notable behavior, it should be mentioned here. ### Returns - **list** of **str** - readwrite_property ``` -------------------------------- ### Generator Function with Yields Section Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/example_numpy.md This generator function uses a 'Yields' section instead of 'Returns' to document the type of values it yields. The example demonstrates its usage in doctest format. ```python def example_generator(n): """Generators have a ``Yields`` section instead of a ``Returns`` section. Parameters ---------- n : int The upper limit of the range to generate, from 0 to `n` - 1. Yields ------ int The next number in the range of 0 to `n` - 1. Examples -------- Examples should be written in doctest format, and should illustrate how to use the function. >>> print([i for i in example_generator(4)]) [0, 1, 2, 3] """ ``` -------------------------------- ### ExampleClass.__special__ Method Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/example_google.md Documentation for the __special__ method of ExampleClass, explaining its inclusion criteria. ```APIDOC ## Method __special__ ### Description By default special members with docstrings are not included. Special members are any methods or attributes that start with and end with a double underscore. Any special member with a docstring will be included in the output, if ``napoleon_include_special_with_doc`` is set to True. This behavior can be enabled by changing the following setting in Sphinx's conf.py:: napoleon_include_special_with_doc = True ``` -------------------------------- ### ExampleError Exception Documentation Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/example_numpy.md Documentation for the ExampleError custom exception class. ```APIDOC ## ExampleError ### Description Custom exception class documented using Napoleon-style docstrings. ### Parameters - **msg** (str) - Required - Human readable string describing the exception. - **code** (int) - Optional - Numeric error code. ### Attributes - **msg** (str) - Human readable string describing the exception. - **code** (int) - Numeric error code. ``` -------------------------------- ### Generator Function with Yields Section Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/example_google.md This generator function uses a ``Yields`` section instead of a ``Returns`` section to document the values it yields. It also includes an ``Examples`` section in doctest format. ```python def example_generator(n): """Generators have a ``Yields`` section instead of a ``Returns`` section. Args: n (int): The upper limit of the range to generate, from 0 to `n` - 1. Yields: int: The next number in the range of 0 to `n` - 1. Examples: Examples should be written in doctest format, and should illustrate how to use the function. >>> print([i for i in example_generator(4)]) [0, 1, 2, 3] """ for i in range(n): yield i ``` -------------------------------- ### Build API Documentation with sphinx-apidoc Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/index.md Use sphinx-apidoc to generate API documentation from your project. The -f flag forces overwriting existing files. ```bash $ sphinx-apidoc -f -o docs/source projectdir ``` -------------------------------- ### Documenting functions with NumPy style Source: https://context7.com/sphinx-contrib/napoleon/llms.txt Use underlined headers for Parameters, Returns, and Raises sections in NumPy style docstrings. ```python def module_level_function(param1, param2=None, *args, **kwargs): """This is an example of a module level function. Function parameters should be documented in the ``Parameters`` section. The name of each parameter is required. The type and description of each parameter is optional, but should be included if not obvious. Parameters ---------- param1 : int The first parameter. param2 : :obj:`str`, optional The second parameter. *args Variable length argument list. **kwargs Arbitrary keyword arguments. Returns ------- bool True if successful, False otherwise. Raises ------ AttributeError The ``Raises`` section is a list of all exceptions that are relevant to the interface. ValueError If `param2` is equal to `param1`. """ if param1 == param2: raise ValueError('param1 may not be equal to param2') return True ``` -------------------------------- ### Python Class with Inline and Standard Docstrings Source: https://github.com/sphinx-contrib/napoleon/blob/master/tests/docs/source/example_numpy.md Demonstrates documenting a Python class, including attributes documented inline and in the class docstring, and properties. ```python class ExampleClass(object): """The summary line for a class docstring should fit on one line. If the class has public attributes, they may be documented here in an ``Attributes`` section and follow the same formatting as a function's ``Args`` section. Alternatively, attributes may be documented inline with the attribute's declaration (see __init__ method below). Properties created with the ``@property`` decorator should be documented in the property's getter method. Attributes ---------- attr1 : str Description of `attr1`. attr2 : :obj:`int`, optional Description of `attr2`. """ def __init__(self, param1, param2, param3): """Example of docstring on the __init__ method. The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself. Either form is acceptable, but the two should not be mixed. Choose one convention to document the __init__ method and be consistent with it. Note ---- Do not include the `self` parameter in the ``Parameters`` section. Parameters ---------- param1 : str Description of `param1`. param2 : :obj:`list` of :obj:`str` Description of `param2`. Multiple lines are supported. param3 : :obj:`int`, optional Description of `param3`. """ self.attr1 = param1 self.attr2 = param2 self.attr3 = param3 #: Doc comment *inline* with attribute #: list of str: Doc comment *before* attribute, with type specified self.attr4 = ["attr4"] self.attr5 = None """str: Docstring *after* attribute, with type specified.""" @property def readonly_property(self): """str: Properties should be documented in their getter method.""" return "readonly_property" @property def readwrite_property(self): """:obj:`list` of :obj:`str`: Properties with both a getter and setter should only be documented in their getter method. If the setter method contains notable behavior, it should be mentioned here. """ return ["readwrite_property"] @readwrite_property.setter def readwrite_property(self, value): value def example_method(self, param1, param2): """Class methods are similar to regular functions. Note ---- Do not include the `self` parameter in the ``Parameters`` section. Parameters ---------- param1 The first parameter. param2 The second parameter. Returns ------- bool True if successful, False otherwise. """ return True def __special__(self): """By default special members with docstrings are not included. Special members are any methods or attributes that start with and end with a double underscore. Any special member with a docstring will be included in the output, if ``napoleon_include_special_with_doc`` is set to True. This behavior can be enabled by changing the following setting in Sphinx's conf.py:: napoleon_include_special_with_doc = True """ pass def __special_without_docstring__(self): pass def _private(self): """By default private members are not included. Private members are any methods or attributes that start with an underscore and are *not* special. By default they are not included in the output. This behavior can be changed such that private members *are* included by changing the following setting in Sphinx's conf.py:: napoleon_include_private_with_doc = True """ pass def _private_without_docstring(self): pass ``` -------------------------------- ### Documenting classes with Google style Source: https://context7.com/sphinx-contrib/napoleon/llms.txt Use Attributes sections and standard method docstrings for class documentation in Google style. ```python class ExampleClass(object): """The summary line for a class docstring should fit on one line. If the class has public attributes, they may be documented here in an ``Attributes`` section and follow the same formatting as a function's ``Args`` section. Attributes: attr1 (str): Description of `attr1`. attr2 (:obj:`int`, optional): Description of `attr2`. """ def __init__(self, param1, param2, param3): """Example of docstring on the __init__ method. Note: Do not include the `self` parameter in the ``Args`` section. Args: param1 (str): Description of `param1`. param2 (:obj:`int`, optional): Description of `param2`. Multiple lines are supported. param3 (:obj:`list` of :obj:`str`): Description of `param3`. """ self.attr1 = param1 self.attr2 = param2 self.attr3 = param3 #: Doc comment *inline* with attribute #: list of str: Doc comment *before* attribute, with type specified self.attr4 = ['attr4'] self.attr5 = None """str: Docstring *after* attribute, with type specified.""" @property def readonly_property(self): """str: Properties should be documented in their getter method.""" return 'readonly_property' def example_method(self, param1, param2): """Class methods are similar to regular functions. Note: Do not include the `self` parameter in the ``Args`` section. Args: param1: The first parameter. param2: The second parameter. Returns: True if successful, False otherwise. """ return True ``` -------------------------------- ### Define parameter documentation format Source: https://github.com/sphinx-contrib/napoleon/blob/master/tests/docs/source/example_numpy.md Standard format for documenting function parameters in NumPy style. ```text name : type description The description may span multiple lines. Following lines should be indented to match the first line of the description. The ": type" is optional. Multiple paragraphs are supported in parameter descriptions. ``` -------------------------------- ### Define Exception Class with Docstrings Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/example_google.md Demonstrates documenting an exception class with Args and Attributes sections. ```python def __init__(self, msg, code): self.msg = msg self.code = code ``` -------------------------------- ### Documenting with PEP 484 type annotations Source: https://context7.com/sphinx-contrib/napoleon/llms.txt Simplify docstrings by using Python 3 type annotations in function signatures. ```python def function_with_pep484_type_annotations(param1: int, param2: str) -> bool: """Example function with PEP 484 type annotations. Args: param1: The first parameter. param2: The second parameter. Returns: The return value. True for success, False otherwise. """ return True ``` -------------------------------- ### Documenting generators with Yields Source: https://context7.com/sphinx-contrib/napoleon/llms.txt Use the Yields section to document generator functions. ```python def example_generator(n): """Generators have a ``Yields`` section instead of a ``Returns`` section. Args: n (int): The upper limit of the range to generate, from 0 to `n` - 1. Yields: int: The next number in the range of 0 to `n` - 1. Examples: Examples should be written in doctest format, and should illustrate how to use the function. >>> print([i for i in example_generator(4)]) [0, 1, 2, 3] """ for i in range(n): yield i ``` -------------------------------- ### Module Level Function with Detailed Docstring Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/example_numpy.md This function demonstrates a comprehensive NumPy style docstring, including sections for Parameters, Returns, and Raises. It also shows how to document variable arguments and multi-line descriptions. ```python def module_level_function(param1, param2=None, *args, **kwargs): """This is an example of a module level function. Function parameters should be documented in the ``Parameters`` section. The name of each parameter is required. The type and description of each parameter is optional, but should be included if not obvious. If *args or **kwargs are accepted, they should be listed as ``*args`` and ``**kwargs``. The format for a parameter is:: name : type description The description may span multiple lines. Following lines should be indented to match the first line of the description. The ": type" is optional. Multiple paragraphs are supported in parameter descriptions. Parameters ---------- param1 : int The first parameter. param2 : :obj:`str`, optional The second parameter. *args Variable length argument list. **kwargs Arbitrary keyword arguments. Returns ------- bool True if successful, False otherwise. The return type is not optional. The ``Returns`` section may span multiple lines and paragraphs. Following lines should be indented to match the first line of the description. The ``Returns`` section supports any reStructuredText formatting, including literal blocks:: { 'param1': param1, 'param2': param2 } Raises ------ AttributeError The ``Raises`` section is a list of all exceptions that are relevant to the interface. ValueError If `param2` is equal to `param1`. """ if param1 == param2: raise ValueError('param1 may not be equal to param2') return True ``` -------------------------------- ### Module Level Variable Documentation Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/example_numpy.md Demonstrates documenting module-level variables. Choose either the 'Attributes' section or an inline docstring, but not both. ```python module_level_variable1 = 12345 ``` ```python module_level_variable2 = 98765 """int: Module level variable documented inline. The docstring may span multiple lines. The type may optionally be specified on the first line, separated by a colon. """ ``` -------------------------------- ### Configure Napoleon with custom settings Source: https://context7.com/sphinx-contrib/napoleon/llms.txt Initialize a Config object to define parsing behavior for docstrings and custom sections, then use it to parse a docstring. ```python config = Config( napoleon_google_docstring=True, # Parse Google style docstrings napoleon_numpy_docstring=True, # Parse NumPy style docstrings napoleon_include_init_with_doc=True, # Include __init__ with docstrings napoleon_include_private_with_doc=True, # Include _private members napoleon_include_special_with_doc=True, # Include __special__ members napoleon_use_admonition_for_examples=True, # Use admonition for Examples napoleon_use_admonition_for_notes=True, # Use admonition for Notes napoleon_use_ivar=True, # Use :ivar: for instance variables napoleon_use_param=True, # Use :param: for parameters napoleon_use_rtype=True, # Use :rtype: for return type napoleon_use_keyword=True, # Use :keyword: for keyword args napoleon_custom_sections=[ # Add custom sections 'Custom Section', # Generic custom section ('Inputs', 'Parameters'), # Alias for Parameters ] ) # Use config with docstring parser docstring = '''Summary. Custom Section: This is a custom section that will be rendered. Inputs: arg1 (int): This uses the Parameters format. ''' parsed = GoogleDocstring(docstring, config) print(parsed) ``` -------------------------------- ### Use PEP 484 Type Annotations with Google Style Source: https://github.com/sphinx-contrib/napoleon/blob/master/docs/source/index.md Integrates Python 3 type hints directly into the function signature, allowing static analysis tools to process types. ```default def func(arg1: int, arg2: str) -> bool: """Summary line. Extended description of function. Args: arg1: Description of arg1 arg2: Description of arg2 Returns: Description of return value """ return True ``` -------------------------------- ### Configuring Napoleon settings Source: https://context7.com/sphinx-contrib/napoleon/llms.txt Import the Config class to manage Napoleon settings programmatically. ```python from sphinxcontrib.napoleon import Config, GoogleDocstring ```