Search code examples
python-3.xpython-sphinxrestructuredtextautodoc

Can I override the docstring for a specific class property in Sphinx autodoc?


Using Sphinx 2.2.0 and python 3.6.8

I have two classes, A and B, and a property of A generates an instance B. I would like my sphinx html output to reference object B, but I would like the raw docstring not to have any sphinx/rest formatting. I am using autodoc and most of the methods and properties in A do not require this modification, but I would like to do it in a couple of places if possible.

class A(object):
    """
    This is class A.
    """
    @property
    def getB(self):
        """
        Get an instance of B.
        """
        return B()

    # A also includes many other methods and properties which 
    # I want to document using autodoc

class B(object):
    pass    

I can write Get an instance of :class:`<B>`. in the getB docstring, but then A.getB.__doc__ or help(A.getB) contain that exact text. I would like A.getB.__doc__ to stay Get an instance of B but have the reference in the html output generated by autodoc.

class A  
Bases: object  

    getB  
        Get an instance of B̲.

Assuming A is in a.py, I have tried

.. automodule:: a
   :member: A
   :exclude-member: getB

   .. method:: getB
      :property:

      get an instance of :class:`<B>`.

However this does not place B within the A class documentation or properly reference class B.

property a.getB
Get an instance of B.

class A
Bases: object

I have also tried .. method:: a.getB and .. method:: a.A.getB with no success.

Short of trying to get the autodoc output and modifying it directly, is there any way I can do this?


Solution

  • In order to place the output from .. method:: getB within the documentation of class A, you need to use autoclass instead of automodule.

    .. autoclass:: a.A
       :members:
       :exclude-members: getB
    
       .. method:: getB
          :property:
    
          Get an instance of :class:`B`.