# Sphinx autodoc extension

## Extension

The `guidata` library provides a Sphinx extension to automatically document data set classes (`guidata.dataset.datatypes.DataSet`). This extension is based on the Sphinx autodoc extension.

Three directives are provided:

> - `.. autodataset_create:: [module.dataset].create` to document the `create()` classmethod of a `DataSet` using its `DataItem`.

> - `.. datasetnote:: [module.dataset] [n]` to display a note on how to instanciate a dataset. Optional parameter `n` gives the number of items to show.

> - `.. autodataset:: [module.dataset]` used to document a dataset class. It is derived from the `.. autoclass::` directive and therefore has the same options. By default, it will document a dataset without its constructor signature but will document its attributes and the `create()` class method using the `autodataset_create` directive. Several additional options are available to more finely tune the documentation (see examples below).

## Example dataset

    # -*- coding: utf-8 -*-

    import atexit
    import datetime
    import shutil
    import tempfile

    import guidata.dataset as gds

    # Creating temporary files and registering cleanup functions
    TEMPDIR = tempfile.mkdtemp(prefix="test_")
    atexit.register(shutil.rmtree, TEMPDIR)
    FILE_ETA = tempfile.NamedTemporaryFile(suffix=".eta", dir=TEMPDIR)
    atexit.register(FILE_ETA.close)
    FILE_CSV = tempfile.NamedTemporaryFile(suffix=".csv", dir=TEMPDIR)
    atexit.register(FILE_CSV.close)

    class AutodocExampleParam1(gds.DataSet):
        """Example of a complete dataset with all possible items. Used as an autodoc
        example."""

        dir = gds.DirectoryItem("<strong>Directory</strong>", TEMPDIR)
        a = gds.FloatItem("Parameter #1", default=2.3)
        b = gds.IntItem("Parameter #2", min=0, max=10, default=5)
        c = gds.StringItem("Parameter #3", default="default value")
        type = gds.ChoiceItem("Processing algorithm", ("type 1", "type 2", "type 3"))
        fname = gds.FileOpenItem("Open file", ("csv", "eta"), FILE_CSV.name)
        fnames = gds.FilesOpenItem("Open files", "csv", FILE_CSV.name)
        fname_s = gds.FileSaveItem("Save file", "eta", FILE_ETA.name)
        string = gds.StringItem("String")
        text = gds.TextItem("Text")
        float_slider = gds.FloatItem(
            "Float (with slider)", default=0.5, min=0, max=1, step=0.01, slider=True
        )
        integer = gds.IntItem("Integer", default=5, min=3, max=16, slider=True).set_pos(
            col=1
        )
        dtime = gds.DateTimeItem("Date/time", default=datetime.datetime(2010, 10, 10))
        date = gds.DateItem("Date", default=datetime.date(2010, 10, 10)).set_pos(col=1)
        bool1 = gds.BoolItem("Boolean option without label")
        bool2 = gds.BoolItem("Boolean option with label", "Label")
        _bg = gds.BeginGroup("A sub group")
        color = gds.ColorItem("Color", default="red")
        choice = gds.ChoiceItem(
            "Single choice 1",
            [
                ("16", "first choice"),
                ("32", "second choice"),
                ("64", "third choice"),
                (128, "fourth choice"),
            ],
        )
        mchoice2 = gds.ImageChoiceItem(
            "Single choice 2",
            [
                ("rect", "first choice", "gif.png"),
                ("ell", "second choice", "txt.png"),
                ("qcq", "third choice", "file.png"),
            ],
        )
        _eg = gds.EndGroup("A sub group")
        floatarray = gds.FloatArrayItem("Float array", format=" %.2e ").set_pos(col=1)
        mchoice3 = gds.MultipleChoiceItem(
            "MC type 1", [str(i) for i in range(12)]
        ).horizontal(4)
        mchoice1 = (
            gds.MultipleChoiceItem(
                "MC type 2", ["first choice", "second choice", "third choice"]
            )
            .vertical(1)
            .set_pos(col=1)
        )
        dictionary = gds.DictItem(
            "Dictionary",
            help="This is a dictionary",
        )

        def doc_test(self, a: int, b: float, c: str) -> str:
            """Test method for autodoc.

            Args:
                a: first parameter.
                b: second parameter.
                c: third parameter.

            Returns:
                Concatenation of c and (a + b).
            """
            return c + str(a + b)

    class AutodocExampleParam2(AutodocExampleParam1):
        pass

## Generated documentation

### Basic usage

In most cases, the `.. autodataset::` directive should be sufficient to document a dataset. However, it might be useful to display examples on how to instanciate the given dataset. This can be done using the `:shownote:` option (or the `.. datasetnote::` directive).

    .. autodataset:: autodoc_example.AutodocExampleParam1

    .. autodataset:: autodoc_example.AutodocExampleParam1
        :shownote:

The second example line would result in the following documentation:

