Type hints support for the Sphinx autodoc extension

Overview

sphinx-autodoc-typehints

This extension allows you to use Python 3 annotations for documenting acceptable argument types and return value types of functions. This allows you to use type hints in a very natural fashion, allowing you to migrate from this:

def format_unit(value, unit):
    """
    Formats the given value as a human readable string using the given units.

    :param float|int value: a numeric value
    :param str unit: the unit for the value (kg, m, etc.)
    :rtype: str
    """
    return '{} {}'.format(value, unit)

to this:

from typing import Union

def format_unit(value: Union[float, int], unit: str) -> str:
    """
    Formats the given value as a human readable string using the given units.

    :param value: a numeric value
    :param unit: the unit for the value (kg, m, etc.)
    """
    return '{} {}'.format(value, unit)

Installation and setup

First, use pip to download and install the extension:

$ pip install sphinx-autodoc-typehints

Then, add the extension to your conf.py:

extensions = [
    'sphinx.ext.autodoc',
    'sphinx_autodoc_typehints'
]

Options

The following configuration options are accepted:

  • set_type_checking_flag (default: False): if True, set typing.TYPE_CHECKING to True to enable "expensive" typing imports
  • typehints_fully_qualified (default: False): if True, class names are always fully qualified (e.g. module.for.Class). If False, just the class name displays (e.g. Class)
  • always_document_param_types (default: False): If False, do not add type info for undocumented parameters. If True, add stub documentation for undocumented parameters to be able to add type info.
  • typehints_document_rtype (default: True): If False, never add an :rtype: directive. If True, add the :rtype: directive if no existing :rtype: is found.

How it works

The extension listens to the autodoc-process-signature and autodoc-process-docstring Sphinx events. In the former, it strips the annotations from the function signature. In the latter, it injects the appropriate :type argname: and :rtype: directives into the docstring.

Only arguments that have an existing :param: directive in the docstring get their respective :type: directives added. The :rtype: directive is added if and only if no existing :rtype: is found.

Compatibility with sphinx.ext.napoleon

To use sphinx.ext.napoleon with sphinx-autodoc-typehints, make sure you load sphinx.ext.napoleon first, before sphinx-autodoc-typehints. See Issue 15 on the issue tracker for more information.

Dealing with circular imports

Sometimes functions or classes from two different modules need to reference each other in their type annotations. This creates a circular import problem. The solution to this is the following:

  1. Import only the module, not the classes/functions from it
  2. Use forward references in the type annotations (e.g. def methodname(self, param1: 'othermodule.OtherClass'):)

On Python 3.7, you can even use from __future__ import annotations and remove the quotes.

Using type hint comments

If you're documenting code that needs to stay compatible with Python 2.7, you cannot use regular type annotations. Instead, you must either be using Python 3.8 or later or have typed_ast installed. The package extras type_comments will pull in the appropiate dependencies automatically. Then you can add type hint comments in the following manner:

def myfunction(arg1, arg2):
    # type: (int, str) -> int
    return 42

or alternatively:

def myfunction(
    arg1,  # type: int
    arg2  # type: str
):
    # type: (...) -> int
    return 42
