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
Course Materials for Math 340

UBC Math 340 Materials This repository aims to be the one repository for which you can find everything you about Math 340. Lecture Notes Lecture Notes

2 Nov 25, 2021
Projeto em Python colaborativo para o Bootcamp de Dados do Itaú em parceria com a Lets Code

🧾 lets-code-todo-list por Henrique V. Domingues e Josué Montalvão Projeto em Python colaborativo para o Bootcamp de Dados do Itaú em parceria com a L

Henrique V. Domingues 1 Jan 11, 2022
The purpose of this project is to share knowledge on how awesome Streamlit is and can be

Awesome Streamlit The fastest way to build Awesome Tools and Apps! Powered by Python! The purpose of this project is to share knowledge on how Awesome

Marc Skov Madsen 1.5k Jan 07, 2023
Show Rubygems description and annotate your code right from Sublime Text.

Gem Description for Sublime Text Show Rubygems description and annotate your code. Just mouse over your Gemfile's gem definitions to show the popup. s

Nando Vieira 2 Dec 19, 2022
Pydocstringformatter - A tool to automatically format Python docstrings that tries to follow recommendations from PEP 8 and PEP 257.

Pydocstringformatter A tool to automatically format Python docstrings that tries to follow recommendations from PEP 8 and PEP 257. See What it does fo

Daniël van Noord 31 Dec 29, 2022
Generate a backend and frontend stack using Python and json-ld, including interactive API documentation.

d4 - Base Project Generator Generate a backend and frontend stack using Python and json-ld, including interactive API documentation. d4? What is d4 fo

Markus Leist 3 May 03, 2022
JMESPath is a query language for JSON.

JMESPath JMESPath (pronounced "james path") allows you to declaratively specify how to extract elements from a JSON document. For example, given this

1.7k Dec 31, 2022
A Json Schema Generator

JSON Schema Generator Author : Eru Michael About A Json Schema Generator. This is a generic program that: Reads a JSON file similar to what's present

1 Nov 10, 2021
Anomaly Detection via Reverse Distillation from One-Class Embedding

Anomaly Detection via Reverse Distillation from One-Class Embedding Implementation (Official Code ⭐️ ⭐️ ⭐️ ) Environment pytorch == 1.91 torchvision =

73 Dec 19, 2022
A Python library that simplifies the extraction of datasets from XML content.

xmldataset: simple xml parsing 🗃️ XML Dataset: simple xml parsing Documentation: https://xmldataset.readthedocs.io A Python library that simplifies t

James Spurin 75 Dec 30, 2022
This repository outlines deploying a local Kubeflow v1.3 instance on microk8s and deploying a simple MNIST classifier using KFServing.

Zero to Inference with Kubeflow Getting Started This repository houses all of the tools, utilities, and example pipeline implementations for exploring

Ed Henry 3 May 18, 2022
This contains timezone mapping information for when preprocessed from the geonames data

when-data This contains timezone mapping information for when preprocessed from the geonames data. It exists in a separate repository so that one does

Armin Ronacher 2 Dec 07, 2021
Valentine-with-Python - A Python program generates an animation of a heart with cool texts of your loved one

Valentine with Python Valentines with Python is a mini fun project I have coded.

Niraj Tiwari 4 Dec 31, 2022
A curated list of awesome mathematics resources

A curated list of awesome mathematics resources

Cyrille Rossant 6.7k Jan 05, 2023
An open source utility for creating publication quality LaTex figures generated from OpenFOAM data files.

foamTEX An open source utility for creating publication quality LaTex figures generated from OpenFOAM data files. Explore the docs » Report Bug · Requ

1 Dec 19, 2021
Course materials for: Geospatial Data Science

Course materials for: Geospatial Data Science These course materials cover the lectures for the course held for the first time in spring 2022 at IT Un

Michael Szell 266 Jan 02, 2023
:blue_book: Automatic documentation from sources, for MkDocs.

mkdocstrings Automatic documentation from sources, for MkDocs. Features - Python handler - Requirements - Installation - Quick usage Features Language

1.1k Jan 04, 2023
Highlight Translator can help you translate the words quickly and accurately.

Highlight Translator can help you translate the words quickly and accurately. By only highlighting, copying, or screenshoting the content you want to translate anywhere on your computer (ex. PDF, PPT

Coolshan 48 Dec 21, 2022
NetBox plugin that stores configuration diffs and checks templates compliance

Config Officer - NetBox plugin NetBox plugin that deals with Cisco device configuration (collects running config from Cisco devices, indicates config

77 Dec 21, 2022
My Sublime Text theme

rsms sublime text theme Install: cd path/to/your/sublime/packages git clone https://github.com/rsms/sublime-theme.git rsms-theme You'll also need the

Rasmus 166 Jan 04, 2023