class autodoc_example.AutodocExampleParam1

  Example of a complete dataset with all possible items. Used as an autodoc example.

  dir

    Directory. Default: ‘/tmp/test_us_y0_fy’.

    Type:

      guidata.dataset.dataitems.DirectoryItem

  a

    Parameter #1. Default: 2.3.

    Type:

      guidata.dataset.dataitems.FloatItem

  b

    Parameter #2. Integer between 0 and 10. Default: 5.

    Type:

      guidata.dataset.dataitems.IntItem

  c

    Parameter #3. Default: ‘default value’.

    Type:

      guidata.dataset.dataitems.StringItem

  type

    Processing algorithm. Single choice from: 0, 1, 2. Default: 0.

    Type:

      guidata.dataset.dataitems.ChoiceItem

  fname

    Open file. Supported file types: *.csv, *.eta. Default: ‘/tmp/test_us_y0_fy/tmpwtbekhc5.csv’.

    Type:

      guidata.dataset.dataitems.FileOpenItem

  fnames

    Open files. Supported file types: *.csv. Default: [‘/tmp/test_us_y0_fy/tmpwtbekhc5.csv’].

    Type:

      guidata.dataset.dataitems.FilesOpenItem

  fname_s

    Save file. Supported file types: *.eta. Default: ‘/tmp/test_us_y0_fy/tmpjm2t5oaa.eta’.

    Type:

      guidata.dataset.dataitems.FileSaveItem

  string

    Default: None.

    Type:

      guidata.dataset.dataitems.StringItem

  text

    Default: None.

    Type:

      guidata.dataset.dataitems.TextItem

  float_slider

    Float (with slider). Float between 0 and 1. Default: 0.5.

    Type:

      guidata.dataset.dataitems.FloatItem

  integer

    Integer between 3 and 16. Default: 5.

    Type:

      guidata.dataset.dataitems.IntItem

  dtime

    Date/time. Default: datetime.datetime(2010, 10, 10, 0, 0).

    Type:

      guidata.dataset.dataitems.DateTimeItem

  date

    Default: datetime.date(2010, 10, 10).

    Type:

      guidata.dataset.dataitems.DateItem

  bool1

    Default: None.

    Type:

      guidata.dataset.dataitems.BoolItem

  bool2

    Label. Default: None.

    Type:

      guidata.dataset.dataitems.BoolItem

  color

    Default: ‘red’.

    Type:

      guidata.dataset.dataitems.ColorItem

  choice

    Single choice 1. Single choice from: ‘16’, ‘32’, ‘64’, 128. Default: ‘16’.

    Type:

      guidata.dataset.dataitems.ChoiceItem

  mchoice2

    Single choice 2. Single choice from: ‘rect’, ‘ell’, ‘qcq’. Default: ‘rect’.

    Type:

      guidata.dataset.dataitems.ImageChoiceItem

  floatarray

    Default: None.

    Type:

      guidata.dataset.dataitems.FloatArrayItem

  mchoice3

    MC type 1. Multiple choice from: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11. Default: ().

    Type:

      guidata.dataset.dataitems.MultipleChoiceItem

  mchoice1

    MC type 2. Multiple choice from: 0, 1, 2. Default: ().

    Type:

      guidata.dataset.dataitems.MultipleChoiceItem

  dictionary

    This is a dictionary. Default: None.

    Type:

      guidata.dataset.dataitems.DictItem

  classmethod create(dir: str, a: float, b: int, c: str, type: int, fname: str, fnames: list, fname_s: str, string: str, text: str, float_slider: float, integer: int, dtime: datetime.datetime, date: datetime.date, bool1: bool, bool2: bool, color: str, choice: int | str, mchoice2: str, floatarray: numpy.ndarray, mchoice3: int, mchoice1: int, dictionary: dict) → autodoc_example.AutodocExampleParam1

    Returns a new instance of `AutodocExampleParam1` with the fields set to the given values.

    Parameters:

      - dir (str) – Directory. Default: ‘/tmp/test_us_y0_fy’.

      - a (float) – Parameter #1. Default: 2.3.

      - b (int) – Parameter #2. Integer between 0 and 10. Default: 5.

      - c (str) – Parameter #3. Default: ‘default value’.

      - type (int) – Processing algorithm. Single choice from: 0, 1, 2. Default: 0.

      - fname (str) – Open file. Supported file types: *.csv, *.eta. Default: ‘/tmp/test_us_y0_fy/tmpwtbekhc5.csv’.

      - fnames (list) – Open files. Supported file types: *.csv. Default: [‘/tmp/test_us_y0_fy/tmpwtbekhc5.csv’].

      - fname_s (str) – Save file. Supported file types: *.eta. Default: ‘/tmp/test_us_y0_fy/tmpjm2t5oaa.eta’.

      - string (str) – Default: None.

      - text (str) – Default: None.

      - float_slider (float) – Float (with slider). Float between 0 and 1. Default: 0.5.

      - integer (int) – Integer between 3 and 16. Default: 5.

      - dtime (datetime.datetime) – Date/time. Default: datetime.datetime(2010, 10, 10, 0, 0).

      - date (datetime.date) – Default: datetime.date(2010, 10, 10).

      - bool1 (bool) – Default: None.

      - bool2 (bool) – Label. Default: None.

      - color (str) – Default: ‘red’.

      - choice (Union[int, str]) – Single choice 1. Single choice from: ‘16’, ‘32’, ‘64’, 128. Default: ‘16’.

      - mchoice2 (str) – Single choice 2. Single choice from: ‘rect’, ‘ell’, ‘qcq’. Default: ‘rect’.

      - floatarray (numpy.ndarray) – Default: None.

      - mchoice3 (int) – MC type 1. Multiple choice from: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11. Default: ().

      - mchoice1 (int) – MC type 2. Multiple choice from: 0, 1, 2. Default: ().

      - dictionary (dict) – This is a dictionary. Default: None.

    Returns:

      New instance of `AutodocExampleParam1`.

  Note

  To instanciate a new `AutodocExampleParam1` dataset, you can use the classmethod `AutodocExampleParam1.create()` like this:

      AutodocExampleParam1.create(dir='/tmp/test_us_y0_fy', a=2.3, b=5, c='default value', type=0, fname='/tmp/test_us_y0_fy/tmpwtbekhc5.csv', fnames=['/tmp/test_us_y0_fy/tmpwtbekhc5.csv'], fname_s='/tmp/test_us_y0_fy/tmpjm2t5oaa.eta', string=None, text=None, float_slider=0.5, integer=5, dtime=datetime.datetime(2010, 10, 10, 0, 0), date=datetime.date(2010, 10, 10), bool1=None, bool2=None, color='red', choice='16', mchoice2='rect', floatarray=None, mchoice3=(), mchoice1=(), dictionary=None)

  You can also first instanciate a default `AutodocExampleParam1` and then set the fields like this:

      param = AutodocExampleParam1()
      param.dir = '/tmp/test_us_y0_fy'
      param.a = 2.3
      param.b = 5
      param.c = 'default value'
      param.type = 0
      param.fname = '/tmp/test_us_y0_fy/tmpwtbekhc5.csv'
      param.fnames = ['/tmp/test_us_y0_fy/tmpwtbekhc5.csv']
      param.fname_s = '/tmp/test_us_y0_fy/tmpjm2t5oaa.eta'
      param.string = None
      param.text = None
      param.float_slider = 0.5
      param.integer = 5
      param.dtime = datetime.datetime(2010, 10, 10, 0, 0)
      param.date = datetime.date(2010, 10, 10)
      param.bool1 = None
      param.bool2 = None
      param.color = 'red'
      param.choice = '16'
      param.mchoice2 = 'rect'
      param.floatarray = None
      param.mchoice3 = ()
      param.mchoice1 = ()
      param.dictionary = None