Comments
  • Reexported classes aren’t linked

    Reexported classes aren’t linked

    For example:

    def foo(m: scipy.sparse.spmatrix):
       pass
    

    Will not get a linked parameter type, since the qualname is scipy.sparse.base.spmatrix, and :class:`~scipy.sparse.spmatrix` will therefore point nowhere in the docs index.

    opened by flying-sheep 35
  • Cannot resolve forward reference

    Cannot resolve forward reference

    Code:

    if TYPE_CHECKING:
        from qc.model.user import User
    
    ...
    
        @property
        @abstractmethod
        def owner(self) -> "User":
            ...
    

    Error with set_type_checking_flag = False:

    WARNING: Cannot resolve forward reference in type annotations of "qc.db.Owned.owner": name 'User' is not defined                                                                                             
    
    Exception occurred:
      File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/inspect.py", line 786, in findsource                                                                                                 
        raise OSError('could not get source code')
    OSError: could not get source code
    

    Error with set_type_checking_flag = True:

    WARNING: autodoc: failed to import module 'app' from module 'qc'; the following exception was raised:
    cannot import name 'User' from 'qc.model.user' (/Users/cyber/dev/jb/qc/qc-backend/qc/model/user.py)
    WARNING: autodoc: failed to import module 'commands' from module 'qc'; the following exception was raised:
    cannot import name 'TSTZ' from 'qc.db' (/Users/cyber/dev/jb/qc/qc-backend/qc/db/__init__.py)
    ... [many more]
    cannot import name 'User' from 'qc.model.user' (/Users/cyber/dev/jb/qc/qc-backend/qc/model/user.py)
    cannot import name 'User' from 'qc.model.user' (/Users/cyber/dev/jb/qc/qc-backend/qc/model/user.py)
    cannot import name 'User' from 'qc.model.user' (/Users/cyber/dev/jb/qc/qc-backend/qc/model/user.py)
    WARNING: autodoc: failed to import module 'test' from module 'qc'; the following exception was raised:
    cannot import name 'User' from 'qc.model.user' (/Users/cyber/dev/jb/qc/qc-backend/qc/model/user.py)
    

    Using sphinx-apidoc and python 3.7.

    duplicate 
    opened by revmischa 28
  • Update special dataclass handling

    Update special dataclass handling

    The existing unit tests appear to catch this regression when running with a python version that exhibits this change, so I didn't add an additional protection.

    Please let me know I'm missing anything in this patch. Thanks for a great tool!

    opened by lbenezriravin 24
  • Allow py310 style annotations (PEP563) when using from __future__ import annotations

    Allow py310 style annotations (PEP563) when using from __future__ import annotations

    This allows one to annotate in Python 3.10 style (PEP563) when from __future__ import annotations is used.

    e.g.:

    from __future__ import annotations
    
    def f(x: int | None) -> int: pass
    

    will work

    opened by basnijholt 23
  • Apparent incompatibility with slot wrappers

    Apparent incompatibility with slot wrappers

    Here's a traceback for you. I've found this error appears on any class that doesn't explicitly define an __init__() - which means that the __init__ in its dict refers to a C method wrapper.

    Python 3.6.

    Traceback (most recent call last):
      File "C:\Python36\lib\site-packages\sphinx\cmdline.py", line 296, in main
        app.build(opts.force_all, filenames)
      File "C:\Python36\lib\site-packages\sphinx\application.py", line 333, in build
        self.builder.build_update()
      File "C:\Python36\lib\site-packages\sphinx\builders\__init__.py", line 251, in build_update
        'out of date' % len(to_build))
      File "C:\Python36\lib\site-packages\sphinx\builders\__init__.py", line 265, in build
        self.doctreedir, self.app))
      File "C:\Python36\lib\site-packages\sphinx\environment\__init__.py", line 556, in update
        self._read_serial(docnames, app)
      File "C:\Python36\lib\site-packages\sphinx\environment\__init__.py", line 576, in _read_serial
        self.read_doc(docname, app)
      File "C:\Python36\lib\site-packages\sphinx\environment\__init__.py", line 684, in read_doc
        pub.publish()
      File "C:\Python36\lib\site-packages\docutils\core.py", line 217, in publish
        self.settings)
      File "C:\Python36\lib\site-packages\sphinx\io.py", line 55, in read
        self.parse()
      File "C:\Python36\lib\site-packages\docutils\readers\__init__.py", line 78, in parse
        self.parser.parse(self.input, document)
      File "C:\Python36\lib\site-packages\docutils\parsers\rst\__init__.py", line 185, in parse
        self.statemachine.run(inputlines, document, inliner=self.inliner)
      File "C:\Python36\lib\site-packages\docutils\parsers\rst\states.py", line 170, in run
        input_source=document['source'])
      File "C:\Python36\lib\site-packages\docutils\statemachine.py", line 239, in run
        context, state, transitions)
      File "C:\Python36\lib\site-packages\docutils\statemachine.py", line 460, in check_line
        return method(match, context, next_state)
      File "C:\Python36\lib\site-packages\docutils\parsers\rst\states.py", line 2745, in underline
        self.section(title, source, style, lineno - 1, messages)
      File "C:\Python36\lib\site-packages\docutils\parsers\rst\states.py", line 326, in section
        self.new_subsection(title, lineno, messages)
      File "C:\Python36\lib\site-packages\docutils\parsers\rst\states.py", line 394, in new_subsection
        node=section_node, match_titles=True)
      File "C:\Python36\lib\site-packages\docutils\parsers\rst\states.py", line 281, in nested_parse
        node=node, match_titles=match_titles)
      File "C:\Python36\lib\site-packages\docutils\parsers\rst\states.py", line 195, in run
        results = StateMachineWS.run(self, input_lines, input_offset)
      File "C:\Python36\lib\site-packages\docutils\statemachine.py", line 239, in run
        context, state, transitions)
      File "C:\Python36\lib\site-packages\docutils\statemachine.py", line 460, in check_line
        return method(match, context, next_state)
      File "C:\Python36\lib\site-packages\docutils\parsers\rst\states.py", line 2318, in explicit_markup
        nodelist, blank_finish = self.explicit_construct(match)
      File "C:\Python36\lib\site-packages\docutils\parsers\rst\states.py", line 2330, in explicit_construct
        return method(self, expmatch)
      File "C:\Python36\lib\site-packages\docutils\parsers\rst\states.py", line 2073, in directive
        directive_class, match, type_name, option_presets)
      File "C:\Python36\lib\site-packages\docutils\parsers\rst\states.py", line 2122, in run_directive
        result = directive_instance.run()
      File "C:\Python36\lib\site-packages\sphinx\ext\autodoc.py", line 1647, in run
        documenter.generate(more_content=self.content)
      File "C:\Python36\lib\site-packages\sphinx\ext\autodoc.py", line 992, in generate
        self.document_members(all_members)
      File "C:\Python36\lib\site-packages\sphinx\ext\autodoc.py", line 914, in document_members
        check_module=members_check_module and not isattr)
      File "C:\Python36\lib\site-packages\sphinx\ext\autodoc.py", line 989, in generate
        self.add_content(more_content)
      File "C:\Python36\lib\site-packages\sphinx\ext\autodoc.py", line 1362, in add_content
        ModuleLevelDocumenter.add_content(self, more_content)
      File "C:\Python36\lib\site-packages\sphinx\ext\autodoc.py", line 723, in add_content
        for i, line in enumerate(self.process_doc(docstrings)):
      File "C:\Python36\lib\site-packages\sphinx\ext\autodoc.py", line 685, in process_doc
        self.options, docstringlines)
      File "C:\Python36\lib\site-packages\sphinx\application.py", line 589, in emit
        results.append(callback(self, *args))
      File "C:\Python36\lib\site-packages\sphinx_autodoc_typehints.py", line 68, in process_docstring
        type_hints = get_type_hints(obj)
      File "C:\Python36\lib\typing.py", line 1419, in get_type_hints
        'or function.'.format(obj))
    TypeError: <slot wrapper '__init__' of 'object' objects> is not a module, class, method, or function.
    
    bug 
    opened by gdude2002 23
  • Support TypeVar arguments

    Support TypeVar arguments

    Example:

    class MyBase:
        """MyBase Doc"""
    
    T = TypeVar('T', bound='MyBase')
    
    class OtherClass:
        """OtherClass Doc"""
        def create_T(cls: Type[T]) -> T:
            """create_T Doc"""
            return cls()
    

    This generates the following Warning: [...] OtherClass.create_T:: WARNING: py:class reference target not found: T

    opened by gpkc 22
  • Error building docs with v1.10

    Error building docs with v1.10

    My docs now fail to build with 1.10 (work with 1.9 or lower):

    Exception occurred:
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx_autodoc_typehints.py", line 60, in get_annotation_args
        original = getattr(sys.modules[module], class_name)
    KeyError: 'numpy'
    The full traceback has been saved in /tmp/sphinx-err-e8ca7ci1.log, if you want to report the issue to the developers.
    

    Here's the log file:

    # Sphinx version: 2.1.2
    # Python version: 3.7.3 (CPython)
    # Docutils version: 0.14 
    # Jinja2 version: 2.10.1
    # Last messages:
    #   failed
    #   failed: No such config value: typehints_fully_qualified
    #   loading intersphinx inventory from https://docs.python.org/objects.inv...
    #   intersphinx inventory has moved: https://docs.python.org/objects.inv -> https://docs.python.org/3/objects.inv
    #   building [mo]: targets for 0 po files that are out of date
    #   building [html]: targets for 61 source files that are out of date
    #   updating environment:
    #   61 added, 0 changed, 0 removed
    #   reading sources... [  1%] api/alibi
    #   reading sources... [  3%] api/alibi.confidence
    # Loaded extensions:
    #   sphinx.ext.mathjax (2.1.2) from /home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/ext/mathjax.py
    #   sphinxcontrib.applehelp (1.0.1) from /home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinxcontrib/applehelp/__init__.py
    #   sphinxcontrib.devhelp (1.0.1) from /home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinxcontrib/devhelp/__init__.py
    #   sphinxcontrib.htmlhelp (1.0.2) from /home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinxcontrib/htmlhelp/__init__.py
    #   sphinxcontrib.serializinghtml (1.1.3) from /home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinxcontrib/serializinghtml/__init__.py
    #   sphinxcontrib.qthelp (1.0.2) from /home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinxcontrib/qthelp/__init__.py
    #   alabaster (0.7.12) from /home/janis/.conda/envs/py37/lib/python3.7/site-packages/alabaster/__init__.py
    #   sphinx.ext.autodoc (2.1.2) from /home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/ext/autodoc/__init__.py
    #   sphinx.ext.doctest (2.1.2) from /home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/ext/doctest.py
    #   sphinx.ext.intersphinx (2.1.2) from /home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/ext/intersphinx.py
    #   sphinx.ext.todo (2.1.2) from /home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/ext/todo.py
    #   sphinx.ext.coverage (2.1.2) from /home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/ext/coverage.py
    #   sphinx.ext.ifconfig (2.1.2) from /home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/ext/ifconfig.py
    #   sphinx.ext.viewcode (2.1.2) from /home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/ext/viewcode.py
    #   sphinx.ext.napoleon (2.1.2) from /home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/ext/napoleon/__init__.py
    #   sphinx_autodoc_typehints (unknown version) from /home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx_autodoc_typehints.py
    #   sphinxcontrib.apidoc (0.3.0) from /home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinxcontrib/apidoc/__init__.py
    #   nbsphinx (0.4.2) from /home/janis/.conda/envs/py37/lib/python3.7/site-packages/nbsphinx.py
    #   nbsphinx_link (1.2.0) from /home/janis/.conda/envs/py37/lib/python3.7/site-packages/nbsphinx_link/__init__.py
    #   m2r (0.2.1) from /home/janis/.conda/envs/py37/lib/python3.7/site-packages/m2r.py
    Traceback (most recent call last):
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/cmd/build.py", line 284, in build_main
        app.build(args.force_all, filenames)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/application.py", line 345, in build
        self.builder.build_update()
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/builders/__init__.py", line 319, in build_update
        len(to_build))
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/builders/__init__.py", line 332, in build
        updated_docnames = set(self.read())
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/builders/__init__.py", line 438, in read
        self._read_serial(docnames)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/builders/__init__.py", line 460, in _read_serial
        self.read_doc(docname)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/builders/__init__.py", line 504, in read_doc
        doctree = read_doc(self.app, self.env, self.env.doc2path(docname))
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/io.py", line 325, in read_doc
        pub.publish()
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/docutils/core.py", line 217, in publish
        self.settings)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/io.py", line 113, in read
        self.parse()
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/docutils/readers/__init__.py", line 78, in parse
        self.parser.parse(self.input, document)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/parsers.py", line 94, in parse
        self.statemachine.run(inputlines, document, inliner=self.inliner)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/docutils/parsers/rst/states.py", line 171, in run
        input_source=document['source'])
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/docutils/statemachine.py", line 239, in run
        context, state, transitions)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/docutils/statemachine.py", line 460, in check_line
        return method(match, context, next_state)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/docutils/parsers/rst/states.py", line 2753, in underline
        self.section(title, source, style, lineno - 1, messages)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/docutils/parsers/rst/states.py", line 327, in section
        self.new_subsection(title, lineno, messages)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/docutils/parsers/rst/states.py", line 395, in new_subsection
        node=section_node, match_titles=True)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/docutils/parsers/rst/states.py", line 282, in nested_parse
        node=node, match_titles=match_titles)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/docutils/parsers/rst/states.py", line 196, in run
        results = StateMachineWS.run(self, input_lines, input_offset)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/docutils/statemachine.py", line 239, in run
        context, state, transitions)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/docutils/statemachine.py", line 460, in check_line
        return method(match, context, next_state)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/docutils/parsers/rst/states.py", line 2326, in explicit_markup
        nodelist, blank_finish = self.explicit_construct(match)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/docutils/parsers/rst/states.py", line 2338, in explicit_construct
        return method(self, expmatch)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/docutils/parsers/rst/states.py", line 2081, in directive
        directive_class, match, type_name, option_presets)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/docutils/parsers/rst/states.py", line 2130, in run_directive
        result = directive_instance.run()
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/ext/autodoc/directive.py", line 150, in run
        documenter.generate(more_content=self.content)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/ext/autodoc/__init__.py", line 760, in generate
        self.document_members(all_members)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/ext/autodoc/__init__.py", line 681, in document_members
        check_module=members_check_module and not isattr)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/ext/autodoc/__init__.py", line 757, in generate
        self.add_content(more_content)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/ext/autodoc/__init__.py", line 495, in add_content
        for i, line in enumerate(self.process_doc(docstrings)):
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/ext/autodoc/__init__.py", line 463, in process_doc
        self.options, docstringlines)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/application.py", line 449, in emit
        return self.events.emit(event, *args)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx/events.py", line 103, in emit
        results.append(callback(self.app, *args))
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx_autodoc_typehints.py", line 368, in process_docstring
        annotation, fully_qualified=app.config.typehints_fully_qualified)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx_autodoc_typehints.py", line 110, in format_annotation
        args = get_annotation_args(annotation, module, class_name)
      File "/home/janis/.conda/envs/py37/lib/python3.7/site-packages/sphinx_autodoc_typehints.py", line 60, in get_annotation_args
        original = getattr(sys.modules[module], class_name)
    KeyError: 'numpy'
    
    bug 
    opened by jklaise 17
  • Strip annotations from initializer signatures

    Strip annotations from initializer signatures

    In process_signature(), the test getattr(obj, '__annotations__', None) fails for classes because it tests against the class object itself and not the initializer method. This results in type annotations not being stripped from the initializer signatures.

    This PR just grabs the initializer method before continuing with the test for the presence of annotations.

    opened by josiah-wolf-oberholtzer 17
  • Python type hint: NameError: name '...' is not defined

    Python type hint: NameError: name '...' is not defined

    Usecase:

    class Foo(object):
        def __init__(self):
            pass
        
        def get_foo(self, name:str) -> 'Foo' :
            return self
    

    The above is a simple example of the issue I am facing. Python type hints supports ' ' to be used when the class is not defined and will be defined at a later stage. Sphinx documentation using your extension fails because Foo is not defined.

    Note: I have also tried adding a __main__ method, thinking it might stop auto-execution, but I ended up having the same error.

    Stacktrace

    bug 
    opened by kingspp 17
  • process_signature silently drops any docstring-specified signature

    process_signature silently drops any docstring-specified signature

    process_signature gets the argspec from the object itself, so any docstring-specified signature (http://www.sphinx-doc.org/en/stable/ext/autodoc.html#confval-autodoc_docstring_signature) gets silently dropped.

    See e.g. http://defopt.readthedocs.io/en/stable/api.html#defopt.run vs https://github.com/evanunderscore/defopt/blob/a03769b931460ce9234c02351f4ee7fe9d055fee/defopt.py#L68 (defopt.run should be listed in the docs with the signature run(funcs, *, parsers=None, short=None, show_types=False, argv=None)).

    Given that you can't necessarily afford to eval the annotations that may exist in a docstring-specified signature (and you actually want their string representations anyways), I guess a correct approach when such a signature is present (although a bit a pain to implement?) would be to parse the signature into an AST, fetch out the parts of the AST corresponding to the annotations, map them back to the string using the AST col_offset, and remove them thusly (and move them to the docstring). Or perhaps there's some smarter approach...

    opened by anntzer 16
  • Getting an `IndentationError` related specifically to a doc string while building.

    Getting an `IndentationError` related specifically to a doc string while building.

    I've encountered a Sphinx bug which I reported here, and it was pointed out to me (via the log) that the error was raised by sphinx-autodoc-hints. The report is duplicated below.

    I'm getting the following error when trying to build HTML files:

    /usr/local/anaconda/lib/python3.7/site-packages/sphinx/util/inspect.py:555: RemovedInSphinx40Warning: sphinx.util.inspect.Signature() is deprecated
      RemovedInSphinx40Warning)
    
    Exception occurred:
      File "/usr/local/anaconda/lib/python3.7/site-packages/typed_ast/ast3.py", line 62, in parse
        return _ast3._parse(source, filename, mode, feature_version)
      File "<unknown>", line 1
        @classmethod
        ^
    IndentationError: unexpected indent
    The full traceback has been saved in /var/folders/yp/lf1xdvp165n5xb7hcrwzpngc0000gn/T/sphinx-err-jidws8_h.log, if you want to report the issue to the developers.
    Please also report this if it was a user error, so that a better error message can be provided next time.
    A bug report can be filed in the tracker at <https://github.com/sphinx-doc/sphinx/issues>. Thanks!
    make: *** [html] Error 2
    

    The code that it's getting caught on is this:

    	@classmethod
    	def fromFITSHeader(cls, fits_header=None, uncertainty=4.848e-6):
    		'''
    		Factory method to create a region from the provided FITS header; the returned object will be as specific as possible (but probably an ASTPolygon).
    		
    		:param fits_header: a FITS header (Astropy, fitsio, an array of cards)
    		:param uncertainty: defaults to 4.848e-6, an uncertainty of 1 arcsec
    		'''
    		if fits_header is None:
    			raise ValueError("This method requires a 'fits_header' to be set.")
    
    		. . .
    

    I am sure the problem is not an indentation error (at least as far as the Python code). When I delete the entire docstring, make html works without error. Any docstring I add causes the error, even a blank one, e.g.

    '''
    
    '''
    

    The Sphinx log is attached here: sphinx-err-gnkuj5m5.log

    Thanks!

    duplicate 
    opened by demitri 15
  • canot find the signature of a method when setting up this extension

    canot find the signature of a method when setting up this extension

    I would like to start using type hinting in my lib to improve the quality of the code. I started small by simply changing few of the methods and installing this extention in my documentation. When I run the doc build (using the classic make html shipped with sphinx quickstart) I get the following error (sorry for the french):

    Le gestionnaire <function process_signature at 0x114c9d280> de l'évènement 'autodoc-process-signature' a créé une exception. (exception: no signature found for builtin <traitlets.traitlets.ObserveHandler object at 0x104b825e0>)

    I wasn't very lucky on Google with this one and I have several questions to identify what is happening here:

    • is it something you have already seen?
    • my lib is now big, how can I know which file triggered the error?
    • could it be related to the fact ObserverHandler is only use with decorators?
    • why is it working without this extention ?

    In case you need an example I pushed my branch here: https://github.com/12rambau/sepal_ui/commit/0ef46da331432bebf7b2a6b3934f050cb0291325

    opened by 12rambau 0
  • Incorrect rename of extra `type-comments`

    Incorrect rename of extra `type-comments`

    The change introduced in https://github.com/tox-dev/sphinx-autodoc-typehints/commit/ccc75d244d0f4452048f80fc73e39a34a4eefc00 renamed the extra type-comments to type-comment (no s), causing mismatched warnings when installing with pip:

    pip install "sphinx-autodoc-typehints[type_comments]<1.19"   # OK
    
    pip install "sphinx-autodoc-typehints[type_comments]>=1.19" 
    [...]
    WARNING: sphinx-autodoc-typehints 1.19.4 does not provide the extra 'type_comments'
    [...]
    
    opened by fmigneault 0
  • Problem with resolving MutableMapping with type subscripts

    Problem with resolving MutableMapping with type subscripts

    This worked fine is version 1.14.1 and earlier but starting in 1.15.0 I get TypeError: ABCMeta is not subscriptable.

    I have code that's something like this:

    from typing import TYPE_CHECKING
    
    if TYPE_CHECKING:
        MyBaseType = MutableMapping[str, Any]
    else:
        MyBaseType = MutableMapping
    
    class MyCustomClass(MyBaseType):
        ...
    
    
    opened by anselor 0
  • Every warning/error should provide useful context

    Every warning/error should provide useful context

    Warnings/errors with generic messages do not provide context for what in the code caused the error.

    Specifically, I ran into it here:

    https://github.com/tox-dev/sphinx-autodoc-typehints/blob/bf27befb610426838d1f2926e470815c47cc8ab8/src/sphinx_autodoc_typehints/init.py#L343

    I changed that log to also print guarded_code and it helped a lot. But I really think it should reraise the exception with the guarded_code and then catch and log it here with additional context:

    https://github.com/tox-dev/sphinx-autodoc-typehints/blob/bf27befb610426838d1f2926e470815c47cc8ab8/src/sphinx_autodoc_typehints/init.py#L347

    opened by anselor 1
  • `typehints_defaults` does not work when missing python3 sytle type hints

    `typehints_defaults` does not work when missing python3 sytle type hints

    Given function signature

    def grid_archive_heatmap(archive, ax=None, ... )
    

    and setting typehints_defaults = "comma" ("braces", "braces-after") . sphinx-autodoc-typehints does not correctly add a "default=" clause for the argument ax in the documentation.

    This problem was encountered at https://github.com/icaros-usc/pyribs/pull/204.

    bug help wanted 
    opened by itsdawei 1
  •  get_annotation_class_name() not always returning string

    get_annotation_class_name() not always returning string

    We encountered the following error while setting a return type which mocked in Sphinx config using a custom Mock object

    Handler <function process_docstring at 0x7f6c16c8ec10> for event 'autodoc-process-docstring' threw an exception (exception: getattr(): attribute name must be string)
    

    The actual exception is raised in get_annotation_args in this line due to a class_name not being str:

    original = getattr(sys.modules[module], class_name)
    

    Looking further into PR #145 was opened to track this issue as they also found that get_annotation_class_name is not always retuning a str but it seems was never fixed.

    A quick example to show how the custom Mock does not return str for __qualname__ or _name attributes:

    >>> class Mock:
        __all__ = []
        def __init__(self, *args, **kwargs):
            pass
        def __call__(self, *args, **kwargs):
            return ''
        @classmethod
        def __getattr__(cls, name):
            return Mock()
        def __add__(self, other):
            return other
        def __or__(self, __):
            return Mock()
    >> Mock()
    <__main__.Mock object at 0x7f22528baf40>
    >>> m =Mock()
    >>> m.__qualname__
    <class '__main__.__qualname__'>
    >>> m._name
    <class '__main__._name'>
    >>> getattr(m, m.__qualname__)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: getattr(): attribute name must be string
    

    We can workaround the issue by not using the custom mock any more but it is still an inconvenience

    help wanted 
    opened by cas-- 1
