Skip to content

Commit

Permalink
Use PEP 604 types
Browse files Browse the repository at this point in the history
  • Loading branch information
AA-Turner committed Jul 22, 2024
1 parent 4651d7a commit 28d4fdd
Show file tree
Hide file tree
Showing 36 changed files with 88 additions and 105 deletions.
4 changes: 2 additions & 2 deletions .ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -419,8 +419,8 @@ select = [
]

# these tests need old ``typing`` generic aliases
"tests/test_util/test_util_typing.py" = ["UP006", "UP035"]
"tests/test_util/typing_test_data.py" = ["FA100", "UP006", "UP035"]
"tests/test_util/test_util_typing.py" = ["UP006", "UP007", "UP035"]
"tests/test_util/typing_test_data.py" = ["FA100", "UP006", "UP007", "UP035"]

"utils/*" = [
"T201", # whitelist ``print`` for stdout messages
Expand Down
4 changes: 2 additions & 2 deletions sphinx/builders/html/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,9 @@ def _stable_hash(obj: Any) -> str:
"""
if isinstance(obj, dict):
obj = sorted(map(_stable_hash, obj.items()))
if isinstance(obj, (list, tuple, set, frozenset)):
if isinstance(obj, list | tuple | set | frozenset):
obj = sorted(map(_stable_hash, obj))
elif isinstance(obj, (type, types.FunctionType)):
elif isinstance(obj, type | types.FunctionType):
# The default repr() of functions includes the ID, which is not ideal.
# We use the fully qualified name instead.
obj = f'{obj.__module__}.{obj.__qualname__}'
Expand Down
2 changes: 1 addition & 1 deletion sphinx/builders/latex/transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,7 @@ def depart_caption(self, node: nodes.caption) -> None:
self.unrestrict(node)

def visit_title(self, node: nodes.title) -> None:
if isinstance(node.parent, (nodes.section, nodes.table)):
if isinstance(node.parent, nodes.section | nodes.table):
self.restrict(node)

def depart_title(self, node: nodes.title) -> None:
Expand Down
12 changes: 6 additions & 6 deletions sphinx/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import types
import warnings
from os import getenv, path
from typing import TYPE_CHECKING, Any, Literal, NamedTuple, Union
from typing import TYPE_CHECKING, Any, Literal, NamedTuple

from sphinx.deprecation import RemovedInSphinx90Warning
from sphinx.errors import ConfigError, ExtensionError
Expand Down Expand Up @@ -66,7 +66,7 @@ def is_serializable(obj: object, *, _seen: frozenset[int] = frozenset()) -> bool
is_serializable(key, _seen=seen) and is_serializable(value, _seen=seen)
for key, value in obj.items()
)
elif isinstance(obj, (list, tuple, set, frozenset)):
elif isinstance(obj, list | tuple | set | frozenset):
seen = _seen | {id(obj)}
return all(is_serializable(item, _seen=seen) for item in obj)

Expand All @@ -87,13 +87,13 @@ def __init__(self, *candidates: str | bool | None) -> None:
self.candidates = candidates

def match(self, value: str | list | tuple) -> bool:
if isinstance(value, (list, tuple)):
if isinstance(value, list | tuple):
return all(item in self.candidates for item in value)
else:
return value in self.candidates


_OptValidTypes = Union[tuple[()], tuple[type, ...], frozenset[type], ENUM]
_OptValidTypes = tuple[()] | tuple[type, ...] | frozenset[type] | ENUM


class _Opt:
Expand Down Expand Up @@ -549,7 +549,7 @@ def _validate_valid_types(
) -> tuple[()] | tuple[type, ...] | frozenset[type] | ENUM:
if not valid_types:
return ()
if isinstance(valid_types, (frozenset, ENUM)):
if isinstance(valid_types, frozenset | ENUM):
return valid_types
if isinstance(valid_types, type):
return frozenset((valid_types,))
Expand Down Expand Up @@ -584,7 +584,7 @@ def convert_source_suffix(app: Sphinx, config: Config) -> None:
config.source_suffix = {source_suffix: 'restructuredtext'}
logger.info(__("Converting `source_suffix = %r` to `source_suffix = %r`."),
source_suffix, config.source_suffix)
elif isinstance(source_suffix, (list, tuple)):
elif isinstance(source_suffix, list | tuple):
# if list, considers as all of them are default filetype
config.source_suffix = dict.fromkeys(source_suffix, 'restructuredtext')
logger.info(__("Converting `source_suffix = %r` to `source_suffix = %r`."),
Expand Down
4 changes: 2 additions & 2 deletions sphinx/domains/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import copy
from abc import ABC, abstractmethod
from collections.abc import Callable
from typing import TYPE_CHECKING, Any, NamedTuple, Optional, cast
from typing import TYPE_CHECKING, Any, NamedTuple, cast

from docutils.nodes import Element, Node, system_message

Expand Down Expand Up @@ -154,7 +154,7 @@ def generate(self, docnames: Iterable[str] | None = None,
raise NotImplementedError


TitleGetter = Callable[[Node], Optional[str]]
TitleGetter = Callable[[Node], str | None]


class Domain:
Expand Down
3 changes: 1 addition & 2 deletions sphinx/domains/c/_ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,12 @@
)

if TYPE_CHECKING:

from docutils.nodes import Element, Node, TextElement

from sphinx.domains.c._symbol import Symbol
from sphinx.environment import BuildEnvironment

DeclarationType = Union[
DeclarationType = Union[ # NoQA: UP007
"ASTStruct", "ASTUnion", "ASTEnum", "ASTEnumerator",
"ASTType", "ASTTypeWithInit", "ASTMacro",
]
Expand Down
3 changes: 2 additions & 1 deletion sphinx/domains/c/_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@
ASTTypeWithInit,
ASTUnaryOpExpr,
ASTUnion,
DeclarationType,
)
from sphinx.domains.c._ids import (
_expression_assignment_ops,
Expand Down Expand Up @@ -82,6 +81,8 @@
if TYPE_CHECKING:
from collections.abc import Callable, Sequence

from sphinx.domains.c._ast import DeclarationType


class DefinitionParser(BaseParser):
@property
Expand Down
1 change: 0 additions & 1 deletion sphinx/domains/cpp/_ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
)

if TYPE_CHECKING:

from docutils.nodes import Element, TextElement

from sphinx.addnodes import desc_signature
Expand Down
2 changes: 1 addition & 1 deletion sphinx/domains/math.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def get_equation_number_for(self, labelid: str) -> int | None:
def process_doc(self, env: BuildEnvironment, docname: str,
document: nodes.document) -> None:
def math_node(node: Node) -> bool:
return isinstance(node, (nodes.math, nodes.math_block))
return isinstance(node, nodes.math | nodes.math_block)

self.data['has_equations'][docname] = any(document.findall(math_node))

Expand Down
1 change: 0 additions & 1 deletion sphinx/domains/python/_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
)

if TYPE_CHECKING:

from docutils.nodes import Node
from docutils.parsers.rst.states import Inliner

Expand Down
9 changes: 4 additions & 5 deletions sphinx/domains/std/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -814,13 +814,12 @@ def process_doc(
if not sectname:
continue
else:
if (isinstance(node, (nodes.definition_list,
nodes.field_list)) and
if (isinstance(node, nodes.definition_list | nodes.field_list) and
node.children):
node = cast(nodes.Element, node.children[0])
if isinstance(node, (nodes.field, nodes.definition_list_item)):
if isinstance(node, nodes.field | nodes.definition_list_item):
node = cast(nodes.Element, node.children[0])
if isinstance(node, (nodes.term, nodes.field_name)):
if isinstance(node, nodes.term | nodes.field_name):
sectname = clean_astext(node)
else:
toctree = next(node.findall(addnodes.toctree), None)
Expand Down Expand Up @@ -1114,7 +1113,7 @@ def get_numfig_title(self, node: Node) -> str | None:
return title_getter(elem)
else:
for subnode in elem:
if isinstance(subnode, (nodes.caption, nodes.title)):
if isinstance(subnode, nodes.caption | nodes.title):
return clean_astext(subnode)

return None
Expand Down
6 changes: 3 additions & 3 deletions sphinx/environment/adapters/indexentries.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@
from sphinx.util.index_entries import _split_into

if TYPE_CHECKING:
from typing import Literal, Optional, TypeAlias, Union
from typing import Literal, TypeAlias

from sphinx.builders import Builder
from sphinx.environment import BuildEnvironment

_IndexEntryTarget: TypeAlias = tuple[Optional[str], Union[str, Literal[False]]]
_IndexEntryTarget: TypeAlias = tuple[str | None, str | Literal[False]]
_IndexEntryTargets: TypeAlias = list[_IndexEntryTarget]
_IndexEntryCategoryKey: TypeAlias = Optional[str]
_IndexEntryCategoryKey: TypeAlias = str | None
_IndexEntrySubItems: TypeAlias = dict[
str,
tuple[_IndexEntryTargets, _IndexEntryCategoryKey],
Expand Down
6 changes: 3 additions & 3 deletions sphinx/environment/adapters/toctree.py
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ def _toctree_standard_entry(
def _toctree_add_classes(node: Element, depth: int, docname: str) -> None:
"""Add 'toctree-l%d' and 'current' classes to the toctree."""
for subnode in node.children:
if isinstance(subnode, (addnodes.compact_paragraph, nodes.list_item)):
if isinstance(subnode, addnodes.compact_paragraph | nodes.list_item):
# for <p> and <li>, indicate the depth level and recurse
subnode['classes'].append(f'toctree-l{depth - 1}')
_toctree_add_classes(subnode, depth, docname)
Expand Down Expand Up @@ -442,7 +442,7 @@ def _toctree_copy(node: ET, depth: int, maxdepth: int, collapse: bool, tags: Tag

copy = node.copy()
for subnode in node.children:
if isinstance(subnode, (addnodes.compact_paragraph, nodes.list_item)):
if isinstance(subnode, addnodes.compact_paragraph | nodes.list_item):
# for <p> and <li>, just recurse
copy.append(_toctree_copy(subnode, depth, maxdepth, collapse, tags))
elif isinstance(subnode, nodes.bullet_list):
Expand All @@ -462,7 +462,7 @@ def _toctree_copy(node: ET, depth: int, maxdepth: int, collapse: bool, tags: Tag
copy.append(_toctree_copy(
child, depth, maxdepth, collapse, tags, # type: ignore[type-var]
))
elif isinstance(subnode, (nodes.reference, nodes.title)):
elif isinstance(subnode, nodes.reference | nodes.title):
# deep copy references and captions
sub_node_copy = subnode.copy()
sub_node_copy.children = [child.deepcopy() for child in subnode.children]
Expand Down
4 changes: 2 additions & 2 deletions sphinx/ext/autodoc/preserve_defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,9 @@ def _is_lambda(x: Any, /) -> bool:


def _get_arguments_inner(x: Any, /) -> ast.arguments | None:
if isinstance(x, (ast.AsyncFunctionDef, ast.FunctionDef, ast.Lambda)):
if isinstance(x, ast.AsyncFunctionDef | ast.FunctionDef | ast.Lambda):
return x.args
if isinstance(x, (ast.Assign, ast.AnnAssign)):
if isinstance(x, ast.Assign | ast.AnnAssign):
return _get_arguments_inner(x.value)
return None

Expand Down
4 changes: 2 additions & 2 deletions sphinx/ext/doctest.py
Original file line number Diff line number Diff line change
Expand Up @@ -420,12 +420,12 @@ def test_doc(self, docname: str, doctree: Node) -> None:

if self.config.doctest_test_doctest_blocks:
def condition(node: Node) -> bool:
return (isinstance(node, (nodes.literal_block, nodes.comment)) and
return (isinstance(node, nodes.literal_block | nodes.comment) and
'testnodetype' in node) or \
isinstance(node, nodes.doctest_block)
else:
def condition(node: Node) -> bool:
return isinstance(node, (nodes.literal_block, nodes.comment)) \
return isinstance(node, nodes.literal_block | nodes.comment) \
and 'testnodetype' in node
for node in doctree.findall(condition):
if self.skipped(node): # type: ignore[arg-type]
Expand Down
4 changes: 2 additions & 2 deletions sphinx/ext/intersphinx/_load.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def validate_intersphinx_mapping(app: Sphinx, config: Config) -> None:
continue

# ensure values are properly formatted
if not isinstance(value, (tuple, list)):
if not isinstance(value, (tuple | list)):
errors += 1
msg = __(
'Invalid value `%r` in intersphinx_mapping[%r]. '
Expand Down Expand Up @@ -105,7 +105,7 @@ def validate_intersphinx_mapping(app: Sphinx, config: Config) -> None:

# ensure inventory locations are None or non-empty
targets: list[InventoryLocation] = []
for target in (inv if isinstance(inv, (tuple, list)) else (inv,)):
for target in (inv if isinstance(inv, (tuple | list)) else (inv,)):
if target is None or target and isinstance(target, str):
targets.append(target)
else:
Expand Down
4 changes: 1 addition & 3 deletions sphinx/ext/intersphinx/_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
from sphinx.util import logging

if TYPE_CHECKING:
from typing import Optional

from sphinx.environment import BuildEnvironment
from sphinx.util.typing import Inventory

Expand All @@ -26,7 +24,7 @@
#:
#: Empty strings are not expected and ``None`` indicates the default
#: inventory file name :data:`~sphinx.builder.html.INVENTORY_FILENAME`.
InventoryLocation = Optional[str]
InventoryLocation = str | None

#: Inventory cache entry. The integer field is the cache expiration time.
InventoryCacheEntry = tuple[InventoryName, int, Inventory]
Expand Down
2 changes: 1 addition & 1 deletion sphinx/pycode/ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def visit_Call(self, node: ast.Call) -> str:
def visit_Constant(self, node: ast.Constant) -> str:
if node.value is Ellipsis:
return "..."
elif isinstance(node.value, (int, float, complex)):
elif isinstance(node.value, int | float | complex):
if self.code:
return ast.get_source_segment(self.code, node) or repr(node.value)
else:
Expand Down
4 changes: 2 additions & 2 deletions sphinx/pycode/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ def __eq__(self, other: Any) -> bool:
return self.kind == other
elif isinstance(other, str):
return self.value == other
elif isinstance(other, (list, tuple)):
elif isinstance(other, list | tuple):
return [self.kind, self.value] == list(other)
elif other is None:
return False
Expand Down Expand Up @@ -404,7 +404,7 @@ def visit_AnnAssign(self, node: ast.AnnAssign) -> None:

def visit_Expr(self, node: ast.Expr) -> None:
"""Handles Expr node and pick up a comment if string."""
if (isinstance(self.previous, (ast.Assign, ast.AnnAssign)) and
if (isinstance(self.previous, ast.Assign | ast.AnnAssign) and
isinstance(node.value, ast.Constant) and isinstance(node.value.value, str)):
try:
targets = get_assign_targets(self.previous)
Expand Down
2 changes: 1 addition & 1 deletion sphinx/testing/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def assert_node(node: Node, cls: Any = None, xpath: str = "", **kwargs: Any) ->
'The node%s has %d child nodes, not one' % (xpath, len(node))
assert_node(node[0], cls[1:], xpath=xpath + "[0]", **kwargs)
elif isinstance(cls, tuple):
assert isinstance(node, (list, nodes.Element)), \
assert isinstance(node, list | nodes.Element), \
'The node%s does not have any items' % xpath
assert len(node) == len(cls), \
'The node%s has %d child nodes, not %r' % (xpath, len(node), len(cls))
Expand Down
4 changes: 2 additions & 2 deletions sphinx/transforms/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ class ApplySourceWorkaround(SphinxTransform):

def apply(self, **kwargs: Any) -> None:
for node in self.document.findall(): # type: Node
if isinstance(node, (nodes.TextElement, nodes.image, nodes.topic)):
if isinstance(node, nodes.TextElement | nodes.image | nodes.topic):
apply_source_workaround(node)


Expand Down Expand Up @@ -477,7 +477,7 @@ def _reorder_index_target_nodes(start_node: nodes.target) -> None:
# as we want *consecutive* target & index nodes.
node: nodes.Node
for node in start_node.findall(descend=False, siblings=True):
if isinstance(node, (nodes.target, addnodes.index)):
if isinstance(node, nodes.target | addnodes.index):
nodes_to_reorder.append(node)
continue
break # must be a consecutive run of target or index nodes
Expand Down
2 changes: 1 addition & 1 deletion sphinx/util/display.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@


def display_chunk(chunk: Any) -> str:
if isinstance(chunk, (list, tuple)):
if isinstance(chunk, list | tuple):
if len(chunk) == 1:
return str(chunk[0])
return f'{chunk[0]} .. {chunk[-1]}'
Expand Down
2 changes: 1 addition & 1 deletion sphinx/util/docfields.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@ def transform(self, node: nodes.field_list) -> None:
if is_typefield:
# filter out only inline nodes; others will result in invalid
# markup being written out
content = [n for n in content if isinstance(n, (nodes.Inline, nodes.Text))]
content = [n for n in content if isinstance(n, nodes.Inline | nodes.Text)]
if content:
types.setdefault(typename, {})[fieldarg] = content
continue
Expand Down
9 changes: 2 additions & 7 deletions sphinx/util/docutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@

import os
import re
from collections.abc import (
Sequence, # NoQA: TCH003
)
from collections.abc import Sequence # NoQA: TCH003
from contextlib import contextmanager
from copy import copy
from os import path
Expand All @@ -29,10 +27,7 @@
report_re = re.compile('^(.+?:(?:\\d+)?): \\((DEBUG|INFO|WARNING|ERROR|SEVERE)/(\\d+)?\\) ')

if TYPE_CHECKING:
from collections.abc import (
Callable, # NoQA: TCH003
Iterator,
)
from collections.abc import Callable, Iterator # NoQA: TCH003
from types import ModuleType

from docutils.frontend import Values
Expand Down
Loading

0 comments on commit 28d4fdd

Please sign in to comment.