简体   繁体   中英

How can I generate documentation for a Python property setter using Sphinx?

I have a Python class something like the following, with docstrings intended to be converted into documentation by Sphinx :

class Direction(object):
    """
    A direction in which movement can be made.
    """
    def __init__(self):
        self._name = None

    @property
    def name(self):
        """
        The unique name of the direction.

        :return: The direction name
        :rtype: string
        """
        return self._name

    @name.setter
    def name(self, value):
        """
        Sets the direction name.

        :param string value: The direction name
        """
        self._name = value

The Sphinx output looks something like this:

class Direction (name) A direction in which movement can be made.

name The unique name of the direction.

Returns: The direction name

Return type: string

which is fine as far as it goes, but note the complete absence of any information about the name setter.

Is there any way to get Sphinx to generate documentation for the property setter?

Sphinx ignores docstrings on property setters so all documentation for a property must be on the @property method.

Whilst Sphinx understands certain specific tags (eg :param ...: ) it will accept any custom tags and will render them as labels for the text which follows them.

Therefore something like the following will render the documentation in a reasonable way ( getter , setter and type can be changed to any other text if required).

@property
def name(self):
    """
    The unique name of the direction.

    :getter: Returns this direction's name
    :setter: Sets this direction's name
    :type: string
    """
    return self._name

The generated documentation looks something like this:

class Direction (name) A direction in which movement can be made.

name The unique name of the direction.

Getter: Returns this direction's name

Setter: Sets this direction's name

Type: string

Thanks to @BrenBarm and @ABB for pointing me in the direction of this solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM