Skip to content

Commit 8d3867b

Browse files
gwaxagronholm
authored andcommitted
Identify typing.NewType wrappers and construct annotation references (#64)
1 parent c6895fa commit 8d3867b

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

sphinx_autodoc_typehints.py

+4
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,10 @@ def format_annotation(annotation):
117117
return '{}`~{}.{}`{}'.format(prefix, module, class_name, extra)
118118
elif annotation is Ellipsis:
119119
return '...'
120+
elif (inspect.isfunction(annotation) and annotation.__module__ == 'typing' and
121+
hasattr(annotation, '__name__') and hasattr(annotation, '__supertype__')):
122+
return ':py:func:`~typing.NewType`\\(:py:data:`~{}`, {})'.format(
123+
annotation.__name__, format_annotation(annotation.__supertype__))
120124
elif inspect.isclass(annotation) or inspect.isclass(getattr(annotation, '__origin__', None)):
121125
if not inspect.isclass(annotation):
122126
annotation_cls = annotation.__origin__

tests/test_sphinx_autodoc_typehints.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
import sys
44
import textwrap
55
from typing import (
6-
Any, AnyStr, Callable, Dict, Generic, Mapping, Optional, Pattern, Tuple, TypeVar, Union, Type)
6+
Any, AnyStr, Callable, Dict, Generic, Mapping, NewType, Optional, Pattern,
7+
Tuple, TypeVar, Union, Type)
78

89
from typing_extensions import Protocol
910

@@ -12,6 +13,7 @@
1213
T = TypeVar('T')
1314
U = TypeVar('U', covariant=True)
1415
V = TypeVar('V', contravariant=True)
16+
W = NewType('W', str)
1517

1618

1719
class A:
@@ -89,7 +91,8 @@ class Slotted:
8991
(C, ':py:class:`~%s.C`' % __name__),
9092
(D, ':py:class:`~%s.D`' % __name__),
9193
(E, ':py:class:`~%s.E`\\[\\~T]' % __name__),
92-
(E[int], ':py:class:`~%s.E`\\[:py:class:`int`]' % __name__)
94+
(E[int], ':py:class:`~%s.E`\\[:py:class:`int`]' % __name__),
95+
(W, ':py:func:`~typing.NewType`\\(:py:data:`~W`, :py:class:`str`)')
9396
])
9497
def test_format_annotation(annotation, expected_result):
9598
result = format_annotation(annotation)

0 commit comments

Comments
 (0)