How to document fields and properties in Python?

烂漫一生 提交于 2019-11-30 04:11:03
Eli Bendersky

Python has a PEP (257) that defines Docstring Conventions. Regarding documentation of attributes, it states:

String literals occurring immediately after a simple assignment at the top level of a module, class, or __init__ method are called "attribute docstrings".

So the following are considered documented attributes:

class Foo(object):
  velocity = 1  
  """Foo's initial velocity - class variable"""

  def __init__(self, args):
    self.location = 0.0 
    """Foo's initial location - instance variable"""   

(Edit: Fixed second docstring)

Documentation of a property in the python interpreter using help works fine for me, see proprerty documentation. Note: IPython's magic help operator, ?, did not display the property docstring.

>>> class foo(object):
>>>    def __init__(self, bar):
>>>        self._bar = bar
>>>    @property
>>>    def bar(self):
>>>        """bar property"""
>>>        return self._bar
>>> help(foo.bar)
Help on property:

    bar property

In Sphinx you must use the :members: directive to document properties, see autodoc documentation. Works like a charm for me!

Attributes will also be documented by Sphinx if :members: is used. Docstrings for attributes can be given as comments preceding the attribute, but using a colon following the hash mark, EG #: the foo attribute. From the Sphinx autodoc documentation:

For module data members and class attributes, documentation can either be put into a comment with special formatting (using a #: to start the comment instead of just #), or in a docstring after the definition. Comments need to be either on a line of their own before the definition, or immediately after the assignment on the same line. The latter form is restricted to one line only.

Document freely accessible attributes in the class docstring or make them into properties. You're documenting properties properly, the problem might be in 2.x and old-style classes, which don't support descriptors — inherit from object in that case.

With Sphinx notation / Restructured Text in your docstrings you can generate nicely formatted documentation from you Python sources automatically. It also supports arguments and return values for functions - no fields as far as I know, but you can easily create a list for them.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!