From f1a051fdfc72a882012f399f99b65bbe7729cb1f Mon Sep 17 00:00:00 2001 From: Takeshi KOMIYA Date: Thu, 31 Dec 2020 14:10:55 +0900 Subject: [PATCH] Fix #8315: autodoc: Failed to resolve struct.Struct type annotation The builtin module, ``struct.Struct`` does not have correct module name since Python 3.8. This allows to refer it automatically. --- CHANGES | 1 + sphinx/util/typing.py | 7 +++++++ tests/test_util_typing.py | 3 +++ 3 files changed, 11 insertions(+) diff --git a/CHANGES b/CHANGES index 3a9f527ad..d013c82e2 100644 --- a/CHANGES +++ b/CHANGES @@ -28,6 +28,7 @@ Bugs fixed class * #8592: autodoc: ``:meta public:`` does not effect to variables * #8594: autodoc: empty __all__ attribute is ignored +* #8315: autodoc: Failed to resolve struct.Struct type annotation * #8306: autosummary: mocked modules are documented as empty page when using :recursive: option * #8094: texinfo: image files on the different directory with document are not diff --git a/sphinx/util/typing.py b/sphinx/util/typing.py index 2d4f67bba..f9807ae09 100644 --- a/sphinx/util/typing.py +++ b/sphinx/util/typing.py @@ -10,6 +10,7 @@ import sys import typing +from struct import Struct from typing import Any, Callable, Dict, Generator, List, Optional, Tuple, TypeVar, Union from docutils import nodes @@ -94,6 +95,9 @@ def restify(cls: Optional["Type"]) -> str: return ':obj:`None`' elif cls is Ellipsis: return '...' + elif cls is Struct: + # Before Python 3.9, struct.Struct class has incorrect __module__. + return ':class:`struct.Struct`' elif inspect.isNewType(cls): return ':class:`%s`' % cls.__name__ elif cls.__module__ in ('__builtin__', 'builtins'): @@ -305,6 +309,9 @@ def stringify(annotation: Any) -> str: return annotation.__qualname__ elif annotation is Ellipsis: return '...' + elif annotation is Struct: + # Before Python 3.9, struct.Struct class has incorrect __module__. + return 'struct.Struct' if sys.version_info >= (3, 7): # py37+ return _stringify_py37(annotation) diff --git a/tests/test_util_typing.py b/tests/test_util_typing.py index a2565f1e1..d167d3bb0 100644 --- a/tests/test_util_typing.py +++ b/tests/test_util_typing.py @@ -10,6 +10,7 @@ import sys from numbers import Integral +from struct import Struct from typing import (Any, Callable, Dict, Generator, List, NewType, Optional, Tuple, TypeVar, Union) @@ -43,6 +44,7 @@ def test_restify(): assert restify(str) == ":class:`str`" assert restify(None) == ":obj:`None`" assert restify(Integral) == ":class:`numbers.Integral`" + assert restify(Struct) == ":class:`struct.Struct`" assert restify(Any) == ":obj:`Any`" @@ -124,6 +126,7 @@ def test_stringify(): assert stringify(str) == "str" assert stringify(None) == "None" assert stringify(Integral) == "numbers.Integral" + assert restify(Struct) == ":class:`struct.Struct`" assert stringify(Any) == "Any"