Search code examples
pythondocstring

How to document fields and properties in Python?


It's easy to document a class or method in Python:

class Something:
  """ Description of the class. """

  def do_it(self):
    """ Description of the method. """
    pass

  class_variable = 1 # How to comment?

  @property
  def give_me_some_special_dict(self):
    """ doesn't work! Doc of general dict will be shown. """
    return {}

But how to document a field or property for usage in API docs or help?


Solution

  • 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)