Skip to content

Commit c6895fa

Browse files
icgoodagronholm
authored andcommitted
Added support for typing_extensions.Protocol (#60)
1 parent fe7ccb2 commit c6895fa

File tree

3 files changed

+26
-4
lines changed

3 files changed

+26
-4
lines changed

setup.cfg

+3-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,9 @@ install_requires =
3030
typing >= 3.5; python_version == "3.4"
3131

3232
[options.extras_require]
33-
test = pytest >= 3.1.0
33+
test =
34+
pytest >= 3.1.0
35+
typing_extensions >= 3.5
3436

3537
[flake8]
3638
max-line-length = 99

sphinx_autodoc_typehints.py

+9-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@
55
from sphinx.util import logging
66
from sphinx.util.inspect import Signature
77

8+
try:
9+
from typing_extensions import Protocol
10+
except ImportError:
11+
Protocol = None
12+
813
try:
914
from inspect import unwrap
1015
except ImportError:
@@ -47,7 +52,8 @@ def format_annotation(annotation):
4752
if inspect.isclass(getattr(annotation, '__origin__', None)):
4853
annotation_cls = annotation.__origin__
4954
try:
50-
if Generic in annotation_cls.mro():
55+
mro = annotation_cls.mro()
56+
if Generic in mro or (Protocol and Protocol in mro):
5157
module = annotation_cls.__module__
5258
except TypeError:
5359
pass # annotation_cls was either the "type" object or typing.Type
@@ -116,7 +122,8 @@ def format_annotation(annotation):
116122
annotation_cls = annotation.__origin__
117123

118124
extra = ''
119-
if Generic in annotation_cls.mro():
125+
mro = annotation_cls.mro()
126+
if Generic in mro or (Protocol and Protocol in mro):
120127
params = (getattr(annotation, '__parameters__', None) or
121128
getattr(annotation, '__args__', None))
122129
if params:

tests/test_sphinx_autodoc_typehints.py

+14-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
from typing import (
66
Any, AnyStr, Callable, Dict, Generic, Mapping, Optional, Pattern, Tuple, TypeVar, Union, Type)
77

8+
from typing_extensions import Protocol
9+
810
from sphinx_autodoc_typehints import format_annotation, process_docstring
911

1012
T = TypeVar('T')
@@ -25,6 +27,14 @@ class C(B[str]):
2527
pass
2628

2729

30+
class D(Protocol):
31+
pass
32+
33+
34+
class E(Protocol[T]):
35+
pass
36+
37+
2838
class Slotted:
2939
__slots__ = ()
3040

@@ -76,7 +86,10 @@ class Slotted:
7686
(A, ':py:class:`~%s.A`' % __name__),
7787
(B, ':py:class:`~%s.B`\\[\\~T]' % __name__),
7888
(B[int], ':py:class:`~%s.B`\\[:py:class:`int`]' % __name__),
79-
(C, ':py:class:`~%s.C`' % __name__)
89+
(C, ':py:class:`~%s.C`' % __name__),
90+
(D, ':py:class:`~%s.D`' % __name__),
91+
(E, ':py:class:`~%s.E`\\[\\~T]' % __name__),
92+
(E[int], ':py:class:`~%s.E`\\[:py:class:`int`]' % __name__)
8093
])
8194
def test_format_annotation(annotation, expected_result):
8295
result = format_annotation(annotation)

0 commit comments

Comments
 (0)