Giter VIP home page Giter VIP logo

sphinx-autodoc2's Introduction

sphinx-autodoc2

sphinx-autodoc2 is a Sphinx extension that automatically generates API documentation for your Python packages.

GitHub Repo stars PyPI

Static analysis of Python code

: There is no need to install your package to generate the documentation, and sphinx-autodoc2 will correctly handle if TYPE_CHECKING blocks and other typing only features. : You can even document packages from outside the project (via git clone)!

Optimized for rebuilds

: Analysis of packages and file rendering are cached, so you can use sphinx-autodoc2 in your development workflow.

Support for __all__

: sphinx-autodoc2 can follow __all__ variable, to only document the public API.

Support for both rst and md docstrings

: sphinx-autodoc2 supports both rst and md (MyST) docstrings, which can be mixed within the same project.

Highly configurable

: sphinx-autodoc2 is highly configurable, with many options to control the analysis and output of the documentation.

Decoupled analysis and rendering

: The analysis and rendering of the documentation are decoupled, and not dependent on Sphinx. : This means that you can use sphinx-autodoc2 to generate documentation outside of Sphinx (see the autodoc2 command line tool).

See the documentation for more information!

Design and comparison to sphinx-autoapi

I wanted an extension with the following goals:

  • Static analysis of Python code, so things like if TYPE_CHECKING were handled correctly
  • Support for MyST docstrings (see executablebooks/MyST-Parser#228)
    • Also support for transitioning from rst to md, i.e. mixing docstrings
  • Make it simple and minimise the amount of configuration and rebuilds necessary
  • Support for building public API via __all__ variable

I am not looking to support other languages tha Python (at least for now).

sphinx-autoapi was a good candidate, but it had a few issues:

I've use a lot of their code, for the astroid static analysis, but I've made a number of "improvements":

  • separating concerns: analysis and template writing
  • type annotations for code base
  • fixed a | b annotations inference
  • added analysis of functools.singledispatch and their registers
  • handling of __all__
  • docstrings (and summaries) are now parsed with the correct source/line, i.e. warnings point to the correct location in the source file
  • added :canonical: to py directives
  • Moved away from using jinja templates, to using python functions
    • IMO the templates were too complex and hard to read, plus they do not benefit from any form of type checking, linting, etc.
    • uses list-table, instead of auto-summary directive

Development

All configuration is mainly in pyproject.toml.

Use tox to run the tests.

pipx install tox
tox -av

Use pre-commit to run the linters and formatters.

pipx install pre-commit
pre-commit run --all-files
# pre-commit install

flit is used to build the package.

pipx install flit
flit build

sphinx-autodoc2's People

Contributors

chrisjsewell avatar dependabot[bot] avatar pre-commit-ci[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

sphinx-autodoc2's Issues

0.4.2: sphinx warnings `reference target not found`

First of all currently it is not possible to use straight sphinx-build command to build documentation out of source tree

+ /usr/bin/sphinx-build -n -T -b man docs build/sphinx/man
Running Sphinx v6.2.1

Traceback (most recent call last):
  File "/usr/lib/python3.8/site-packages/sphinx/config.py", line 354, in eval_config_file
    exec(code, namespace)  # NoQA: S102
  File "/home/tkloczko/rpmbuild/BUILD/sphinx-autodoc2-0.4.2/docs/conf.py", line 4, in <module>
    from autodoc2 import __version__
ModuleNotFoundError: No module named 'autodoc2'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/lib/python3.8/site-packages/sphinx/cmd/build.py", line 280, in build_main
    app = Sphinx(args.sourcedir, args.confdir, args.outputdir,
  File "/usr/lib/python3.8/site-packages/sphinx/application.py", line 207, in __init__
    self.config = Config.read(self.confdir, confoverrides or {}, self.tags)
  File "/usr/lib/python3.8/site-packages/sphinx/config.py", line 177, in read
    namespace = eval_config_file(filename, tags)
  File "/usr/lib/python3.8/site-packages/sphinx/config.py", line 367, in eval_config_file
    raise ConfigError(msg % traceback.format_exc()) from exc
sphinx.errors.ConfigError: There is a programmable error in your configuration file:

Traceback (most recent call last):
  File "/usr/lib/python3.8/site-packages/sphinx/config.py", line 354, in eval_config_file
    exec(code, namespace)  # NoQA: S102
  File "/home/tkloczko/rpmbuild/BUILD/sphinx-autodoc2-0.4.2/docs/conf.py", line 4, in <module>
    from autodoc2 import __version__
ModuleNotFoundError: No module named 'autodoc2'

This can be fixed by patch like below:

--- a/docs/conf.py
+++ b/docs/conf.py
@@ -1,3 +1,7 @@
+import sys
+import os
+sys.path.insert(0, os.path.abspath("../src"))
+
 """The configuration for this packages documentation."""
 from datetime import date

This patch fixes what is in the comment and that can of fix is suggested in sphinx example copy.py https://www.sphinx-doc.org/en/master/usage/configuration.html#example-of-configuration-file

Than .. on building my packages I'm using sphinx-build command with -n switch which shows warmings about missing references. These are not critical issues.

Here is the output with warnings: python-sphinx-autodoc2-sphinx-watnings.txt

You can peak on fixes that kind of issues in other projects
RDFLib/rdflib-sqlalchemy#95
RDFLib/rdflib#2036
click-contrib/sphinx-click@abc31069
frostming/unearth#14
jaraco/cssutils#21
latchset/jwcrypto#289
latchset/jwcrypto#289
pypa/distlib@98b9b89f
pywbem/pywbem#2895
sissaschool/elementpath@bf869d9e
sissaschool/xmlschema@42ea98f2
sqlalchemy/sqlalchemy@5e88e6e8

0.4.2 MystRenderer renders default values incorrectly

I am using sphinx2-autodoc2 to generate documentation for a Python class like this:

class Foo:
"""This is class foo"""

  bar = 42
  """The bar of foo"""

When running this through Sphinx-autodoc2 it creates Foo.md with the following relevant parts:

````{py:attribute} bar
:canonical: Foo.bar
:value: >
   1

```{autodoc2-docstring} Foo.bar
```
````

Notice the ">" and extra linebreak!

This renders rather ugly:
image

What is wanted is more akin to:

image

This is caused by the following from myst_.py:

if isinstance(value, str):
if len(value.splitlines()) == 1:
if len(value) > 100:
value = value[:100] + "..."
yield ":value: >" # use > to ensure its understood as a string
yield f" {value!r}"
else:
yield ":value: <Multiline-String>"
# TODO in sphinx-autoapi, they made a code block inside a details/summary HTML
else:
value = str(value).replace("\n", " ")
if len(value) > 100:
value = value[:100] + "..."
yield ":value: >"
yield f" {value}"

I'm not sure what the intent of the comment: # use > to ensure its understood as a string is supposed to mean.

The rst-renderer is not up to such shenigans:

if isinstance(value, str):
if len(value.splitlines()) == 1:
if len(value) > 100:
value = value[:100] + "..."
yield f" :value: {value!r}"
else:
yield " :value: <Multiline-String>"
# TODO in sphinx-autoapi, they made a code block inside a details/summary HTML
else:
value = str(value).replace("\n", " ")
if len(value) > 100:
value = value[:100] + "..."
yield f" :value: {value}"

I can make a PR with a proposed fix, are you still accepting those?

Can error due to `TypeAlias` visitor via `astroid`

Lack of Astroid 3 support would help me because I am running into a separate issue:

  • sphinx-autodoc2: 0.4.2
  • astroid: 2.15.8

Related code: Unknown (cannot tell)

[Autodoc2] Analysing package...[ 16%] my_package.my_module
Extension error (autodoc2.sphinx.extension):
Handler <function run_autodoc at 0x7f1388fe0900> for event 'builder-inited' threw an exception (exception: 'TreeRebuilder' object has no attribute 'visit_typealias')
Command exited with exit code: 2
The server will continue serving the build folder, but the contents being served are no longer in sync with the documentation sources. Please fix the cause of the error above or press Ctrl+C to stop the server.

TreeRebuilder.visit_typealias() exists in 3.0.0, but not in 2.5.18.

ValueError: Item src does not exist

I'm getting the following when trying to build our docs with sphinx-autodoc2:

[Autodoc2] Determining files to write ...
[Autodoc2] Writing modules...[  0%] src                                                                                                                      
Traceback (most recent call last):
  File "/home/valberg/code/project/venv/lib/python3.11/site-packages/sphinx/events.py", line 94, in emit
    results.append(listener.handler(self.app, *args))
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/valberg/code/project/venv/lib/python3.11/site-packages/autodoc2/sphinx/extension.py", line 76, in run_autodoc
    mod_path = run_autodoc_package(app, config, i)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/valberg/code/project/venv/lib/python3.11/site-packages/autodoc2/sphinx/extension.py", line 213, in run_autodoc_package
    content = "\n".join(
              ^^^^^^^^^^
  File "/home/valberg/code/project/venv/lib/python3.11/site-packages/autodoc2/render/rst_.py", line 25, in render_item
    raise ValueError(f"Item {full_name} does not exist")
ValueError: Item src does not exist

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/valberg/code/project/venv/lib/python3.11/site-packages/sphinx/cmd/build.py", line 276, in build_main
    app = Sphinx(args.sourcedir, args.confdir, args.outputdir,
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/valberg/code/project/venv/lib/python3.11/site-packages/sphinx/application.py", line 262, in __init__
    self._init_builder()
  File "/home/valberg/code/project/venv/lib/python3.11/site-packages/sphinx/application.py", line 335, in _init_builder
    self.events.emit('builder-inited')
  File "/home/valberg/code/project/venv/lib/python3.11/site-packages/sphinx/events.py", line 105, in emit
    raise ExtensionError(__("Handler %r for event %r threw an exception") %
sphinx.errors.ExtensionError: Handler <function run_autodoc at 0x7f32ba1a1d00> for event 'builder-inited' threw an exception (exception: Item src does not exist)

Extension error (autodoc2.sphinx.extension):
Handler <function run_autodoc at 0x7f32ba1a1d00> for event 'builder-inited' threw an exception (exception: Item src does not exist)

Our docs/conf.py looks like this:

import os
import sys

project = "Project"
copyright = ""
author = ""

extensions = [
    "myst_parser",
    "sphinx.ext.viewcode",
    "sphinxcontrib.mermaid",
    "autodoc2",
]
autodoc2_packages = [
    "../src/",
]

templates_path = ["_templates"]

language = "en"

exclude_patterns = []

html_theme = "furo"
html_static_path = []

myst_enable_extensions = [
    "dollarmath",
    "amsmath",
    "deflist",
    "fieldlist",
    "html_admonition",
    "html_image",
    "colon_fence",
    "smartquotes",
    "replacements",
    "strikethrough",
    "substitution",
    "tasklist",
    "attrs_image",
]

It looks like it goes through all the modules alright, but when it comes to writing them it fails.

Am I doing anything wrong or is this a real bug?

Within a module, we can shorten a.b.c.d... for readability

Tested it works, we just need to test the target is in the current module.

    def render_method(self, item: ItemData) -> t.Iterable[str]:
        """Create the content for a method."""
        short_name = item["full_name"].split(".")[-1]
        show_annotations = self.show_annotations(item)
        sig = f"{short_name}({self.format_args(item['args'], show_annotations, ignore_self='self')})"
        if show_annotations and item.get("return_annotation"):

            _ = f" -> {self.format_annotation(item['return_annotation'])}"
            _ = _.replace('PySpice.Unit.Unit.', '')
            sig += _

autodoc2-object and -summary outputs full path

When using autodoc2-object and -summary, instead of outputting Baz for instance it outputs the full path, meaning Foo.Bar.Baz. This duplicates the path when trying to press to an object (hello.rst#Foo.Bar.Foo.Bar.Baz), is needlessly long, and conflicts with the behaviour of the auto-generation.

Links are outdated

chrisjsewell/sphinx-autodoc2 -> sphinx-extensions2/sphinx-autodoc2. Caught this because of linkcheck

0.5.0: pytest is failing in `tests/test_render.py::test_sphinx_build_directives` unit

I'm packaging your module as an rpm package so I'm using the typical PEP517 based build, install and test cycle used on building packages from non-root account.

  • python3 -sBm build -w --no-isolation
  • because I'm calling build with --no-isolation I'm using during all processes only locally installed modules
  • install .whl file in </install/prefix> using 'installer` module
  • run pytest with $PYTHONPATH pointing to sitearch and sitelib inside </install/prefix>
  • build is performed in env which is cut off from access to the public network (pytest is executed with -m "not network")
Here is pytest output:
+ PYTHONPATH=/home/tkloczko/rpmbuild/BUILDROOT/python-sphinx-autodoc2-0.5.0-2.fc35.x86_64/usr/lib64/python3.8/site-packages:/home/tkloczko/rpmbuild/BUILDROOT/python-sphinx-autodoc2-0.5.0-2.fc35.x86_64/usr/lib/python3.8/site-packages
+ /usr/bin/pytest -ra -m 'not network'
============================= test session starts ==============================
platform linux -- Python 3.8.18, pytest-7.4.3, pluggy-1.3.0
rootdir: /home/tkloczko/rpmbuild/BUILD/sphinx-autodoc2-0.5.0
configfile: pyproject.toml
testpaths: tests
plugins: datadir-1.5.0, regressions-2.5.0
collected 45 items

tests/test_analyse_module.py .....................................       [ 82%]
tests/test_database.py .                                                 [ 84%]
tests/test_render.py ......F                                             [100%]

=================================== FAILURES ===================================
_________________________ test_sphinx_build_directives _________________________

tmp_path = PosixPath('/tmp/pytest-of-tkloczko/pytest-10/test_sphinx_build_directives0')
file_regression = <pytest_regressions.file_regression.FileRegressionFixture object at 0x7fab683055e0>

    def test_sphinx_build_directives(tmp_path: Path, file_regression):
        """Test building the Sphinx docs, using directives."""
        build_package(tmp_path)
        source = tmp_path / "source"
        source.mkdir()
        source.joinpath("conf.py").write_text(
            dedent(
                """\
            project = "tester"
            extensions = ["autodoc2"]
            autodoc2_packages = [
                {
                    "path": "../package",
                    "auto_mode": False,
                }
            ]
            """
            ),
            "utf-8",
        )
        source.joinpath("index.rst").write_text(
            dedent(
                """\
            Test
            ====

            .. autodoc2-docstring:: package.func
               :literal:
               :literal-linenos:
               :literal-lexer: restructuredtext

            .. autodoc2-docstring:: package.func

            .. autodoc2-object:: package.func
               :literal:
               :literal-lexer: restructuredtext

            .. autodoc2-object:: package.func
               :literal:

               render_plugin = "myst"

            .. autodoc2-object:: package.func

            .. autodoc2-summary::

                package.func
                package.a1
            """
            ),
            "utf-8",
        )
        warnings = io.StringIO()
        build = tmp_path / "build"
        app = SphinxTestApp(
            buildername="html",
            srcdir=sphinx_path(source),
            builddir=sphinx_path(build),
            warning=warnings,
        )
        try:
            app.build()
        finally:
            app.cleanup()

        assert not warnings.getvalue()

        doctree = app.env.get_doctree("index")
        doctree["source"] = "index.rst"
        content = "\n".join([line.rstrip() for line in doctree.pformat().splitlines()])
>       file_regression.check(content, extension=".xml")
E       AssertionError: FILES DIFFER:
E       /tmp/pytest-of-tkloczko/pytest-10/test_sphinx_build_directives0/test_render/test_sphinx_build_directives.xml
E       /tmp/pytest-of-tkloczko/pytest-10/test_sphinx_build_directives0/test_render/test_sphinx_build_directives.obtained.xml
E       HTML DIFF: /tmp/pytest-of-tkloczko/pytest-10/test_sphinx_build_directives0/test_render/test_sphinx_build_directives.obtained.diff.html
E       ---
E       +++
E       @@ -1,4 +1,4 @@
E       -<document source="index.rst">
E       +<document source="index.rst" translation_progress="{'total': 0, 'translated': 0}">
E            <section ids="test" names="test">
E                <title>
E                    Test
E       @@ -25,7 +25,7 @@
E                            package.
E                        <desc_name classes="sig-name descname" xml:space="preserve">
E                            func
E       -                <desc_parameterlist xml:space="preserve">
E       +                <desc_parameterlist multi_line_parameter_list="False" xml:space="preserve">
E                            <desc_parameter xml:space="preserve">
E                                <desc_sig_name classes="n">
E                                    a

tests/test_render.py:226: AssertionError
=========================== short test summary info ============================
FAILED tests/test_render.py::test_sphinx_build_directives - AssertionError: F...
========================= 1 failed, 44 passed in 2.27s =========================
List of installed modules in build env:
Package                       Version
----------------------------- -------
alabaster                     0.7.13
astroid                       3.0.1
Babel                         2.13.1
build                         1.0.3
charset-normalizer            3.3.2
cppclean                      0.13
distro                        1.8.0
dnf                           4.18.1
docutils                      0.20.1
exceptiongroup                1.1.3
gpg                           1.23.0
idna                          3.4
imagesize                     1.4.1
importlib-metadata            6.8.0
iniconfig                     2.0.0
installer                     0.7.0
Jinja2                        3.1.2
libdnf                        0.72.0
markdown-it-py                3.0.0
MarkupSafe                    2.1.3
mdit-py-plugins               0.4.0
mdurl                         0.1.2
myst-parser                   2.0.0
packaging                     23.2
pluggy                        1.3.0
Pygments                      2.17.2
pyproject_hooks               1.0.0
pytest                        7.4.3
pytest-datadir                1.5.0
pytest-regressions            2.5.0
python-dateutil               2.8.2
pytz                          2023.3
PyYAML                        6.0.1
requests                      2.31.0
six                           1.16.0
snowballstemmer               2.2.0
Sphinx                        7.1.2
sphinxcontrib-applehelp       1.0.4
sphinxcontrib-devhelp         1.0.5
sphinxcontrib-htmlhelp        2.0.4
sphinxcontrib-jsmath          1.0.1
sphinxcontrib-qthelp          1.0.3
sphinxcontrib-serializinghtml 1.1.9
tomli                         2.0.1
typing_extensions             4.8.0
urllib3                       1.26.18
wheel                         0.42.0
zipp                          3.17.0

Question: remove module name from path

Hello,

First, thanks for your work!

Do you know if it's possible to remove the full name from a class or function reference?

As shown below, it's even more bizarre that the name is shortened in the PARAMETERS sections, but not in the function signature.

I'd like to have Point everywhere, instead of differt2d.geometry.Point. The same applies for others.

I have set the add_module_names variable to False in conf.py, but it doesn't work (I guess it's because we are not using autodoc here).

image

Class variable intialized with object: value rendered as None

Great work! I'm converting a project from autodoc, and loving the improvements...
Came across this, its a bit of a show-stopper:

Code like this:

class Foo:
    """I'm a Foo"""
    pass

class Bar:
    """I'm composed of Foo"""

    s = "just fine"

    my_foo = Foo()
    """ What the foo?"""

    i = 42  # no problem

renders to:

.. py:class:: Bar
   :canonical: scratch.Bar

   .. autodoc2-docstring:: scratch.Bar

   .. py:attribute:: s
      :canonical: scratch.Bar.s
      :value: 'just fine'

      .. autodoc2-docstring:: scratch.Bar.s

   .. py:attribute:: my_foo
      :canonical: scratch.Bar.my_foo
      :value: None

      .. autodoc2-docstring:: scratch.Bar.my_foo

   .. py:attribute:: i
      :canonical: scratch.Bar.i
      :value: 42

Was expecting value of my_foo to be Foo().

I think this is a known issue in astroid_utils

def get_const_values(node: nodes.NodeNG) -> t.Any:
    """Get the value of a constant node."""
    # TODO its not ideal that this goes to None if not understood

Any work around for this?
thanks.

Docstrings don't seem to create linked headings

I am entirely new to Sphinx so this could just be a PEBKAC, but I've not managed to find a solution after quite a bit of searching.

When documenting a module's docstring with Sphinx-Autodoc2, it doesn't generate headings that have a little # link (that would usually link to page.html#heading-name so you can link to a section of the documentation) and they don't appear in the 'Contents' sidebar in 2 of the themes I tried that had such a sidebar.

I'm using this Sphinx configuration:

# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration

extensions = [
    'autodoc2',
    'myst_parser',
]

templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']


# -- Options for Autodoc2 ----------------------------------------------------

autodoc2_docstring_parser_regexes = [
    # this will render all docstrings as 'MyST' Markdown
    (r".*", "myst"),
]

autodoc2_packages = [
    {
        "path": "../mypackage",
        # Don't render documentation for everything as a matter of course
        "auto_mode": False,
    },
]


# -- Options for MyST (Markdown) ---------------------------------------------

# tried with and without
#myst_heading_anchors = 2


# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output

html_theme = 'furo'
html_static_path = ['_static']

Notably I am using MyST.

Here is a markdown file in which I am invoking autodoc2:

Page Title
==========

```{autodoc2-docstring} mypackage.mymodule
```

## A


## B

### C


## D

### E

(The content of mypackage.mymodule starts with a docstring containing headers of various depths)

image

(but note the headings within the docstring don't have the permalink, which appears on hover:)

image

Inner exceptions are missing

I have an exception defined as a nested inner class. It ends up being missing from the resulting documentation. Other exceptions and other nested inner classes do appear, though.

class OuterEx(Exception):
    """This exception is in the module.

    This is rendered.
    """
    pass

class ContainingCls:
    """This is the containing class.

    This is rendered.
    """

    class InnerCls:
        """This is an inner regular class.

        This is rendered."""
        pass

    class InnerEx(Exception):
        """This is an inner exception.

        This is missing!
        """
        pass

Resulting RST:

:py:mod:`test_pkg`
==================

.. py:module:: test_pkg

.. autodoc2-docstring:: test_pkg
   :allowtitles:

Package Contents
----------------

Classes
~~~~~~~

.. list-table::
   :class: autosummary longtable
   :align: left

   * - :py:obj:`ContainingCls <test_pkg.ContainingCls>`
     - .. autodoc2-docstring:: test_pkg.ContainingCls
          :summary:

API
~~~

.. py:exception:: OuterEx()
   :canonical: test_pkg.OuterEx

   Bases: :py:obj:`Exception`

   .. autodoc2-docstring:: test_pkg.OuterEx

   .. rubric:: Initialization

   .. autodoc2-docstring:: test_pkg.OuterEx.__init__

.. py:class:: ContainingCls
   :canonical: test_pkg.ContainingCls

   .. autodoc2-docstring:: test_pkg.ContainingCls

   .. py:class:: InnerCls
      :canonical: test_pkg.ContainingCls.InnerCls

      .. autodoc2-docstring:: test_pkg.ContainingCls.InnerCls

0.4.2: pytest warnings

I'm packaging your module as an rpm package so I'm using the typical PEP517 based build, install and test cycle used on building packages from non-root account.

  • python3 -sBm build -w --no-isolation
  • because I'm calling build with --no-isolation I'm using during all processes only locally installed modules
  • install .whl file in </install/prefix> using 'installer` module
  • run pytest with $PYTHONPATH pointing to sitearch and sitelib inside </install/prefix>
  • build is performed in env which is cut off from access to the public network (pytest is executed with -m "not network")

Here is pytest output:

+ PYTHONPATH=/home/tkloczko/rpmbuild/BUILDROOT/python-sphinx-autodoc2-0.4.2-2.fc35.x86_64/usr/lib64/python3.8/site-packages:/home/tkloczko/rpmbuild/BUILDROOT/python-sphinx-autodoc2-0.4.2-2.fc35.x86_64/usr/lib/python3.8/site-packages
+ /usr/bin/pytest -ra -m 'not network'
==================================================================================== test session starts ====================================================================================
platform linux -- Python 3.8.17, pytest-7.3.1, pluggy-1.0.0
rootdir: /home/tkloczko/rpmbuild/BUILD/sphinx-autodoc2-0.4.2
configfile: pyproject.toml
testpaths: tests
plugins: datadir-1.4.1, regressions-2.4.2
collected 44 items

tests/test_analyse_module.py ....................................                                                                                                                     [ 81%]
tests/test_database.py .                                                                                                                                                              [ 84%]
tests/test_render.py .......                                                                                                                                                          [100%]

===================================================================================== warnings summary ======================================================================================
tests/test_analyse_module.py: 38 warnings
tests/test_database.py: 5 warnings
tests/test_render.py: 21 warnings
  /home/tkloczko/rpmbuild/BUILDROOT/python-sphinx-autodoc2-0.4.2-2.fc35.x86_64/usr/lib/python3.8/site-packages/autodoc2/analysis.py:116: DeprecationWarning: The 'Module.doc' attribute is deprecated, use 'Module.doc_node' instead.
    "doc": fix_docstring_indent(node.doc),

tests/test_analyse_module.py: 18 warnings
tests/test_render.py: 21 warnings
  /home/tkloczko/rpmbuild/BUILDROOT/python-sphinx-autodoc2-0.4.2-2.fc35.x86_64/usr/lib/python3.8/site-packages/autodoc2/astroid_utils.py:449: DeprecationWarning: The 'FunctionDef.doc' attribute is deprecated, use 'FunctionDef.doc_node' instead.
    doc = node.doc

tests/test_analyse_module.py: 16 warnings
tests/test_render.py: 14 warnings
  /home/tkloczko/rpmbuild/BUILDROOT/python-sphinx-autodoc2-0.4.2-2.fc35.x86_64/usr/lib/python3.8/site-packages/autodoc2/astroid_utils.py:391: DeprecationWarning: The 'ClassDef.doc' attribute is deprecated, use 'ClassDef.doc_node' instead.
    doc = node.doc

tests/test_analyse_module.py::test_basic[class_inherited]
tests/test_analyse_module.py::test_basic[class_inherited_with_docstring]
  /home/tkloczko/rpmbuild/BUILDROOT/python-sphinx-autodoc2-0.4.2-2.fc35.x86_64/usr/lib/python3.8/site-packages/autodoc2/astroid_utils.py:401: DeprecationWarning: The 'ClassDef.doc' attribute is deprecated, use 'ClassDef.doc_node' instead.
    if base.doc is not None:

tests/test_analyse_module.py::test_basic[class_inherited_with_docstring]
  /home/tkloczko/rpmbuild/BUILDROOT/python-sphinx-autodoc2-0.4.2-2.fc35.x86_64/usr/lib/python3.8/site-packages/autodoc2/astroid_utils.py:402: DeprecationWarning: The 'ClassDef.doc' attribute is deprecated, use 'ClassDef.doc_node' instead.
    return str(base.doc), base.qname()

tests/test_render.py::test_sphinx_build[with_rebuild]
tests/test_render.py::test_sphinx_build[with_rebuild]
  /usr/lib/python3.8/site-packages/sphinxcontrib/htmlhelp/__init__.py:26: RemovedInSphinx80Warning: The alias 'sphinx.util.progress_message' is deprecated, use 'sphinx.http_date.epoch_to_rfc1123' instead. Check CHANGES for Sphinx API modifications.
    from sphinx.util import progress_message

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
============================================================================= 44 passed, 138 warnings in 2.70s ==============================================================================

Here is list of installed modules in build env

Package                       Version
----------------------------- -------
alabaster                     0.7.13
astroid                       2.15.4
asttokens                     2.2.1
Babel                         2.12.1
backcall                      0.2.0
build                         0.10.0
charset-normalizer            3.1.0
decorator                     5.1.1
distro                        1.8.0
docutils                      0.19
exceptiongroup                1.1.1
executing                     1.2.0
gpg                           1.20.0
idna                          3.4
imagesize                     1.4.1
importlib-metadata            6.6.0
iniconfig                     2.0.0
installer                     0.7.0
ipython                       8.12.0
jedi                          0.18.2
Jinja2                        3.1.2
lazy-object-proxy             1.9.0
libcomps                      0.1.19
markdown-it-py                3.0.0
MarkupSafe                    2.1.2
matplotlib-inline             0.1.6
mdit-py-plugins               0.4.0
mdurl                         0.1.2
myst-parser                   1.0.0
packaging                     23.1
parso                         0.8.3
pexpect                       4.8.0
pickleshare                   0.7.5
pluggy                        1.0.0
prompt-toolkit                3.0.38
ptyprocess                    0.7.0
pure-eval                     0.2.2
Pygments                      2.15.1
pyproject_hooks               1.0.0
pytest                        7.3.1
pytest-datadir                1.4.1
pytest-regressions            2.4.2
python-dateutil               2.8.2
pytz                          2023.2
PyYAML                        6.0
requests                      2.31.0
setuptools                    67.7.2
six                           1.16.0
snowballstemmer               2.2.0
Sphinx                        6.2.1
sphinxcontrib-applehelp       1.0.4
sphinxcontrib-devhelp         1.0.2
sphinxcontrib-htmlhelp        2.0.0
sphinxcontrib-jsmath          1.0.1
sphinxcontrib-qthelp          1.0.3
sphinxcontrib-serializinghtml 1.1.5
stack-data                    0.6.2
tomli                         2.0.1
traitlets                     5.9.0
typing_extensions             4.5.0
urllib3                       1.26.15
wcwidth                       0.2.6
wheel                         0.40.0
wrapt                         1.14.1
zipp                          3.15.0

astroid 3 breaks builds: AttributeError: 'Module' object has no attribute 'doc'

I am not sure if this an astroid or autodoc2 issue, but the astroid 3 release broke builds.

Example error:


Running Sphinx v7.2.6
making output directory... done
�[2K[Autodoc2] Analysing package...[  5%] itkwasm.pixel_types
Traceback (most recent call last):
  File "/home/docs/checkouts/readthedocs.org/user_builds/itkwasm/envs/latest/lib/python3.10/site-packages/sphinx/events.py", line 97, in emit
    results.append(listener.handler(self.app, *args))
  File "/home/docs/checkouts/readthedocs.org/user_builds/itkwasm/envs/latest/lib/python3.10/site-packages/autodoc2/sphinx/extension.py", line 76, in run_autodoc
    mod_path = run_autodoc_package(app, config, i)
  File "/home/docs/checkouts/readthedocs.org/user_builds/itkwasm/envs/latest/lib/python3.10/site-packages/autodoc2/sphinx/extension.py", line 164, in run_autodoc_package
    for data in analyse_module(mod_path, mod_name):
  File "/home/docs/checkouts/readthedocs.org/user_builds/itkwasm/envs/latest/lib/python3.10/site-packages/autodoc2/analysis.py", line 41, in analyse_module
    yield from walk_node(
  File "/home/docs/checkouts/readthedocs.org/user_builds/itkwasm/envs/latest/lib/python3.10/site-packages/autodoc2/analysis.py", line 105, in walk_node
    yield from func(node, state)
  File "/home/docs/checkouts/readthedocs.org/user_builds/itkwasm/envs/latest/lib/python3.10/site-packages/autodoc2/analysis.py", line 116, in yield_module
    "doc": fix_docstring_indent(node.doc),
AttributeError: 'Module' object has no attribute 'doc'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/docs/checkouts/readthedocs.org/user_builds/itkwasm/envs/latest/lib/python3.10/site-packages/sphinx/cmd/build.py", line 293, in build_main
    app = Sphinx(args.sourcedir, args.confdir, args.outputdir,
  File "/home/docs/checkouts/readthedocs.org/user_builds/itkwasm/envs/latest/lib/python3.10/site-packages/sphinx/application.py", line 272, in __init__
    self._init_builder()
  File "/home/docs/checkouts/readthedocs.org/user_builds/itkwasm/envs/latest/lib/python3.10/site-packages/sphinx/application.py", line 343, in _init_builder
    self.events.emit('builder-inited')
  File "/home/docs/checkouts/readthedocs.org/user_builds/itkwasm/envs/latest/lib/python3.10/site-packages/sphinx/events.py", line 108, in emit
    raise ExtensionError(__("Handler %r for event %r threw an exception") %
sphinx.errors.ExtensionError: Handler <function run_autodoc at 0x7f69dd1211b0> for event 'builder-inited' threw an exception (exception: 'Module' object has no attribute 'doc')

Add support for overloaded functions

Currently I can't seem to get sphinx-autodoc2 to generate the signature for overloaded functions.

Example

from typing import overload

@overload()
def myfunc(a: int):
  """foobar with int"""
...

@overload()
def myfunc(a: str):
  """foobar with str"""
...

def myfunc(a):
  """foobar"""
  # Implementation

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.