From 4d5867d5a235040b3e7d3373a56c5b2b580db7b7 Mon Sep 17 00:00:00 2001 From: Bryan Forbes Date: Tue, 12 Apr 2022 04:45:37 -0500 Subject: [PATCH] Handle UnionType (#221) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Bernát Gábor --- CHANGELOG.md | 1 + src/sphinx_autodoc_typehints/__init__.py | 2 ++ tests/roots/test-dummy/dummy_module_future_annotations.py | 4 +++- tests/test_sphinx_autodoc_typehints.py | 6 ++++-- 4 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6240a3ba..33bddefe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## 1.18.0 - Support and require `nptyping>=2` +- Handle `UnionType` ## 1.17.1 diff --git a/src/sphinx_autodoc_typehints/__init__.py b/src/sphinx_autodoc_typehints/__init__.py index 9ec89cf1..cde07203 100644 --- a/src/sphinx_autodoc_typehints/__init__.py +++ b/src/sphinx_autodoc_typehints/__init__.py @@ -175,6 +175,8 @@ def format_annotation(annotation: Any, config: Config) -> str: # noqa: C901 # t formatted_args = f"\\[\\[{', '.join(fmt[:-1])}], {fmt[-1]}]" elif full_name == "typing.Literal": formatted_args = f"\\[{', '.join(repr(arg) for arg in args)}]" + elif full_name == "types.UnionType": + return " | ".join([format_annotation(arg, config) for arg in args]) if args and not formatted_args: try: diff --git a/tests/roots/test-dummy/dummy_module_future_annotations.py b/tests/roots/test-dummy/dummy_module_future_annotations.py index a84934d0..5cc16cb1 100644 --- a/tests/roots/test-dummy/dummy_module_future_annotations.py +++ b/tests/roots/test-dummy/dummy_module_future_annotations.py @@ -1,7 +1,9 @@ from __future__ import annotations -def function_with_py310_annotations(self, x: bool, y: int, z: str | None = None) -> str: # noqa: U100 +def function_with_py310_annotations( + self, x: bool | None, y: int | str | float, z: str | None = None # noqa: U100 +) -> str: """ Method docstring. diff --git a/tests/test_sphinx_autodoc_typehints.py b/tests/test_sphinx_autodoc_typehints.py index b87f73ad..b5f0a009 100644 --- a/tests/test_sphinx_autodoc_typehints.py +++ b/tests/test_sphinx_autodoc_typehints.py @@ -370,6 +370,8 @@ def set_python_path() -> None: def maybe_fix_py310(expected_contents: str) -> str: if PY310_PLUS: for old, new in [ + ("*bool** | **None*", '"bool" | "None"'), + ("*int** | **str** | **float*", '"int" | "str" | "float"'), ("*str** | **None*", '"Optional"["str"]'), ("(*bool*)", '("bool")'), ("(*int*", '("int"'), @@ -704,9 +706,9 @@ def test_sphinx_output_future_annotations(app: SphinxTestApp, status: StringIO) Method docstring. Parameters: - * **x** (*bool*) -- foo + * **x** (*bool** | **None*) -- foo - * **y** (*int*) -- bar + * **y** (*int** | **str** | **float*) -- bar * **z** (*str** | **None*) -- baz