Releases(1.19.5)
  • 1.19.5(Nov 2, 2022)

    What's Changed

    • [pre-commit.ci] pre-commit autoupdate by @pre-commit-ci in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/262
    • [pre-commit.ci] pre-commit autoupdate by @pre-commit-ci in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/264
    • [pre-commit.ci] pre-commit autoupdate by @pre-commit-ci in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/265
    • Add link to pyproject-api docs as example of this extension by @ketozhang in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/267

    New Contributors

    • @ketozhang made their first contribution in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/267

    Full Changelog: https://github.com/tox-dev/sphinx-autodoc-typehints/compare/1.19.4...1.19.5

    Source code(tar.gz)
    Source code(zip)
  • 1.19.4(Sep 27, 2022)

    What's Changed

    • Fix IndexError for line and keyword split by @gaborbernat in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/261

    Full Changelog: https://github.com/tox-dev/sphinx-autodoc-typehints/compare/1.19.3...1.19.4

    Source code(tar.gz)
    Source code(zip)
  • 1.19.3(Sep 26, 2022)

    What's Changed

    • [pre-commit.ci] pre-commit autoupdate by @pre-commit-ci in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/251
    • [pre-commit.ci] pre-commit autoupdate by @pre-commit-ci in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/252
    • Add support for paramspec by @Numerlor in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/255
    • allow starred args and kwargs in docstring params by @Numerlor in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/254
    • Fix the CI by @gaborbernat in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/258

    Full Changelog: https://github.com/tox-dev/sphinx-autodoc-typehints/compare/1.19.2...1.19.3

    Source code(tar.gz)
    Source code(zip)
  • 1.19.2(Aug 8, 2022)

    What's Changed

    • [pre-commit.ci] pre-commit autoupdate by @pre-commit-ci in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/249
    • only convert role for pydata annotations if module is typing by @Numerlor in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/250

    New Contributors

    • @Numerlor made their first contribution in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/250

    Full Changelog: https://github.com/tox-dev/sphinx-autodoc-typehints/compare/1.19.1...1.19.2

    Source code(tar.gz)
    Source code(zip)
  • 1.19.1(Jul 31, 2022)

    What's Changed

    • Add support for recursive type hints by @hmc-cs-mdrissi in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/248

    New Contributors

    • @hmc-cs-mdrissi made their first contribution in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/248

    Full Changelog: https://github.com/tox-dev/sphinx-autodoc-typehints/compare/1.19.0...1.19.1

    Source code(tar.gz)
    Source code(zip)
  • 1.19.0(Jul 27, 2022)

    What's Changed

    • Bump actions/download-artifact from 2 to 3 by @dependabot in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/240
    • Bump actions/checkout from 2 to 3 by @dependabot in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/241
    • Bump actions/setup-python from 2 to 4 by @dependabot in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/242
    • Bump actions/upload-artifact from 2 to 3 by @dependabot in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/243
    • [pre-commit.ci] pre-commit autoupdate by @pre-commit-ci in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/236
    • [pre-commit.ci] pre-commit autoupdate by @pre-commit-ci in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/244
    • [pre-commit.ci] pre-commit autoupdate by @pre-commit-ci in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/245
    • [pre-commit.ci] pre-commit autoupdate by @pre-commit-ci in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/246
    • Check 3.11 support by @gaborbernat in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/247

    New Contributors

    • @dependabot made their first contribution in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/240

    Full Changelog: https://github.com/tox-dev/sphinx-autodoc-typehints/compare/1.18.3...1.19.0

    Source code(tar.gz)
    Source code(zip)
  • 1.18.3(Jun 10, 2022)

    What's Changed

    • Fix for new nptyping by @gaborbernat in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/235

    Full Changelog: https://github.com/tox-dev/sphinx-autodoc-typehints/compare/1.18.2...1.18.3

    Source code(tar.gz)
    Source code(zip)
  • 1.18.2(Jun 3, 2022)

    What's Changed

    • [pre-commit.ci] pre-commit autoupdate by @pre-commit-ci in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/230
    • Support and require nptyping 2.1.1 by @gaborbernat in https://github.com/tox-dev/sphinx-autodoc-typehints/pull/232

    Full Changelog: https://github.com/tox-dev/sphinx-autodoc-typehints/compare/1.18.1...1.18.2

    Source code(tar.gz)
    Source code(zip)
