From 7ca52480570300dd7f147bbe12b08f3f917223ba Mon Sep 17 00:00:00 2001 From: Takeshi KOMIYA Date: Sun, 31 Jan 2021 23:37:58 +0900 Subject: [PATCH] Fix #8775: Avoid the crash of autodoc caused by type union operator The type union operator (PEP-604) causes autodoc crashed in python 3.9 or below because of the syntax is not suppoerted yet in the interpreters. Internally, `typing.get_type_hints()` raises TypeError on evaluating the annotation by BitOr operator for types. To avoid the crash, this adds a fallback not to evaluate the annotations and keep as is. As a side effect, `autodoc_type_aliases` will not work for the modules and classes that uses type union operator for their annotations. --- sphinx/util/typing.py | 4 +++- tests/test_ext_autodoc.py | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/sphinx/util/typing.py b/sphinx/util/typing.py index 5cee1834a..db754bb03 100644 --- a/sphinx/util/typing.py +++ b/sphinx/util/typing.py @@ -77,7 +77,9 @@ def get_type_hints(obj: Any, globalns: Dict = None, localns: Dict = None) -> Dic # Failed to evaluate ForwardRef (maybe TYPE_CHECKING) return safe_getattr(obj, '__annotations__', {}) except TypeError: - return {} + # Invalid object is given. But try to get __annotations__ as a fallback for + # the code using type union operator (PEP 604) in python 3.9 or below. + return safe_getattr(obj, '__annotations__', {}) except KeyError: # a broken class found (refs: https://github.com/sphinx-doc/sphinx/issues/8084) return {} diff --git a/tests/test_ext_autodoc.py b/tests/test_ext_autodoc.py index b95441703..93b80f7ad 100644 --- a/tests/test_ext_autodoc.py +++ b/tests/test_ext_autodoc.py @@ -2237,7 +2237,7 @@ def test_name_mangling(app): ] -@pytest.mark.skipif(sys.version_info < (3, 10), reason='python 3.10+ is required.') +@pytest.mark.skipif(sys.version_info < (3, 7), reason='python 3.7+ is required.') @pytest.mark.sphinx('html', testroot='ext-autodoc') def test_type_union_operator(app): options = {'members': None}