Skip to content

Commit 39a1e73

Browse files
ENH: Better format typing.NewType annotations (#254)
* ENH: Show new type names for function signatures Fixes: #253 * Fixup pdoc/__init__.py
1 parent 37e5afe commit 39a1e73

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

pdoc/__init__.py

+16-2
Original file line numberDiff line numberDiff line change
@@ -1167,6 +1167,20 @@ def _link_inheritance(self):
11671167
del self._super_members
11681168

11691169

1170+
def _formatannotation(annot):
1171+
"""
1172+
Format annotation, properly handling NewType types
1173+
1174+
>>> _formatannotation(NewType('MyType', str))
1175+
'MyType'
1176+
"""
1177+
is_new_type = (getattr(annot, '__qualname__', '').startswith('NewType.') and
1178+
getattr(annot, '__module__', '') == 'typing')
1179+
if is_new_type:
1180+
return annot.__name__
1181+
return inspect.formatannotation(annot)
1182+
1183+
11701184
class Function(Doc):
11711185
"""
11721186
Representation of documentation for a function or method.
@@ -1265,7 +1279,7 @@ def return_annotation(self, *, link=None) -> str:
12651279
if isinstance(annot, str):
12661280
s = annot
12671281
else:
1268-
s = inspect.formatannotation(annot)
1282+
s = _formatannotation(annot)
12691283
s = re.sub(r'\b(typing\.)?ForwardRef\((?P<quot>[\"\'])(?P<str>.*?)(?P=quot)\)',
12701284
r'\g<str>', s)
12711285
s = s.replace(' ', '\N{NBSP}') # Better line breaks in html signatures
@@ -1371,7 +1385,7 @@ def __repr__(self):
13711385

13721386
formatted = p.name
13731387
if p.annotation is not EMPTY:
1374-
annotation = inspect.formatannotation(p.annotation).replace(' ', '\N{NBSP}')
1388+
annotation = _formatannotation(p.annotation).replace(' ', '\N{NBSP}')
13751389
# "Eval" forward-declarations (typing string literals)
13761390
if isinstance(p.annotation, str):
13771391
annotation = annotation.strip("'")

pdoc/test/__init__.py

+10
Original file line numberDiff line numberDiff line change
@@ -841,6 +841,16 @@ def bug130_str_annotation(a: "str"):
841841
self.assertEqual(pdoc.Function('bug130', mod, bug130_str_annotation).params(annotate=True),
842842
['a:\N{NBSP}str'])
843843

844+
# typed, NewType
845+
CustomType = typing.NewType('CustomType', bool)
846+
847+
def bug253_newtype_annotation(a: CustomType):
848+
return
849+
850+
self.assertEqual(
851+
pdoc.Function('bug253', mod, bug253_newtype_annotation).params(annotate=True),
852+
['a:\N{NBSP}CustomType'])
853+
844854
# builtin callables with signatures in docstrings
845855
from itertools import repeat
846856
self.assertEqual(pdoc.Function('repeat', mod, repeat).params(), ['object', 'times'])

0 commit comments

Comments
 (0)