From 423e7ab2ca42123584504ef03e0a3c07b9369275 Mon Sep 17 00:00:00 2001 From: Takeshi KOMIYA Date: Mon, 21 Dec 2020 01:43:36 +0900 Subject: [PATCH] Fix #8559: AttributeError is raised when using ForwardRef The restify() helper crashes when ForwardRef is passed. --- CHANGES | 3 +++ sphinx/util/typing.py | 2 ++ tests/test_util_typing.py | 6 ++++++ 3 files changed, 11 insertions(+) diff --git a/CHANGES b/CHANGES index 226f7da6d6..bcf7cf2348 100644 --- a/CHANGES +++ b/CHANGES @@ -16,6 +16,9 @@ Features added Bugs fixed ---------- +* #8559: autodoc: AttributeError is raised when using forward-reference type + annotations + Testing -------- diff --git a/sphinx/util/typing.py b/sphinx/util/typing.py index 222e2edf2b..2d4f67bba2 100644 --- a/sphinx/util/typing.py +++ b/sphinx/util/typing.py @@ -153,6 +153,8 @@ def _restify_py37(cls: Optional["Type"]) -> str: return ':obj:`%s`' % cls._name else: return ':obj:`%s.%s`' % (cls.__module__, cls._name) + elif isinstance(cls, ForwardRef): + return ':class:`%s`' % cls.__forward_arg__ else: # not a class (ex. TypeVar) return ':obj:`%s.%s`' % (cls.__module__, cls.__name__) diff --git a/tests/test_util_typing.py b/tests/test_util_typing.py index 882c652cc6..a2565f1e1f 100644 --- a/tests/test_util_typing.py +++ b/tests/test_util_typing.py @@ -109,6 +109,12 @@ def test_restify_type_hints_alias(): assert restify(MyTuple) == ":class:`Tuple`\\ [:class:`str`, :class:`str`]" # type: ignore +@pytest.mark.skipif(sys.version_info < (3, 7), reason='python 3.7+ is required.') +def test_restify_type_ForwardRef(): + from typing import ForwardRef # type: ignore + assert restify(ForwardRef("myint")) == ":class:`myint`" + + def test_restify_broken_type_hints(): assert restify(BrokenType) == ':class:`tests.test_util_typing.BrokenType`'