Skip to content

Commit

Permalink
REF: Format Optional as X | None
Browse files Browse the repository at this point in the history
Ref: 6e8bdfd ENH: Improve formatting of Optional, Union and collection.abc types
Ref: #395

Thanks @hhoppe
  • Loading branch information
kernc committed Nov 26, 2024
1 parent 78e771b commit 115a168
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 6 deletions.
10 changes: 5 additions & 5 deletions pdoc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1294,17 +1294,17 @@ def _formatannotation(annot):
>>> _formatannotation(NewType('MyType', str))
'pdoc.MyType'
>>> _formatannotation(Optional[Tuple[Optional[int], None]])
'Optional[Tuple[Optional[int], None]]'
'Tuple[int | None, None] | None'
>>> _formatannotation(Optional[Union[int, float, None]])
'Optional[int | float]'
'int | float | None'
>>> _formatannotation(Union[int, float])
'int | float'
>>> from typing import Callable
>>> _formatannotation(Callable[[Optional[int]], float])
'Callable[[Optional[int]], float]'
'Callable[[int | None], float]'
>>> from collections.abc import Callable
>>> _formatannotation(Callable[[Optional[int]], float])
'Callable[[Optional[int]], float]'
'Callable[[int | None], float]'
"""
class force_repr(str):
__repr__ = str.__str__
Expand All @@ -1322,7 +1322,7 @@ def maybe_replace_reprs(a):
t = ' | '.join(inspect.formatannotation(maybe_replace_reprs(x))
for x in union_args)
if is_optional:
t = f'Optional[{t}]'
t += ' | None'
return force_repr(t)
# typing.NewType('T', foo) -> T
module = getattr(a, '__module__', '')
Expand Down
2 changes: 1 addition & 1 deletion pdoc/test/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -975,7 +975,7 @@ def prop(self) -> typing.Optional[int]:

mod = DUMMY_PDOC_MODULE
cls = pdoc.Class('Foobar', mod, Foobar)
self.assertEqual(cls.doc['prop'].type_annotation(), 'Optional[int]')
self.assertEqual(cls.doc['prop'].type_annotation(), 'int\N{NBSP}|\N{NBSP}None')

@ignore_warnings
def test_Variable_type_annotation_py36plus(self):
Expand Down

0 comments on commit 115a168

Please sign in to comment.