Skip to content

Commit

Permalink
REF: Also replace typing.Union[None, T] -> Optional[T]
Browse files Browse the repository at this point in the history
Closes #325

Co-authored-by: Hugues Hoppe <hhoppe@gmail.com>
  • Loading branch information
kernc and hhoppe committed Mar 21, 2021
1 parent bacbd53 commit c2c1320
Showing 1 changed file with 5 additions and 6 deletions.
11 changes: 5 additions & 6 deletions pdoc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1274,8 +1274,9 @@ def maybe_replace_reprs(a):
# Union[T, None] -> Optional[T]
if (getattr(a, '__origin__', None) is typing.Union and
len(a.__args__) == 2 and
a.__args__[1] is type(None)): # noqa: E721
t = inspect.formatannotation(maybe_replace_reprs(a.__args__[0]))
type(None) in a.__args__):
t = inspect.formatannotation(
maybe_replace_reprs(next(filter(None, a.__args__))))
return force_repr(f'Optional[{t}]')
# typing.NewType('T', foo) -> T
module = getattr(a, '__module__', '')
Expand All @@ -1285,10 +1286,8 @@ def maybe_replace_reprs(a):
if module.startswith('nptyping.'):
return force_repr(repr(a))
# Recurse into args
try:
if hasattr(a, 'copy_with') and hasattr(a, '__args__'):
a = a.copy_with(tuple([maybe_replace_reprs(arg) for arg in a.__args__]))
except Exception:
pass # Not a typing._GenericAlias
return a

return str(inspect.formatannotation(maybe_replace_reprs(annot)))
Expand Down Expand Up @@ -1393,7 +1392,7 @@ def return_annotation(self, *, link=None) -> str:
s = annot
else:
s = _formatannotation(annot)
s = re.sub(r'\b(typing\.)?ForwardRef\((?P<quot>[\"\'])(?P<str>.*?)(?P=quot)\)',
s = re.sub(r'\bForwardRef\((?P<quot>[\"\'])(?P<str>.*?)(?P=quot)\)',
r'\g<str>', s)
s = s.replace(' ', '\N{NBSP}') # Better line breaks in html signatures

Expand Down

0 comments on commit c2c1320

Please sign in to comment.