Skip to content

Commit

Permalink
Narrow Generator[T, None, None] types to Iterator[T] (#12241)
Browse files Browse the repository at this point in the history
  • Loading branch information
AA-Turner authored Apr 9, 2024
1 parent 413e740 commit 3421e53
Show file tree
Hide file tree
Showing 20 changed files with 61 additions and 54 deletions.
4 changes: 2 additions & 2 deletions sphinx/builders/gettext.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@

if TYPE_CHECKING:
import os
from collections.abc import Generator, Iterable
from collections.abc import Iterable, Iterator

from docutils.nodes import Element

Expand Down Expand Up @@ -69,7 +69,7 @@ def add(self, msg: str, origin: Element | MsgOrigin) -> None:
line = -1
self.metadata[msg].append((origin.source, line, origin.uid)) # type: ignore[arg-type]

def __iter__(self) -> Generator[Message, None, None]:
def __iter__(self) -> Iterator[Message]:
for message in self.messages:
positions = sorted({(source, line) for source, line, uuid
in self.metadata[message]})
Expand Down
4 changes: 2 additions & 2 deletions sphinx/builders/linkcheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
from sphinx.util.nodes import get_node_line

if TYPE_CHECKING:
from collections.abc import Generator, Iterator
from collections.abc import Iterator
from typing import Any, Callable

from requests import Response
Expand Down Expand Up @@ -224,7 +224,7 @@ def __init__(self, config: Config) -> None:
self.to_ignore: list[re.Pattern[str]] = list(map(re.compile,
self.config.linkcheck_ignore))

def check(self, hyperlinks: dict[str, Hyperlink]) -> Generator[CheckResult, None, None]:
def check(self, hyperlinks: dict[str, Hyperlink]) -> Iterator[CheckResult]:
self.invoke_threads()

total_links = 0
Expand Down
4 changes: 2 additions & 2 deletions sphinx/domains/c/_symbol.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from sphinx.util import logging

if TYPE_CHECKING:
from collections.abc import Generator, Iterator
from collections.abc import Iterator

from typing_extensions import Self

Expand Down Expand Up @@ -248,7 +248,7 @@ def _find_named_symbols(self, ident: ASTIdentifier,
Symbol.debug_print("recurseInAnon: ", recurseInAnon)
Symbol.debug_print("searchInSiblings: ", searchInSiblings)

def candidates() -> Generator[Symbol, None, None]:
def candidates() -> Iterator[Symbol]:
s = self
if Symbol.debug_lookup:
Symbol.debug_print("searching in self:")
Expand Down
6 changes: 3 additions & 3 deletions sphinx/domains/cpp/_symbol.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from sphinx.util import logging

if TYPE_CHECKING:
from collections.abc import Generator, Iterator
from collections.abc import Iterator

from sphinx.environment import BuildEnvironment

Expand Down Expand Up @@ -237,7 +237,7 @@ def get_all_symbols(self) -> Iterator[Any]:
yield from sChild.get_all_symbols()

@property
def children_recurse_anon(self) -> Generator[Symbol, None, None]:
def children_recurse_anon(self) -> Iterator[Symbol]:
for c in self._children:
yield c
if not c.identOrOp.is_anon():
Expand Down Expand Up @@ -347,7 +347,7 @@ def matches(s: Symbol) -> bool:
return False
return True

def candidates() -> Generator[Symbol, None, None]:
def candidates() -> Iterator[Symbol]:
s = self
if Symbol.debug_lookup:
Symbol.debug_print("searching in self:")
Expand Down
4 changes: 2 additions & 2 deletions sphinx/environment/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from sphinx.util.osutil import canon_path, os_path

if TYPE_CHECKING:
from collections.abc import Generator, Iterator
from collections.abc import Iterator
from pathlib import Path

from docutils import nodes
Expand Down Expand Up @@ -524,7 +524,7 @@ def get_outdated_files(self, config_changed: bool) -> tuple[set[str], set[str],

return added, changed, removed

def check_dependents(self, app: Sphinx, already: set[str]) -> Generator[str, None, None]:
def check_dependents(self, app: Sphinx, already: set[str]) -> Iterator[str]:
to_rewrite: list[str] = []
for docnames in self.events.emit('env-get-updated', self):
to_rewrite.extend(docnames)
Expand Down
4 changes: 2 additions & 2 deletions sphinx/ext/apidoc.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
from sphinx.util.template import ReSTRenderer

if TYPE_CHECKING:
from collections.abc import Generator, Sequence
from collections.abc import Iterator, Sequence

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -214,7 +214,7 @@ def is_skipped_module(filename: str, opts: Any, _excludes: Sequence[re.Pattern[s


def walk(rootpath: str, excludes: Sequence[re.Pattern[str]], opts: Any,
) -> Generator[tuple[str, list[str], list[str]], None, None]:
) -> Iterator[tuple[str, list[str], list[str]]]:
"""Walk through the directory and list files and subdirectories up."""
followlinks = getattr(opts, 'followlinks', False)
includeprivate = getattr(opts, 'includeprivate', False)
Expand Down
4 changes: 2 additions & 2 deletions sphinx/ext/autodoc/importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
)

if TYPE_CHECKING:
from collections.abc import Callable, Generator, Mapping
from collections.abc import Callable, Iterator, Mapping
from types import ModuleType
from typing import Any

Expand All @@ -38,7 +38,7 @@ def _filter_enum_dict(
enum_class: type[Enum],
attrgetter: Callable[[Any, str, Any], Any],
enum_class_dict: Mapping[str, object],
) -> Generator[tuple[str, type, Any], None, None]:
) -> Iterator[tuple[str, type, Any]]:
"""Find the attributes to document of an enumeration class.
The output consists of triplets ``(attribute name, defining class, value)``
Expand Down
4 changes: 2 additions & 2 deletions sphinx/ext/autodoc/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from sphinx.util.inspect import isboundmethod, safe_getattr

if TYPE_CHECKING:
from collections.abc import Generator, Iterator, Sequence
from collections.abc import Iterator, Sequence

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -137,7 +137,7 @@ def invalidate_caches(self) -> None:


@contextlib.contextmanager
def mock(modnames: list[str]) -> Generator[None, None, None]:
def mock(modnames: list[str]) -> Iterator[None]:
"""Insert mock modules during context::
with mock(['target.module.name']):
Expand Down
4 changes: 2 additions & 2 deletions sphinx/ext/viewcode.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from sphinx.util.nodes import make_refnode

if TYPE_CHECKING:
from collections.abc import Generator, Iterable
from collections.abc import Iterable, Iterator

from sphinx.application import Sphinx
from sphinx.builders import Builder
Expand Down Expand Up @@ -239,7 +239,7 @@ def should_generate_module_page(app: Sphinx, modname: str) -> bool:
return True


def collect_pages(app: Sphinx) -> Generator[tuple[str, dict[str, Any], str], None, None]:
def collect_pages(app: Sphinx) -> Iterator[tuple[str, dict[str, Any], str]]:
env = app.builder.env
if not hasattr(env, '_viewcode_modules'):
return
Expand Down
8 changes: 4 additions & 4 deletions sphinx/testing/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from sphinx.testing.util import SphinxTestApp, SphinxTestAppWrapperForSkipBuilding

if TYPE_CHECKING:
from collections.abc import Callable, Generator
from collections.abc import Callable, Iterator
from pathlib import Path
from typing import Any

Expand Down Expand Up @@ -147,7 +147,7 @@ def app(
app_params: tuple[dict, dict],
make_app: Callable,
shared_result: SharedResult,
) -> Generator[SphinxTestApp, None, None]:
) -> Iterator[SphinxTestApp]:
"""
Provides the 'sphinx.application.Sphinx' object
"""
Expand Down Expand Up @@ -183,7 +183,7 @@ def warning(app: SphinxTestApp) -> StringIO:


@pytest.fixture()
def make_app(test_params: dict, monkeypatch: Any) -> Generator[Callable, None, None]:
def make_app(test_params: dict, monkeypatch: Any) -> Iterator[Callable]:
"""
Provides make_app function to initialize SphinxTestApp instance.
if you want to initialize 'app' in your test function. please use this
Expand Down Expand Up @@ -289,7 +289,7 @@ def sphinx_test_tempdir(tmp_path_factory: Any) -> Path:


@pytest.fixture()
def rollback_sysmodules() -> Generator[None, None, None]: # NoQA: PT004
def rollback_sysmodules() -> Iterator[None]: # NoQA: PT004
"""
Rollback sys.modules to its value before testing to unload modules
during tests.
Expand Down
4 changes: 2 additions & 2 deletions sphinx/transforms/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from sphinx.util.nodes import apply_source_workaround, is_smartquotable

if TYPE_CHECKING:
from collections.abc import Generator
from collections.abc import Iterator

from docutils.nodes import Node, Text

Expand Down Expand Up @@ -376,7 +376,7 @@ def is_available(self) -> bool:
for tag in normalize_language_tag(language)
)

def get_tokens(self, txtnodes: list[Text]) -> Generator[tuple[str, str], None, None]:
def get_tokens(self, txtnodes: list[Text]) -> Iterator[tuple[str, str]]:
# A generator that yields ``(texttype, nodetext)`` tuples for a list
# of "Text" nodes (interface to ``smartquotes.educate_tokens()``).
for txtnode in txtnodes:
Expand Down
16 changes: 8 additions & 8 deletions sphinx/util/docutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
report_re = re.compile('^(.+?:(?:\\d+)?): \\((DEBUG|INFO|WARNING|ERROR|SEVERE)/(\\d+)?\\) ')

if TYPE_CHECKING:
from collections.abc import Generator
from collections.abc import Iterator
from types import ModuleType

from docutils.frontend import Values
Expand All @@ -43,7 +43,7 @@


@contextmanager
def docutils_namespace() -> Generator[None, None, None]:
def docutils_namespace() -> Iterator[None]:
"""Create namespace for reST parsers."""
try:
_directives = copy(directives._directives) # type: ignore[attr-defined]
Expand Down Expand Up @@ -121,7 +121,7 @@ def unregister_node(node: type[Element]) -> None:


@contextmanager
def patched_get_language() -> Generator[None, None, None]:
def patched_get_language() -> Iterator[None]:
"""Patch docutils.languages.get_language() temporarily.
This ignores the second argument ``reporter`` to suppress warnings.
Expand All @@ -141,7 +141,7 @@ def patched_get_language(language_code: str, reporter: Reporter | None = None) -


@contextmanager
def patched_rst_get_language() -> Generator[None, None, None]:
def patched_rst_get_language() -> Iterator[None]:
"""Patch docutils.parsers.rst.languages.get_language().
Starting from docutils 0.17, get_language() in ``rst.languages``
also has a reporter, which needs to be disabled temporarily.
Expand All @@ -165,7 +165,7 @@ def patched_get_language(language_code: str, reporter: Reporter | None = None) -


@contextmanager
def using_user_docutils_conf(confdir: str | None) -> Generator[None, None, None]:
def using_user_docutils_conf(confdir: str | None) -> Iterator[None]:
"""Let docutils know the location of ``docutils.conf`` for Sphinx."""
try:
docutilsconfig = os.environ.get('DOCUTILSCONFIG', None)
Expand All @@ -181,7 +181,7 @@ def using_user_docutils_conf(confdir: str | None) -> Generator[None, None, None]


@contextmanager
def du19_footnotes() -> Generator[None, None, None]:
def du19_footnotes() -> Iterator[None]:
def visit_footnote(self: HTMLTranslator, node: Element) -> None:
label_style = self.settings.footnote_references
if not isinstance(node.previous_sibling(), type(node)):
Expand Down Expand Up @@ -214,7 +214,7 @@ def depart_footnote(self: HTMLTranslator, node: Element) -> None:


@contextmanager
def patch_docutils(confdir: str | None = None) -> Generator[None, None, None]:
def patch_docutils(confdir: str | None = None) -> Iterator[None]:
"""Patch to docutils temporarily."""
with patched_get_language(), \
patched_rst_get_language(), \
Expand Down Expand Up @@ -359,7 +359,7 @@ def __init__(self) -> None:


@contextmanager
def switch_source_input(state: State, content: StringList) -> Generator[None, None, None]:
def switch_source_input(state: State, content: StringList) -> Iterator[None]:
"""Switch current source input of state temporarily."""
try:
# remember the original ``get_source_and_line()`` method
Expand Down
8 changes: 4 additions & 4 deletions sphinx/util/i18n.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

if TYPE_CHECKING:
import datetime as dt
from collections.abc import Generator
from collections.abc import Iterator
from typing import Protocol, Union

from babel.core import Locale
Expand Down Expand Up @@ -112,7 +112,7 @@ def __init__(self, basedir: str | os.PathLike[str], locale_dirs: list[str],
self.encoding = encoding

@property
def locale_dirs(self) -> Generator[str, None, None]:
def locale_dirs(self) -> Iterator[str]:
if not self.language:
return

Expand All @@ -125,7 +125,7 @@ def locale_dirs(self) -> Generator[str, None, None]:
logger.verbose(__('locale_dir %s does not exist'), locale_path)

@property
def pofiles(self) -> Generator[tuple[str, str], None, None]:
def pofiles(self) -> Iterator[tuple[str, str]]:
for locale_dir in self.locale_dirs:
basedir = path.join(locale_dir, self.language, 'LC_MESSAGES')
for root, dirnames, filenames in os.walk(basedir):
Expand All @@ -139,7 +139,7 @@ def pofiles(self) -> Generator[tuple[str, str], None, None]:
yield basedir, relpath(fullpath, basedir)

@property
def catalogs(self) -> Generator[CatalogInfo, None, None]:
def catalogs(self) -> Iterator[CatalogInfo]:
for basedir, filename in self.pofiles:
domain = canon_path(path.splitext(filename)[0])
yield CatalogInfo(basedir, domain, self.encoding)
Expand Down
14 changes: 7 additions & 7 deletions sphinx/util/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from sphinx.util.osutil import abspath

if TYPE_CHECKING:
from collections.abc import Generator
from collections.abc import Iterator

from docutils.nodes import Node

Expand Down Expand Up @@ -246,7 +246,7 @@ def clear(self) -> list[logging.LogRecord]:


@contextmanager
def pending_warnings() -> Generator[logging.Handler, None, None]:
def pending_warnings() -> Iterator[logging.Handler]:
"""Context manager to postpone logging warnings temporarily.
Similar to :func:`pending_logging`.
Expand Down Expand Up @@ -274,7 +274,7 @@ def pending_warnings() -> Generator[logging.Handler, None, None]:


@contextmanager
def suppress_logging() -> Generator[MemoryHandler, None, None]:
def suppress_logging() -> Iterator[MemoryHandler]:
"""Context manager to suppress logging all logs temporarily.
For example::
Expand Down Expand Up @@ -303,7 +303,7 @@ def suppress_logging() -> Generator[MemoryHandler, None, None]:


@contextmanager
def pending_logging() -> Generator[MemoryHandler, None, None]:
def pending_logging() -> Iterator[MemoryHandler]:
"""Context manager to postpone logging all logs temporarily.
For example::
Expand All @@ -323,7 +323,7 @@ def pending_logging() -> Generator[MemoryHandler, None, None]:


@contextmanager
def skip_warningiserror(skip: bool = True) -> Generator[None, None, None]:
def skip_warningiserror(skip: bool = True) -> Iterator[None]:
"""Context manager to skip WarningIsErrorFilter temporarily."""
logger = logging.getLogger(NAMESPACE)

Expand All @@ -343,7 +343,7 @@ def skip_warningiserror(skip: bool = True) -> Generator[None, None, None]:


@contextmanager
def prefixed_warnings(prefix: str) -> Generator[None, None, None]:
def prefixed_warnings(prefix: str) -> Iterator[None]:
"""Context manager to prepend prefix to all warning log records temporarily.
For example::
Expand Down Expand Up @@ -393,7 +393,7 @@ def __init__(self) -> None:
self.logs: list[logging.LogRecord] = []

@contextmanager
def collect(self) -> Generator[None, None, None]:
def collect(self) -> Iterator[None]:
with pending_logging() as memhandler:
yield

Expand Down
Loading

0 comments on commit 3421e53

Please sign in to comment.