Sphinx注釋自動生成Python文檔

      網友投稿 1050 2022-05-29

      Sphinx自動生成Python文檔

      sphinx是一種基于Python的文檔工具,它可以令人輕松的撰寫出清晰且優美的文檔,由Georg Brandl在BSD許可證下開發。新版的Python3文檔就是由sphinx生成的,其他諸如機器學習庫scikit-learn、Jupyter Notebook也是基于sphinx生成的。

      安裝sphinx包

      pip install sphinx

      嘗試

      > Separate source and build directories (y/n) [n]: y > Project name: sphinx_test > Author name(s): liyu > Project release []: 1.0 > Project language [en]: zh_CN 或 回車默認英文

      5.在doc/source/conf.py指定項目代碼路徑

      import os import sys sys.path.insert(0, os.path.abspath('../../src'))

      6.在doc/source/conf.py修改擴展extensions,添加功能【包括注釋中的文檔】、【支持NumPy和Google風格】、【包括測試片段】、【鏈接到其他項目的文檔】、【TODO項】、【文檔覆蓋率統計】、【通過javascript呈現數學】

      extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.mathjax', ]

      8.生成HTMLmake html

      9.打開build/html/google_style

      重新生成文檔

      項目代碼未變更

      在doc下執行命令make clean

      在doc下執行命令make html(直接也行)

      項目代碼已變更

      刪除doc/build下的所有文件夾

      刪除doc/source下除index.rst的所有.rst文件

      在doc下執行命令sphinx-apidoc -o source …/src/

      在doc下執行命令make html

      切換主題

      Sphinx注釋自動生成Python文檔

      1.安裝主題pip install sphinx_rtd_theme

      2.修改doc/source/conf.py的html_theme

      html_theme = 'sphinx_rtd_theme'

      3.重新生成

      主題可以參考

      https://www.sphinx-doc.org/en/master/examples.html#documentation-using-the-alabaster-theme

      https://www.sphinx-doc.org/en/master/usage/theming.html

      napoleon支持Numpy和Google_style風格

      https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html

      設置PyCharm Docstrings風格

      代碼:

      numpy_style:

      """Example NumPy style docstrings. This module demonstrates documentation as specified by the `NumPy Documentation HOWTO`_. Docstrings may extend over multiple lines. Sections are created with a section header followed by an underline of equal length. Example ------- Examples can be given using either the ``Example`` or ``Examples`` sections. Sections support any reStructuredText formatting, including literal blocks:: $ python example_numpy.py Section breaks are created with two blank lines. Section breaks are also implicitly created anytime a new section starts. Section bodies *may* be indented: Notes ----- This is an example of an indented section. It's like any other section, but the body is indented to help it stand out from surrounding text. If a section is indented, then a section break is created by resuming unindented text. 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. Either form is acceptable, but the two should not be mixed. Choose one convention to document module level variables and be consistent with it. .. _NumPy Documentation HOWTO: https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt """ module_level_variable1 = 12345 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. """ def function_with_types_in_docstring(param1, param2): """Example function with types documented in the docstring. `PEP 484`_ type annotations are supported. If attribute, parameter, and return types are annotated according to `PEP 484`_, they do not need to be included in the docstring: Parameters ---------- param1 : int The first parameter. param2 : str The second parameter. Returns ------- bool True if successful, False otherwise. .. _PEP 484: https://www.python.org/dev/peps/pep-0484/ """ def function_with_pep484_type_annotations(param1: int, param2: str) -> bool: """Example function with PEP 484 type annotations. The return type must be duplicated in the docstring to comply with the NumPy docstring style. Parameters ---------- param1 The first parameter. param2 The second parameter. Returns ------- bool True if successful, False otherwise. """ 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 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] """ for i in range(n): yield i 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 class ExampleClass: """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 : list(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(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): """list(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

      google_style:

      """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 literal blocks:: $ python example_google.py Section breaks are created by resuming unindented text. Section breaks are also implicitly created anytime a new section starts. 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. Either form is acceptable, but the two should not be mixed. Choose one convention to document module level variables and be consistent with it. Todo: * For module TODOs * You have to also use ``sphinx.ext.todo`` extension .. _Google Python Style Guide: https://google.github.io/styleguide/pyguide.html """ module_level_variable1 = 12345 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. """ def function_with_types_in_docstring(param1, param2): """Example function with types documented in the docstring. `PEP 484`_ type annotations are supported. If attribute, parameter, and return types are annotated according to `PEP 484`_, they do not need to be included in the docstring: Args: param1 (int): The first parameter. param2 (str): The second parameter. Returns: bool: The return value. True for success, False otherwise. .. _PEP 484: https://www.python.org/dev/peps/pep-0484/ """ 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. """ 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 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. The "(type)" is optional. Multiple paragraphs are supported in parameter descriptions. 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 return type is optional and may be specified at the beginning of the ``Returns`` section followed by a colon. The ``Returns`` section may span multiple lines and paragraphs. Following lines should be indented to match the first line. 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 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 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 ``Args`` section. Args: msg (str): Human readable string describing the exception. code (:obj:`int`, optional): Error code. Attributes: msg (str): Human readable string describing the exception. code (int): Exception error code. """ def __init__(self, msg, code): self.msg = msg self.code = code class ExampleClass: """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 (list(str)): Description of `param3`. """ self.attr1 = param1 self.attr2 = param2 self.attr3 = param3 #: Doc comment *inline* with attribute #: list(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): """list(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

      最后,大家喜歡的話歡迎和關注哈(^o^)/~

      AI EI企業智能 EI創新孵化Lab 機器學習 運籌優化

      版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。

      上一篇:如何電腦上共享代碼
      下一篇:React Native發布重構路線圖
      相關文章
      亚洲一级高清在线中文字幕| 亚洲国产一区国产亚洲| 亚洲男女性高爱潮网站| 亚洲AV人人澡人人爽人人夜夜| 中文亚洲成a人片在线观看| 亚洲AV无码一区二区三区国产| 亚洲成AV人影片在线观看| 亚洲中文字幕无码av| 亚洲AV无码一区二区三区人 | 亚洲成?v人片天堂网无码| 理论亚洲区美一区二区三区| 国产亚洲精品AAAA片APP| 亚洲中文字幕无码爆乳| 亚洲国产一区二区三区在线观看| 亚洲一区二区三区高清在线观看 | 91麻豆精品国产自产在线观看亚洲 | 亚洲精品无码Av人在线观看国产 | 久久精品国产亚洲综合色| 亚洲精品V欧洲精品V日韩精品 | 亚洲a无码综合a国产av中文| 色九月亚洲综合网| 亚洲精品国产成人影院| 国产精品亚洲玖玖玖在线观看| 国产AV无码专区亚洲AWWW| 亚洲国产一二三精品无码| 无码专区—VA亚洲V天堂| 久久久久亚洲av无码专区导航| 亚洲精品成人久久| 亚洲国产日韩视频观看| 亚洲AV香蕉一区区二区三区| 国产精品亚洲小说专区| 国产成人精品亚洲精品| 国产精品亚洲片在线| 亚洲韩国—中文字幕| 亚洲国产美女精品久久久久| 最新亚洲精品国偷自产在线 | 亚洲黄色片在线观看| 亚洲伊人色一综合网| 亚洲精品亚洲人成在线| 一区二区三区亚洲视频| 国产偷国产偷亚洲清高动态图|