diff --git a/sphinx_autodoc_typehints.py b/sphinx_autodoc_typehints.py index d2671bb5..90196af2 100644 --- a/sphinx_autodoc_typehints.py +++ b/sphinx_autodoc_typehints.py @@ -108,6 +108,12 @@ def format_annotation(annotation): return '{}`~{}.{}`{}'.format(prefix, module, class_name, extra) elif annotation is Ellipsis: return '...' + elif hasattr(annotation, '__name__') \ + and hasattr(annotation, '__supertype__') \ + and annotation.__module__ == 'typing': + # May be a NewType + return ':py:class:`~typing.NewType.{}`\\[{}]'.format( + annotation.__name__, format_annotation(annotation.__supertype__)) elif inspect.isclass(annotation) or inspect.isclass(getattr(annotation, '__origin__', None)): if not inspect.isclass(annotation): annotation_cls = annotation.__origin__ diff --git a/tests/test_sphinx_autodoc_typehints.py b/tests/test_sphinx_autodoc_typehints.py index 5a944f05..a552850e 100644 --- a/tests/test_sphinx_autodoc_typehints.py +++ b/tests/test_sphinx_autodoc_typehints.py @@ -2,14 +2,15 @@ import pytest import sys import textwrap -from typing import ( - Any, AnyStr, Callable, Dict, Generic, Mapping, Optional, Pattern, Tuple, TypeVar, Union, Type) +from typing import Any, AnyStr, Callable, Dict, Generic, \ + Mapping, Optional, Pattern, Tuple, TypeVar, Union, Type, NewType from sphinx_autodoc_typehints import format_annotation, process_docstring T = TypeVar('T') U = TypeVar('U', covariant=True) V = TypeVar('V', contravariant=True) +Z = NewType('Z', float) class A: @@ -69,6 +70,7 @@ class Slotted: (Callable[[T], T], ':py:data:`~typing.Callable`\\[\\[\\~T], \\~T]'), (Pattern, ':py:class:`~typing.Pattern`\\[:py:data:`~typing.AnyStr`]'), (Pattern[str], ':py:class:`~typing.Pattern`\\[:py:class:`str`]'), + (Z, ':py:class:`~typing.NewType.Z`\\[:py:class:`float`]'), (A, ':py:class:`~%s.A`' % __name__), (B, ':py:class:`~%s.B`\\[\\~T]' % __name__), (B[int], ':py:class:`~%s.B`\\[:py:class:`int`]' % __name__)