Owner
Alex Grönholm
Alex Grönholm
Sphinx-performance - CLI tool to measure the build time of different, free configurable Sphinx-Projects

CLI tool to measure the build time of different, free configurable Sphinx-Projec

useblocks 11 Nov 25, 2022
A powerful Sphinx changelog-generating extension.

What is Releases? Releases is a Python (2.7, 3.4+) compatible Sphinx (1.8+) extension designed to help you keep a source control friendly, merge frien

Jeff Forcier 166 Dec 29, 2022
Main repository for the Sphinx documentation builder

Sphinx Sphinx is a tool that makes it easy to create intelligent and beautiful documentation for Python projects (or other documents consisting of mul

null 5.1k Jan 2, 2023
A curated list of awesome tools for Sphinx Python Documentation Generator

Awesome Sphinx (Python Documentation Generator) A curated list of awesome extra libraries, software and resources for Sphinx (Python Documentation Gen

Hyunjun Kim 831 Dec 27, 2022
Main repository for the Sphinx documentation builder

Sphinx Sphinx is a tool that makes it easy to create intelligent and beautiful documentation for Python projects (or other documents consisting of mul

null 5.1k Jan 4, 2023
Sphinx theme for readthedocs.org

Read the Docs Sphinx Theme This Sphinx theme was designed to provide a great reader experience for documentation users on both desktop and mobile devi

Read the Docs 4.3k Dec 31, 2022
Numpy's Sphinx extensions

numpydoc -- Numpy's Sphinx extensions This package provides the numpydoc Sphinx extension for handling docstrings formatted according to the NumPy doc

NumPy 234 Dec 26, 2022
ReStructuredText and Sphinx bridge to Doxygen

Breathe Packagers: PGP signing key changes for Breathe >= v4.23.0. https://github.com/michaeljones/breathe/issues/591 This is an extension to reStruct

Michael Jones 643 Dec 31, 2022
Watch a Sphinx directory and rebuild the documentation when a change is detected. Also includes a livereload enabled web server.

sphinx-autobuild Rebuild Sphinx documentation on changes, with live-reload in the browser. Installation sphinx-autobuild is available on PyPI. It can

Executable Books 440 Jan 6, 2023
sphinx builder that outputs markdown files.

sphinx-markdown-builder sphinx builder that outputs markdown files Please ★ this repo if you found it useful ★ ★ ★ If you want frontmatter support ple

Clay Risser 144 Jan 6, 2023
Sphinx Bootstrap Theme

Sphinx Bootstrap Theme This Sphinx theme integrates the Bootstrap CSS / JavaScript framework with various layout options, hierarchical menu navigation

Ryan Roemer 584 Nov 16, 2022
📖 Generate markdown API documentation from Google-style Python docstring. The lazy alternative to Sphinx.

lazydocs Generate markdown API documentation for Google-style Python docstring. Getting Started • Features • Documentation • Support • Contribution •

Machine Learning Tooling 118 Dec 31, 2022
Seamlessly integrate pydantic models in your Sphinx documentation.

Seamlessly integrate pydantic models in your Sphinx documentation.

Franz Wöllert 71 Dec 26, 2022
Speed up Sphinx builds by selectively removing toctrees from some pages

Remove toctrees from Sphinx pages Improve your Sphinx build time by selectively removing TocTree objects from pages. This is useful if your documentat

Executable Books 8 Jan 4, 2023
python package sphinx template

python-package-sphinx-template python-package-sphinx-template

Soumil Nitin Shah 2 Dec 26, 2022
epub2sphinx is a tool to convert epub files to ReST for Sphinx

epub2sphinx epub2sphinx is a tool to convert epub files to ReST for Sphinx. It uses Pandoc for converting HTML data inside epub files into ReST. It cr

Nihaal 8 Dec 15, 2022
A `:github:` role for Sphinx

sphinx-github-role A github role for Sphinx. Usage Basic usage MyST: :caption: index.md See {github}`astrojuanlu/sphinx-github-role#1`. reStructuredT

Juan Luis Cano Rodríguez 4 Nov 22, 2022
This is a template (starter kit) for writing Maturity Work with Sphinx / LaTeX at Collège du Sud

sphinx-tm-template Ce dépôt est un template de base utilisable pour écrire ton travail de maturité dans le séminaire d'informatique du Collège du Sud.

null 6 Dec 22, 2022
VSCode extension that generates docstrings for python files

VSCode Python Docstring Generator Visual Studio Code extension to quickly generate docstrings for python functions. Features Quickly generate a docstr

Nils Werner 506 Jan 3, 2023