Python: document property to specify type

114 Views Asked by At

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

1

There are 1 best solutions below

0
On

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)

                """