Skip to content

Identify typing.NewType wrappers and construct annotation references #64

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 23, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions sphinx_autodoc_typehints.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,10 @@ def format_annotation(annotation):
return '{}`~{}.{}`{}'.format(prefix, module, class_name, extra)
elif annotation is Ellipsis:
return '...'
elif (inspect.isfunction(annotation) and annotation.__module__ == 'typing' and
hasattr(annotation, '__name__') and hasattr(annotation, '__supertype__')):
return ':py:func:`~typing.NewType`\\(:py:data:`~{}`, {})'.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__
Expand Down
7 changes: 5 additions & 2 deletions tests/test_sphinx_autodoc_typehints.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
import sys
import textwrap
from typing import (
Any, AnyStr, Callable, Dict, Generic, Mapping, Optional, Pattern, Tuple, TypeVar, Union, Type)
Any, AnyStr, Callable, Dict, Generic, Mapping, NewType, Optional, Pattern,
Tuple, TypeVar, Union, Type)

from typing_extensions import Protocol

Expand All @@ -12,6 +13,7 @@
T = TypeVar('T')
U = TypeVar('U', covariant=True)
V = TypeVar('V', contravariant=True)
W = NewType('W', str)


class A:
Expand Down Expand Up @@ -89,7 +91,8 @@ class Slotted:
(C, ':py:class:`~%s.C`' % __name__),
(D, ':py:class:`~%s.D`' % __name__),
(E, ':py:class:`~%s.E`\\[\\~T]' % __name__),
(E[int], ':py:class:`~%s.E`\\[:py:class:`int`]' % __name__)
(E[int], ':py:class:`~%s.E`\\[:py:class:`int`]' % __name__),
(W, ':py:func:`~typing.NewType`\\(:py:data:`~W`, :py:class:`str`)')
])
def test_format_annotation(annotation, expected_result):
result = format_annotation(annotation)
Expand Down