summaryrefslogtreecommitdiff
path: root/sphinx/ext/autodoc
diff options
context:
space:
mode:
Diffstat (limited to 'sphinx/ext/autodoc')
-rw-r--r--sphinx/ext/autodoc/__init__.py57
-rw-r--r--sphinx/ext/autodoc/directive.py23
-rw-r--r--sphinx/ext/autodoc/importer.py30
-rw-r--r--sphinx/ext/autodoc/mock.py6
4 files changed, 27 insertions, 89 deletions
diff --git a/sphinx/ext/autodoc/__init__.py b/sphinx/ext/autodoc/__init__.py
index 6eff27102..983c43b24 100644
--- a/sphinx/ext/autodoc/__init__.py
+++ b/sphinx/ext/autodoc/__init__.py
@@ -18,14 +18,14 @@ from types import ModuleType
from typing import (
Any, Callable, Dict, Iterator, List, Optional, Sequence, Set, Tuple, Type, TypeVar, Union
)
-from typing import get_type_hints
+from typing import TYPE_CHECKING, get_type_hints
from docutils.statemachine import StringList
import sphinx
from sphinx.application import Sphinx
from sphinx.config import Config, ENUM
-from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning
+from sphinx.deprecation import RemovedInSphinx50Warning
from sphinx.environment import BuildEnvironment
from sphinx.ext.autodoc.importer import import_object, get_module_members, get_object_members
from sphinx.ext.autodoc.mock import mock
@@ -39,9 +39,7 @@ from sphinx.util.inspect import (
)
from sphinx.util.typing import stringify as stringify_typehint
-if False:
- # For type annotation
- from typing import Type # NOQA # for python3.5.1
+if TYPE_CHECKING:
from sphinx.ext.autodoc.directive import DocumenterBridge
@@ -322,7 +320,7 @@ class Documenter:
self.analyzer = None # type: ModuleAnalyzer
@property
- def documenters(self) -> Dict[str, "Type[Documenter]"]:
+ def documenters(self) -> Dict[str, Type["Documenter"]]:
"""Returns registered Documenter classes"""
return self.env.app.registry.documenters
@@ -509,12 +507,8 @@ class Documenter:
# etc. don't support a prepended module name
self.add_line(' :module: %s' % self.modname, sourcename)
- def get_doc(self, encoding: str = None, ignore: int = None) -> List[List[str]]:
+ def get_doc(self, ignore: int = None) -> List[List[str]]:
"""Decode and return lines of the docstring(s) for the object."""
- if encoding is not None:
- warnings.warn("The 'encoding' argument to autodoc.%s.get_doc() is deprecated."
- % self.__class__.__name__,
- RemovedInSphinx40Warning, stacklevel=2)
if ignore is not None:
warnings.warn("The 'ignore' argument to autodoc.%s.get_doc() is deprecated."
% self.__class__.__name__,
@@ -842,7 +836,7 @@ class Documenter:
# This is used for situations where you have a module that collects the
# functions and classes of internal submodules.
guess_modname = self.get_real_modname()
- self.real_modname = real_modname or guess_modname
+ self.real_modname = real_modname or guess_modname # type: str
# try to also get a source code analyzer for attribute docs
try:
@@ -1015,7 +1009,7 @@ class ModuleDocumenter(Documenter):
# Sort by __all__
def keyfunc(entry: Tuple[Documenter, bool]) -> int:
name = entry[0].name.split('::')[1]
- if name in self.__all__:
+ if self.__all__ and name in self.__all__:
return self.__all__.index(name)
else:
return len(self.__all__)
@@ -1088,12 +1082,7 @@ class DocstringSignatureMixin:
_new_docstrings = None # type: List[List[str]]
_signatures = None # type: List[str]
- def _find_signature(self, encoding: str = None) -> Tuple[str, str]:
- if encoding is not None:
- warnings.warn("The 'encoding' argument to autodoc.%s._find_signature() is "
- "deprecated." % self.__class__.__name__,
- RemovedInSphinx40Warning, stacklevel=2)
-
+ def _find_signature(self) -> Tuple[str, str]:
# candidates of the object name
valid_names = [self.objpath[-1]] # type: ignore
if isinstance(self, ClassDocumenter):
@@ -1152,14 +1141,10 @@ class DocstringSignatureMixin:
return result
- def get_doc(self, encoding: str = None, ignore: int = None) -> List[List[str]]:
- if encoding is not None:
- warnings.warn("The 'encoding' argument to autodoc.%s.get_doc() is deprecated."
- % self.__class__.__name__,
- RemovedInSphinx40Warning, stacklevel=2)
+ def get_doc(self, ignore: int = None) -> List[List[str]]:
if self._new_docstrings is not None:
return self._new_docstrings
- return super().get_doc(None, ignore) # type: ignore
+ return super().get_doc(ignore) # type: ignore
def format_signature(self, **kwargs: Any) -> str:
if self.args is None and self.env.config.autodoc_docstring_signature: # type: ignore
@@ -1522,11 +1507,7 @@ class ClassDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # type:
self.add_line(' ' + _('Bases: %s') % ', '.join(bases),
sourcename)
- def get_doc(self, encoding: str = None, ignore: int = None) -> List[List[str]]:
- if encoding is not None:
- warnings.warn("The 'encoding' argument to autodoc.%s.get_doc() is deprecated."
- % self.__class__.__name__,
- RemovedInSphinx40Warning, stacklevel=2)
+ def get_doc(self, ignore: int = None) -> List[List[str]]:
lines = getattr(self, '_new_docstrings', None)
if lines is not None:
return lines
@@ -1648,9 +1629,6 @@ class DataDocumenter(ModuleLevelDocumenter):
except KeyError:
# a broken class found (refs: https://github.com/sphinx-doc/sphinx/issues/8084)
annotations = {}
- except AttributeError:
- # AttributeError is raised on 3.5.2 (fixed by 3.5.3)
- annotations = {}
if self.objpath[-1] in annotations:
objrepr = stringify_typehint(annotations.get(self.objpath[-1]))
@@ -1763,7 +1741,7 @@ class TypeVarDocumenter(DataDocumenter):
self.options.annotation = SUPPRESS # type: ignore
super().add_directive_header(sig)
- def get_doc(self, encoding: str = None, ignore: int = None) -> List[List[str]]:
+ def get_doc(self, ignore: int = None) -> List[List[str]]:
if ignore is not None:
warnings.warn("The 'ignore' argument to autodoc.%s.get_doc() is deprecated."
% self.__class__.__name__,
@@ -2036,9 +2014,6 @@ class AttributeDocumenter(DocstringStripSignatureMixin, ClassLevelDocumenter):
except KeyError:
# a broken class found (refs: https://github.com/sphinx-doc/sphinx/issues/8084)
annotations = {}
- except AttributeError:
- # AttributeError is raised on 3.5.2 (fixed by 3.5.3)
- annotations = {}
if self.objpath[-1] in annotations:
objrepr = stringify_typehint(annotations.get(self.objpath[-1]))
@@ -2064,14 +2039,14 @@ class AttributeDocumenter(DocstringStripSignatureMixin, ClassLevelDocumenter):
else:
self.add_line(' :annotation: %s' % self.options.annotation, sourcename)
- def get_doc(self, encoding: str = None, ignore: int = None) -> List[List[str]]:
+ def get_doc(self, ignore: int = None) -> List[List[str]]:
try:
# Disable `autodoc_inherit_docstring` temporarily to avoid to obtain
# a docstring from the value which descriptor returns unexpectedly.
# ref: https://github.com/sphinx-doc/sphinx/issues/7805
orig = self.env.config.autodoc_inherit_docstrings
self.env.config.autodoc_inherit_docstrings = False # type: ignore
- return super().get_doc(encoding, ignore)
+ return super().get_doc(ignore)
finally:
self.env.config.autodoc_inherit_docstrings = orig # type: ignore
@@ -2197,7 +2172,7 @@ class SlotsAttributeDocumenter(AttributeDocumenter):
self.env.note_reread()
return False
- def get_doc(self, encoding: str = None, ignore: int = None) -> List[List[str]]:
+ def get_doc(self, ignore: int = None) -> List[List[str]]:
"""Decode and return lines of the docstring(s) for the object."""
if ignore is not None:
warnings.warn("The 'ignore' argument to autodoc.%s.get_doc() is deprecated."
@@ -2212,7 +2187,7 @@ class SlotsAttributeDocumenter(AttributeDocumenter):
return []
-def get_documenters(app: Sphinx) -> Dict[str, "Type[Documenter]"]:
+def get_documenters(app: Sphinx) -> Dict[str, Type[Documenter]]:
"""Returns registered Documenter classes"""
warnings.warn("get_documenters() is deprecated.", RemovedInSphinx50Warning, stacklevel=2)
return app.registry.documenters
diff --git a/sphinx/ext/autodoc/directive.py b/sphinx/ext/autodoc/directive.py
index 9a3428f5d..5543059cb 100644
--- a/sphinx/ext/autodoc/directive.py
+++ b/sphinx/ext/autodoc/directive.py
@@ -6,27 +6,21 @@
:license: BSD, see LICENSE for details.
"""
-import warnings
-from typing import Any, Callable, Dict, List, Set
+from typing import Any, Callable, Dict, List, Set, Type
from docutils import nodes
from docutils.nodes import Element, Node
-from docutils.parsers.rst.states import RSTState, Struct
+from docutils.parsers.rst.states import RSTState
from docutils.statemachine import StringList
from docutils.utils import Reporter, assemble_option_dict
from sphinx.config import Config
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.environment import BuildEnvironment
from sphinx.ext.autodoc import Documenter, Options
from sphinx.util import logging
from sphinx.util.docutils import SphinxDirective, switch_source_input
from sphinx.util.nodes import nested_parse_with_titles
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
logger = logging.getLogger(__name__)
@@ -53,23 +47,14 @@ class DocumenterBridge:
"""A parameters container for Documenters."""
def __init__(self, env: BuildEnvironment, reporter: Reporter, options: Options,
- lineno: int, state: Any = None) -> None:
+ lineno: int, state: Any) -> None:
self.env = env
self.reporter = reporter
self.genopt = options
self.lineno = lineno
self.filename_set = set() # type: Set[str]
self.result = StringList()
-
- if state:
- self.state = state
- else:
- # create fake object for self.state.document.settings.tab_width
- warnings.warn('DocumenterBridge requires a state object on instantiation.',
- RemovedInSphinx40Warning, stacklevel=2)
- settings = Struct(tab_width=8)
- document = Struct(settings=settings)
- self.state = Struct(document=document)
+ self.state = state
def warn(self, msg: str) -> None:
logger.warning(msg, location=(self.env.docname, self.lineno))
diff --git a/sphinx/ext/autodoc/importer.py b/sphinx/ext/autodoc/importer.py
index 133ce1439..132eb81ba 100644
--- a/sphinx/ext/autodoc/importer.py
+++ b/sphinx/ext/autodoc/importer.py
@@ -13,7 +13,6 @@ import traceback
import warnings
from typing import Any, Callable, Dict, List, Mapping, NamedTuple, Optional, Tuple
-from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias
from sphinx.pycode import ModuleAnalyzer
from sphinx.util import logging
from sphinx.util.inspect import isclass, isenumclass, safe_getattr
@@ -157,9 +156,10 @@ def get_module_members(module: Any) -> List[Tuple[str, Any]]:
return sorted(list(members.values()))
-Attribute = NamedTuple('Attribute', [('name', str),
- ('directly_defined', bool),
- ('value', Any)])
+class Attribute(NamedTuple):
+ name: str
+ directly_defined: bool
+ value: Any
def _getmro(obj: Any) -> Tuple["Type", ...]:
@@ -235,25 +235,3 @@ def get_object_members(subject: Any, objpath: List[str], attrgetter: Callable,
members[name] = Attribute(name, True, INSTANCEATTR)
return members
-
-
-from sphinx.ext.autodoc.mock import ( # NOQA
- _MockModule, _MockObject, MockFinder, MockLoader, mock
-)
-
-deprecated_alias('sphinx.ext.autodoc.importer',
- {
- '_MockModule': _MockModule,
- '_MockObject': _MockObject,
- 'MockFinder': MockFinder,
- 'MockLoader': MockLoader,
- 'mock': mock,
- },
- RemovedInSphinx40Warning,
- {
- '_MockModule': 'sphinx.ext.autodoc.mock._MockModule',
- '_MockObject': 'sphinx.ext.autodoc.mock._MockObject',
- 'MockFinder': 'sphinx.ext.autodoc.mock.MockFinder',
- 'MockLoader': 'sphinx.ext.autodoc.mock.MockLoader',
- 'mock': 'sphinx.ext.autodoc.mock.mock',
- })
diff --git a/sphinx/ext/autodoc/mock.py b/sphinx/ext/autodoc/mock.py
index 40258a135..bf4ac2979 100644
--- a/sphinx/ext/autodoc/mock.py
+++ b/sphinx/ext/autodoc/mock.py
@@ -14,7 +14,7 @@ import sys
from importlib.abc import Loader, MetaPathFinder
from importlib.machinery import ModuleSpec
from types import FunctionType, MethodType, ModuleType
-from typing import Any, Generator, Iterator, List, Sequence, Tuple, Union
+from typing import Any, Generator, Iterator, List, Optional, Sequence, Tuple, Union
from sphinx.util import logging
@@ -117,8 +117,8 @@ class MockFinder(MetaPathFinder):
self.loader = MockLoader(self)
self.mocked_modules = [] # type: List[str]
- def find_spec(self, fullname: str, path: Sequence[Union[bytes, str]],
- target: ModuleType = None) -> ModuleSpec:
+ def find_spec(self, fullname: str, path: Optional[Sequence[Union[bytes, str]]],
+ target: ModuleType = None) -> Optional[ModuleSpec]:
for modname in self.modnames:
# check if fullname is (or is a descendant of) one of our targets
if modname == fullname or fullname.startswith(modname + '.'):