Search code examples
pythondocumentationpython-sphinxtype-hintingread-the-docs

Types of setter arguments not showing in Sphinx documentation


I can't figure out how to get the type hints to appear in the Sphinx generated documentation from setters arguments.

I have a Python class with an attribute called batches and I've got docstrings in the property and type hinting in the setter argument (int). Below is the minimal example, but here is the full version

class Settings:
    """Settings used"""

    def __init__(self):
        self._batches = None 

    @property
    def batches(self):
        """Number of batches to simulate"""
        return self._batches

    @batches.setter
    def batches(self, batches: int):
        self._batches = batches

I'm building documentation with sphinx and using the following command

sphinx-build -b html ./source/ ./build/html/

In the conf.py I have the "sphinx_autodoc_typehints" package before the napoleon package as suggested by the sphinx docs. I have also tried putting it after just to check :-)

In the docs I am using :autosummary:

.. autosummary::
   :toctree: generated
   :nosignatures:
   :template: myclass.rst

The docs are building but the type hints are not appearing:

doc output


Solution

  • A property made using the decorators is for all purposes the same as an attribute. It is not a function. Sphinx honors this. Actually, Sphinx only read the documentation for the @property method, not the @property.setter one at all.

    In your case, specifying a type hint for the base property should be enough.

    class Settings:
    
        @property
        def batches(self) -> int:
            """Number of batches to simulate"""
            return self._batches
    

    In case your setter accepts other types (like floats, strings, etc) and manage to cast this input as an int internally, you can document that as prose in the base property, like so.

    class Settings:
    
        @property
        def batches(self) -> int:
            """Number of batches to simulate
    
            When set with a non integer value, the value is coerced
            as an integer, or will raise a :exc:`TypeError` if this 
            fails.
            """
            return self._batches
    
        @batches.setter
        def batches(self, batches: Union[int,str]):
            self._batches = int(batches)