### Advanced usage

The `.. autodataset::` directive behavior can be modified using all `.. autoclass::` options, as well as the the following ones:

> - `:showsig:` to show the constructor signature

> - `:hideattr:` to hide the dataset attributes

> - `:shownote: [n]` to add a note on how to instanciate the dataset with the first `n` items. If `n` is not provided, all items will be shown.

> - `:hidecreate:` to hide the `create()` method documentation which is shown by default.

The following reST example shows how these options can be used.

    .. autodataset:: autodoc_example.AutodocExampleParam2
        :showsig:
        :hideattr:
        :hidecreate:
        :shownote: 5
        :members:

class autodoc_example.AutodocExampleParam2(title: str | None = None, comment: str | None = None, icon: str = '', readonly: bool = False, skip_defaults: bool = False)

  Example of a complete dataset with all possible items. Used as an autodoc example.

  Note

  To instanciate a new `AutodocExampleParam2` dataset, you can use the classmethod `AutodocExampleParam2.create()` like this:

      AutodocExampleParam2.create(dir='/tmp/test_us_y0_fy', a=2.3, b=5, c='default value', type=0, fname='/tmp/test_us_y0_fy/tmpwtbekhc5.csv', fnames=['/tmp/test_us_y0_fy/tmpwtbekhc5.csv'], fname_s='/tmp/test_us_y0_fy/tmpjm2t5oaa.eta', string=None, text=None, float_slider=0.5, integer=5, dtime=datetime.datetime(2010, 10, 10, 0, 0), date=datetime.date(2010, 10, 10), bool1=None, bool2=None, color='red', choice='16', mchoice2='rect', floatarray=None, mchoice3=(), mchoice1=(), dictionary=None)

  You can also first instanciate a default `AutodocExampleParam2` and then set the fields like this:

      param = AutodocExampleParam2()
      param.dir = '/tmp/test_us_y0_fy'
      param.a = 2.3
      param.b = 5
      param.c = 'default value'
      param.type = 0
      ...