1

Let's consider the following example:

from typing import Union
import numpy as np

class MyClass:
    def __init__(self):
        self._x = None
        
    @property
    def x(self) -> Union[float, np.ndarray]:
        if len(self._x) == 1:
            return self._x[0]
        else:
            return self._x
    
    @x.setter
    def x(self, value: Union[float, list, np.ndarray]):
        self._x = np.atleast_1d(value)

Any suggestion on how can I properly document the above code? I am using Sphinx and numpydoc.

Thanks a lot!

EDIT: I realized that my question is not really clear so I'm going to add few words. Basically, the main issue is how to document the fact that the x is a float, list or array in input and float or array as output. I saw in some examples that this should be done in the getter only and I don't know if I should add the keywords Parameters and Returns or if it is a better way to do it as I didn't find enough answers on this (or I just miss them).

mzjn
  • 48,958
  • 13
  • 128
  • 248
mauro
  • 504
  • 3
  • 14
  • 1
    Have you tried anything? What is the problem? – mzjn Oct 14 '21 at 11:48
  • This extension might be of interest: https://pypi.org/project/sphinx-autodoc-typehints/. Not sure if it works well with numpydoc though. – mzjn Oct 14 '21 at 15:00

1 Answers1

0

You can just explicitly assign the __doc__ attribute on the final property, like in:

class MyClass:
    def __init__(self):
        self._x = None
        
    @property
    def x(self) -> Union[float, np.ndarray]:
        ...
    
    @x.setter
    def x(self, value: Union[float, list, np.ndarray]):
        ...

    x.__doc__ = """\
                 Documentation text goes here.
                 (you may want to call textwrap.dedent on this string)

                """
jsbueno
  • 99,910
  • 10
  • 151
  • 209