Skip to content
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

Optional[Type] is shown as Union[Type, NoneType] #324

Closed
hhoppe opened this issue Mar 19, 2021 · 3 comments
Closed

Optional[Type] is shown as Union[Type, NoneType] #324

hhoppe opened this issue Mar 19, 2021 · 3 comments
Labels
enhancement New feature or request

Comments

@hhoppe
Copy link
Contributor

hhoppe commented Mar 19, 2021

In the doc I maintain, https://google.github.io/mediapy/, the functions have many typing attributes.
These generally look great in the pdoc3 output, except that Optional[Type] is replaced by the more confusing Union[Type, NoneType].
Perhaps it would be possible to recognize this pattern and somehow change it back?

@hhoppe
Copy link
Contributor Author

hhoppe commented Mar 19, 2021

Also, the return type -> None is shown using the lengthier -> NoneType.

@kernc
Copy link
Member

kernc commented Mar 19, 2021

except that Optional[Type] is replaced by the more confusing Union[Type, NoneType]

I'm afraid that's what the values are resolved as by typing internals:

>>> import typing
>>> def foo() -> typing.Optional[int]: pass
>>> typing.get_type_hints(foo)
{'return': typing.Union[int, NoneType]}

If you can think of a good matching/replacement scheme, this would be the place to override it:

pdoc/pdoc/__init__.py

Lines 1243 to 1258 in aef1917

def _formatannotation(annot):
"""
Format annotation, properly handling NewType types
>>> import typing
>>> _formatannotation(typing.NewType('MyType', str))
'MyType'
"""
module = getattr(annot, '__module__', '')
is_newtype = (getattr(annot, '__qualname__', '').startswith('NewType.') and
module == 'typing')
if is_newtype:
return annot.__name__
if module.startswith('nptyping'): # GH-231
return repr(annot)
return inspect.formatannotation(annot)

@kernc kernc added the enhancement New feature or request label Mar 19, 2021
@hhoppe
Copy link
Contributor Author

hhoppe commented Mar 19, 2021

Thanks for the pointers. Handling the general case looks difficult. It seems that inspect uses repr to create a string from an annotation, which can be arbitrarily nested. One could try to recognize the pattern(s) in the resulting string, but that would require a parser rather than a regular expression.

@kernc kernc closed this as completed in 6bd00e1 Mar 20, 2021
kernc added a commit to kernc/pdoc that referenced this issue Jun 22, 2024
kernc added a commit to johann-petrak/pdoc that referenced this issue Jun 22, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Development

No branches or pull requests

2 participants