From 8ffd1ad8c3c5ffd9546d15a49cca7f0f8c7e3a2c Mon Sep 17 00:00:00 2001 From: Adam Turner <9087854+AA-Turner@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:13:07 -0700 Subject: [PATCH] Bump ty to 0.0.90 (#14763) --- .../tutorials/examples/autodoc_intenum.py | 2 +- pyproject.toml | 3 +- sphinx/_cli/__init__.py | 2 +- sphinx/_cli/util/colour.py | 2 +- sphinx/addnodes.py | 2 +- sphinx/application.py | 4 +- sphinx/builders/gettext.py | 6 +-- sphinx/builders/html/__init__.py | 4 +- sphinx/builders/xml.py | 2 +- sphinx/cmd/quickstart.py | 4 +- sphinx/config.py | 6 +-- sphinx/directives/admonitions.py | 2 +- sphinx/domains/__init__.py | 10 ++-- sphinx/domains/c/__init__.py | 8 ++-- sphinx/domains/c/_ast.py | 24 +++++----- sphinx/domains/c/_parser.py | 6 +-- sphinx/domains/c/_symbol.py | 12 ++--- sphinx/domains/cpp/__init__.py | 14 +++--- sphinx/domains/cpp/_ast.py | 38 +++++++-------- sphinx/domains/cpp/_parser.py | 4 +- sphinx/domains/cpp/_symbol.py | 10 ++-- sphinx/domains/javascript.py | 2 +- sphinx/domains/python/__init__.py | 2 +- sphinx/domains/python/_annotations.py | 2 +- sphinx/domains/python/_object.py | 8 ++-- sphinx/domains/std/__init__.py | 18 ++++---- sphinx/environment/__init__.py | 2 +- sphinx/environment/adapters/toctree.py | 6 +-- sphinx/environment/collectors/metadata.py | 2 +- sphinx/ext/autodoc/_dynamic/_loader.py | 2 +- sphinx/ext/autodoc/_dynamic/_member_finder.py | 2 +- .../autodoc/_dynamic/_preserve_defaults.py | 2 +- sphinx/ext/autodoc/_dynamic/_signatures.py | 2 +- sphinx/ext/autodoc/_dynamic/_type_comments.py | 6 +-- sphinx/ext/autodoc/_generate.py | 6 +-- .../_legacy_class_based/_documenters.py | 46 +++++++++---------- sphinx/ext/autosummary/generate.py | 2 +- sphinx/ext/doctest.py | 22 ++++----- sphinx/ext/graphviz.py | 2 +- sphinx/ext/inheritance_diagram.py | 2 +- sphinx/ext/intersphinx/_shared.py | 16 +++---- sphinx/ext/mathjax.py | 2 +- sphinx/ext/napoleon/__init__.py | 17 +++++++ sphinx/ext/napoleon/docstring.py | 11 +++-- sphinx/ext/viewcode.py | 16 +++---- sphinx/highlighting.py | 2 +- sphinx/io.py | 2 +- sphinx/jinja2glue.py | 6 +-- sphinx/locale/__init__.py | 2 +- sphinx/parsers.py | 1 + sphinx/pycode/ast.py | 2 +- sphinx/pycode/parser.py | 26 +++++------ sphinx/roles.py | 2 +- sphinx/search/ja.py | 4 +- sphinx/search/zh.py | 2 +- sphinx/testing/util.py | 4 +- sphinx/theming.py | 2 +- sphinx/transforms/__init__.py | 2 +- sphinx/transforms/i18n.py | 4 +- sphinx/util/_serialise.py | 2 +- sphinx/util/display.py | 2 +- sphinx/util/docfields.py | 4 +- sphinx/util/docutils.py | 29 ++++++------ sphinx/util/inspect.py | 2 +- sphinx/util/matching.py | 2 +- sphinx/util/nodes.py | 6 +-- sphinx/util/parallel.py | 10 ++-- sphinx/util/requests.py | 2 +- sphinx/util/rst.py | 2 +- sphinx/util/template.py | 2 +- sphinx/util/typing.py | 2 +- sphinx/versioning.py | 14 +++--- sphinx/writers/html5.py | 2 +- sphinx/writers/latex.py | 6 +-- sphinx/writers/texinfo.py | 4 +- sphinx/writers/text.py | 2 +- tests/test_builders/test_build_linkcheck.py | 2 +- tests/test_builders/xpath_util.py | 2 +- tests/test_directives/test_directive_only.py | 2 +- .../test_ext_autodoc_automodule.py | 2 +- .../test_ext_autodoc/test_ext_autodoc_mock.py | 4 +- .../test_ext_autodoc_signatures.py | 2 +- .../test_ext_autosummary.py | 4 +- .../test_ext_intersphinx.py | 11 ++++- .../test_ext_inheritance_diagram.py | 2 +- tests/test_highlighting.py | 2 +- tests/test_intl/test_intl.py | 2 +- tests/test_pycode/test_pycode.py | 3 +- .../test_transforms_post_transforms.py | 2 +- tests/test_util/test_util_inspect.py | 8 ++-- tests/test_util/test_util_inspect_py314.py | 6 +-- tests/test_util/test_util_rst.py | 2 +- tests/test_util/test_util_template.py | 2 +- tests/test_util/test_util_typing.py | 7 +-- tests/test_versioning.py | 4 +- ty.toml | 2 + uv.lock | 39 ++++++++-------- 97 files changed, 331 insertions(+), 296 deletions(-) diff --git a/doc/development/tutorials/examples/autodoc_intenum.py b/doc/development/tutorials/examples/autodoc_intenum.py index ebddcbbd4d..f97e9ddab8 100644 --- a/doc/development/tutorials/examples/autodoc_intenum.py +++ b/doc/development/tutorials/examples/autodoc_intenum.py @@ -45,7 +45,7 @@ class IntEnumDocumenter(ClassDocumenter): use_hex = self.options.hex self.add_line('', source_name) - for the_member_name, enum_member in enum_object.__members__.items(): # type: ignore[attr-defined] + for the_member_name, enum_member in enum_object.__members__.items(): # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] the_member_value = enum_member.value if use_hex: the_member_value = hex(the_member_value) diff --git a/pyproject.toml b/pyproject.toml index d429bd6ec4..18858552fc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -135,8 +135,7 @@ types = [ "mypy==1.19.1", "pyrefly", "pyright==1.1.407", - # Newer releases report hundreds of diagnostics with the current rule ignores. - "ty==0.0.10", + "ty==0.0.90", { include-group = "type-stubs" }, ] type-stubs = [ diff --git a/sphinx/_cli/__init__.py b/sphinx/_cli/__init__.py index cce4c56e7d..a28addc48d 100644 --- a/sphinx/_cli/__init__.py +++ b/sphinx/_cli/__init__.py @@ -302,7 +302,7 @@ def run(argv: Sequence[str] = (), /) -> int: cmd_args = cmd_parser.parse_args(cmd_argv) return runner(cmd_args) except SystemExit as exc: - return exc.code # type: ignore[return-value] + return exc.code # type: ignore[return-value] # ty: ignore[invalid-return-type] except (Exception, KeyboardInterrupt): return 2 diff --git a/sphinx/_cli/util/colour.py b/sphinx/_cli/util/colour.py index c38f45f2dc..b29f7d0d63 100644 --- a/sphinx/_cli/util/colour.py +++ b/sphinx/_cli/util/colour.py @@ -78,7 +78,7 @@ def _create_colour_func(escape_code: str, /) -> Callable[[str], str]: return text return f'\x1b[{escape_code}m{text}\x1b[39;49;00m' - inner.__escape_code = escape_code # type: ignore[attr-defined] + inner.__escape_code = escape_code # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] return inner diff --git a/sphinx/addnodes.py b/sphinx/addnodes.py index 68cd86242e..16f0998457 100644 --- a/sphinx/addnodes.py +++ b/sphinx/addnodes.py @@ -147,7 +147,7 @@ class desc_signature( classes = ['sig', 'sig-object'] @property - def child_text_separator(self) -> str: # type: ignore[override] + def child_text_separator(self) -> str: # type: ignore[override] # ty: ignore[invalid-property-type-override] if self.get('is_multiline'): return ' ' else: diff --git a/sphinx/application.py b/sphinx/application.py index 5349c36ad4..e6d85095e4 100644 --- a/sphinx/application.py +++ b/sphinx/application.py @@ -1507,7 +1507,7 @@ class Sphinx: filename = filename or '' self.registry.add_js_file(filename, priority=priority, **kwargs) with contextlib.suppress(AttributeError): - self.builder.add_js_file( # type: ignore[attr-defined] + self.builder.add_js_file( # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] filename, priority=priority, **kwargs ) @@ -1574,7 +1574,7 @@ class Sphinx: logger.debug('[app] adding stylesheet: %r', filename) self.registry.add_css_files(filename, priority=priority, **kwargs) with contextlib.suppress(AttributeError): - self.builder.add_css_file( # type: ignore[attr-defined] + self.builder.add_css_file( # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] filename, priority=priority, **kwargs ) diff --git a/sphinx/builders/gettext.py b/sphinx/builders/gettext.py index fc659d744d..cb241d4186 100644 --- a/sphinx/builders/gettext.py +++ b/sphinx/builders/gettext.py @@ -181,7 +181,7 @@ class I18nBuilder(Builder): for toctree in self.env.tocs[docname].findall(addnodes.toctree): for node, msg in extract_messages(toctree): - node.uid = '' # type: ignore[attr-defined] # Hack UUID model + node.uid = '' # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] # Hack UUID model catalog.add(msg, node) for node, msg in extract_messages(doctree): @@ -264,7 +264,7 @@ class MessageCatalogBuilder(I18nBuilder): logger.info(bold(__('building [%s]: ')), self.name, nonl=True) logger.info(__('targets for %d template files'), len(files)) - extract_translations = self.templates.environment.extract_translations + extract_translations = self.templates.environment.extract_translations # ty: ignore[unresolved-attribute] for template in status_iterator( files, @@ -283,7 +283,7 @@ class MessageCatalogBuilder(I18nBuilder): msg = f'{template}: {exc!r}' raise ThemeError(msg) from exc - def build( # type: ignore[misc] + def build( # type: ignore[misc] # ty: ignore[override-of-final-method] self, docnames: Iterable[str] | None, summary: str | None = None, diff --git a/sphinx/builders/html/__init__.py b/sphinx/builders/html/__init__.py index 35190c368e..247bee98be 100644 --- a/sphinx/builders/html/__init__.py +++ b/sphinx/builders/html/__init__.py @@ -515,7 +515,7 @@ class StandaloneHTMLBuilder(Builder): self._orig_js_files = list(dict.fromkeys(self._js_files)) styles = list(self._get_style_filenames()) - self.globalcontext = { + self.globalcontext: dict[str, Any] = { 'embedded': self.embedded, 'project': self.config.project, 'release': return_codes_re.sub('', self.config.release), @@ -1351,7 +1351,7 @@ def validate_math_renderer(app: Sphinx) -> None: if app.builder.format != 'html': return - name = app.builder.math_renderer_name # type: ignore[attr-defined] + name = app.builder.math_renderer_name # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] if name is None: msg = __( 'Many math_renderers are registered. But no math_renderer is selected.' diff --git a/sphinx/builders/xml.py b/sphinx/builders/xml.py index e1a50ca45b..7d8fa0636e 100644 --- a/sphinx/builders/xml.py +++ b/sphinx/builders/xml.py @@ -89,7 +89,7 @@ class XMLBuilder(Builder): # so that we can override the translator class visitor: XMLTranslator = self.create_translator(doctree) # type: ignore[assignment] doctree.walkabout(visitor) - return ''.join(visitor.output) # ty: ignore[unresolved-attribute] + return ''.join(visitor.output) def finish(self) -> None: pass diff --git a/sphinx/cmd/quickstart.py b/sphinx/cmd/quickstart.py index 0a15791aa5..3c291c0e08 100644 --- a/sphinx/cmd/quickstart.py +++ b/sphinx/cmd/quickstart.py @@ -750,7 +750,7 @@ def main(argv: Sequence[str] = (), /) -> int: try: args = parser.parse_args(argv or sys.argv[1:]) except SystemExit as err: - return err.code # type: ignore[return-value] + return err.code # type: ignore[return-value] # ty: ignore[invalid-return-type] d = vars(args) # delete None or False value @@ -806,7 +806,7 @@ def main(argv: Sequence[str] = (), /) -> int: print('[Interrupted.]') return 130 # 128 + SIGINT - for variable in d.get('variables', []): # type: ignore[union-attr] + for variable in d.get('variables', []): # type: ignore[union-attr] # ty: ignore[not-iterable] try: name, value = variable.split('=') d[name] = value diff --git a/sphinx/config.py b/sphinx/config.py index 979d350608..d0ad3920e4 100644 --- a/sphinx/config.py +++ b/sphinx/config.py @@ -619,7 +619,7 @@ def _validate_valid_types( if not valid_types: return frozenset() if isinstance(valid_types, (frozenset, ENUM)): - return valid_types # ty: ignore[invalid-return-type] + return valid_types if isinstance(valid_types, type): return frozenset((valid_types,)) if valid_types is Any: @@ -705,7 +705,7 @@ def evaluate_copyright_placeholders(_app: Sphinx, config: Config) -> None: else: if any('%Y' in line for line in value): items = (line.replace('%Y', replace_yr) for line in value) - config[k] = type(value)(items) # type: ignore[call-arg] + config[k] = type(value)(items) # type: ignore[call-arg] # ty: ignore[too-many-positional-arguments] def correct_copyright_year(_app: Sphinx, config: Config) -> None: @@ -736,7 +736,7 @@ def correct_copyright_year(_app: Sphinx, config: Config) -> None: items = ( _substitute_copyright_year(x, current_yr, replace_yr) for x in value ) - config[k] = type(value)(items) # type: ignore[call-arg] + config[k] = type(value)(items) # type: ignore[call-arg] # ty: ignore[too-many-positional-arguments] def _substitute_copyright_year( diff --git a/sphinx/directives/admonitions.py b/sphinx/directives/admonitions.py index ddd7a9eca7..97e6f40248 100644 --- a/sphinx/directives/admonitions.py +++ b/sphinx/directives/admonitions.py @@ -27,7 +27,7 @@ def _collapsible_arg(argument: str | None) -> str: class SphinxAdmonition(BaseAdmonition, SphinxDirective): - option_spec: ClassVar[OptionSpec] = BaseAdmonition.option_spec.copy() # type: ignore[union-attr] + option_spec: ClassVar[OptionSpec] = BaseAdmonition.option_spec.copy() # type: ignore[union-attr] # ty: ignore[unresolved-attribute] option_spec |= { 'collapsible': _collapsible_arg, } diff --git a/sphinx/domains/__init__.py b/sphinx/domains/__init__.py index 17aa7bdc45..41c8860901 100644 --- a/sphinx/domains/__init__.py +++ b/sphinx/domains/__init__.py @@ -113,10 +113,10 @@ class Domain: self._type2role: dict[str, str] = {} # convert class variables to instance one (to enhance through API) - self.object_types = dict(self.object_types) # type: ignore[misc] - self.directives = dict(self.directives) # type: ignore[misc] - self.roles = dict(self.roles) # type: ignore[misc] - self.indices = list(self.indices) # type: ignore[misc] + self.object_types = dict(self.object_types) # type: ignore[misc] # ty: ignore[invalid-attribute-access] + self.directives = dict(self.directives) # type: ignore[misc] # ty: ignore[invalid-attribute-access] + self.roles = dict(self.roles) # type: ignore[misc] # ty: ignore[invalid-attribute-access] + self.indices = list(self.indices) # type: ignore[misc] # ty: ignore[invalid-attribute-access] if self.name not in domain_data: assert isinstance(self.initial_data, dict) @@ -191,7 +191,7 @@ class Domain: fullname = f'{self.name}:{name}' BaseDirective = self.directives[name] - class DirectiveAdapter(BaseDirective): # type: ignore[valid-type,misc] + class DirectiveAdapter(BaseDirective): # type: ignore[valid-type,misc] # ty: ignore[unsupported-base] def run(self) -> list[Node]: self.name = fullname return super().run() diff --git a/sphinx/domains/c/__init__.py b/sphinx/domains/c/__init__.py index 91f548d402..2ecdc3a572 100644 --- a/sphinx/domains/c/__init__.py +++ b/sphinx/domains/c/__init__.py @@ -150,7 +150,7 @@ class CObject(ObjectDescription[ASTDeclaration]): if s is not None: # something is already declared with that name return - decl_clone = symbol.declaration.clone() + decl_clone = symbol.declaration.clone() # ty: ignore[unresolved-attribute] decl_clone.enumeratorScopedSymbol = symbol Symbol( parent=target_symbol, @@ -175,7 +175,7 @@ class CObject(ObjectDescription[ASTDeclaration]): newest_id = ids[0] assert newest_id # shouldn't be None - name = ast.symbol.get_full_nested_name().get_display_string().lstrip('.') + name = ast.symbol.get_full_nested_name().get_display_string().lstrip('.') # ty: ignore[unresolved-attribute] if newest_id not in self.state.document.ids: # always add the newest id assert newest_id @@ -554,7 +554,7 @@ class AliasTransform(SphinxTransform): if not skip_this: signode = addnodes.desc_signature('', '') nodes.append(signode) - s.declaration.describe_signature( + s.declaration.describe_signature( # ty: ignore[unresolved-attribute] signode, 'markName', self.env, render_options ) @@ -952,7 +952,7 @@ class CDomain(Domain): env, fromdocname, builder, 'any', target, node, contnode ) if retnode: - return [('c:' + self.role_for_objtype(objtype), retnode)] + return [('c:' + self.role_for_objtype(objtype), retnode)] # ty: ignore[unsupported-operator] return [] def get_objects(self) -> Iterator[tuple[str, str, str, str, str, int]]: diff --git a/sphinx/domains/c/_ast.py b/sphinx/domains/c/_ast.py index 89e76627b6..9340182a68 100644 --- a/sphinx/domains/c/_ast.py +++ b/sphinx/domains/c/_ast.py @@ -28,13 +28,13 @@ if TYPE_CHECKING: ) type DeclarationType = ( - 'ASTStruct' - | 'ASTUnion' - | 'ASTEnum' - | 'ASTEnumerator' - | 'ASTType' - | 'ASTTypeWithInit' - | 'ASTMacro' + ASTStruct + | ASTUnion + | ASTEnum + | ASTEnumerator + | ASTType + | ASTTypeWithInit + | ASTMacro ) @@ -372,7 +372,7 @@ class ASTParenExpr(ASTExpression): return '(' + transform(self.expr) + ')' def get_id(self, version: int) -> str: - return self.expr.get_id(version) # type: ignore[attr-defined] + return self.expr.get_id(version) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] def describe_signature( self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol @@ -834,7 +834,7 @@ class ASTFunctionParameter(ASTBase): def get_id(self, version: int, objectType: str, symbol: Symbol) -> str: # the anchor will be our parent - return symbol.parent.declaration.get_id(version, prefixed=False) + return symbol.parent.declaration.get_id(version, prefixed=False) # ty: ignore[unresolved-attribute] def _stringify(self, transform: StringifyTransform) -> str: if self.ellipsis: @@ -849,7 +849,7 @@ class ASTFunctionParameter(ASTBase): if self.ellipsis: signode += addnodes.desc_sig_punctuation('...', '...') else: - self.arg.describe_signature(signode, mode, env, symbol=symbol) + self.arg.describe_signature(signode, mode, env, symbol=symbol) # ty: ignore[unresolved-attribute] class ASTParameters(ASTBase): @@ -1670,7 +1670,7 @@ class ASTMacroParameter(ASTBase): name = str(self) signode += addnodes.desc_sig_name(name, name) else: - self.arg.describe_signature(signode, mode, env, symbol=symbol) + self.arg.describe_signature(signode, mode, env, symbol=symbol) # ty: ignore[unresolved-attribute] class ASTMacro(ASTBase): @@ -1906,7 +1906,7 @@ class ASTDeclaration(ASTBaseBase): def get_id(self, version: int, prefixed: bool = True) -> str: if self.objectType == 'enumerator' and self.enumeratorScopedSymbol: - return self.enumeratorScopedSymbol.declaration.get_id(version, prefixed) + return self.enumeratorScopedSymbol.declaration.get_id(version, prefixed) # ty: ignore[unresolved-attribute] id_ = self.declaration.get_id(version, self.objectType, self.symbol) if prefixed: return _id_prefix[version] + id_ diff --git a/sphinx/domains/c/_parser.py b/sphinx/domains/c/_parser.py index 1f6da643ca..21eff3cd97 100644 --- a/sphinx/domains/c/_parser.py +++ b/sphinx/domains/c/_parser.py @@ -150,8 +150,8 @@ class DefinitionParser(BaseParser): # character-literal if self.match(char_literal_re): - prefix = self.last_match.group(1) # may be None when no prefix - data = self.last_match.group(2) + prefix = self.last_match.group(1) # ty: ignore[unresolved-attribute] # may be None when no prefix + data = self.last_match.group(2) # ty: ignore[unresolved-attribute] try: return ASTCharLiteral(prefix, data) except UnicodeDecodeError as e: @@ -404,7 +404,7 @@ class DefinitionParser(BaseParser): self.pos = pos if not one_more: break - return ASTBinOpExpr(exprs, ops) # type: ignore[return-value] + return ASTBinOpExpr(exprs, ops) # type: ignore[return-value] # ty: ignore[invalid-return-type] return _parse_bin_op_expr(self, 0) diff --git a/sphinx/domains/c/_symbol.py b/sphinx/domains/c/_symbol.py index 0494305dd3..7768252e91 100644 --- a/sphinx/domains/c/_symbol.py +++ b/sphinx/domains/c/_symbol.py @@ -143,22 +143,22 @@ class Symbol: return self._children_by_name.values() def _add_child(self, child: Symbol) -> None: - name = child.ident.name + name = child.ident.name # ty: ignore[unresolved-attribute] if name in self._children_by_name: # Duplicate so don't add - will be reported in _add_symbols() return self._children_by_name[name] = child child_docname: str = child.docname self._children_by_docname.setdefault(child_docname, {})[name] = child - if child.ident.is_anonymous: + if child.ident.is_anonymous: # ty: ignore[unresolved-attribute] self._anon_children.add(child) def _remove_child(self, child: Symbol) -> None: - name = child.ident.name + name = child.ident.name # ty: ignore[unresolved-attribute] self._children_by_name.pop(name, None) if children := self._children_by_docname.get(child.docname): children.pop(name, None) - if child.ident.is_anonymous: + if child.ident.is_anonymous: # ty: ignore[unresolved-attribute] self._anon_children.discard(child) def _fill_empty(self, declaration: ASTDeclaration, docname: str, line: int) -> None: @@ -466,7 +466,7 @@ class Symbol: if Symbol.debug_lookup: Symbol.debug_print('cand_id:', cand_id) for symbol in with_decl: - old_id = symbol.declaration.get_newest_id() + old_id = symbol.declaration.get_newest_id() # ty: ignore[unresolved-attribute] if Symbol.debug_lookup: Symbol.debug_print('old_id: ', old_id) if cand_id == old_id: @@ -551,7 +551,7 @@ class Symbol: assert other is not None for other_child in other._children: - other_name = other_child.ident.name + other_name = other_child.ident.name # ty: ignore[unresolved-attribute] if other_name not in self._children_by_name: # TODO: hmm, should we prune by docnames? other_child.parent = self diff --git a/sphinx/domains/cpp/__init__.py b/sphinx/domains/cpp/__init__.py index 6334fabd0e..abff579ca9 100644 --- a/sphinx/domains/cpp/__init__.py +++ b/sphinx/domains/cpp/__init__.py @@ -211,7 +211,7 @@ class CPPObject(ObjectDescription[ASTDeclaration]): if s is not None: # something is already declared with that name return - decl_clone = symbol.declaration.clone() + decl_clone = symbol.declaration.clone() # ty: ignore[unresolved-attribute] decl_clone.enumeratorScopedSymbol = symbol Symbol( parent=target_symbol, @@ -247,10 +247,10 @@ class CPPObject(ObjectDescription[ASTDeclaration]): location=self.get_location(), ) - name = ast.symbol.get_full_nested_name().get_display_string().lstrip(':') + name = ast.symbol.get_full_nested_name().get_display_string().lstrip(':') # ty: ignore[unresolved-attribute] # Add index entry, but not if it's a declaration inside a concept is_in_concept = False - s = ast.symbol.parent + s = ast.symbol.parent # ty: ignore[unresolved-attribute] while s is not None: decl = s.declaration s = s.parent @@ -278,7 +278,7 @@ class CPPObject(ObjectDescription[ASTDeclaration]): # if the name is not unique, the first one will win names = self.env.domaindata['cpp']['names'] if name not in names: - names[name] = ast.symbol.docname + names[name] = ast.symbol.docname # ty: ignore[unresolved-attribute] # always add the newest id assert newest_id signode['ids'].append(newest_id) @@ -424,7 +424,7 @@ class CPPObject(ObjectDescription[ASTDeclaration]): self.env.ref_context['cpp:parent_key'] = last_symbol.get_lookup_key() self.env.current_document.cpp_domain_name = ( *self.env.current_document.cpp_domain_name, - last_symbol.identOrOp._stringify(str), + last_symbol.identOrOp._stringify(str), # ty: ignore[unresolved-attribute] ) def after_content(self) -> None: @@ -672,7 +672,7 @@ class AliasTransform(SphinxTransform): if not skip_this: signode = addnodes.desc_signature('', '') nodes.append(signode) - s.declaration.describe_signature( + s.declaration.describe_signature( # ty: ignore[unresolved-attribute] signode, 'markName', self.env, render_options ) @@ -1270,7 +1270,7 @@ class CPPDomain(Domain): if objtype == 'templateParam': return [('cpp:templateParam', retnode)] else: - return [('cpp:' + self.role_for_objtype(objtype), retnode)] + return [('cpp:' + self.role_for_objtype(objtype), retnode)] # ty: ignore[unsupported-operator] return [] def get_objects(self) -> Iterator[tuple[str, str, str, str, str, int]]: diff --git a/sphinx/domains/cpp/_ast.py b/sphinx/domains/cpp/_ast.py index 90730196a2..9424c26c03 100644 --- a/sphinx/domains/cpp/_ast.py +++ b/sphinx/domains/cpp/_ast.py @@ -313,8 +313,8 @@ class ASTNestedName(ASTBase): template_params: list[Any] = [] if mode == 'lastIsName': assert symbol is not None - if symbol.declaration.templatePrefix is not None: - template_params = symbol.declaration.templatePrefix.templates + if symbol.declaration.templatePrefix is not None: # ty: ignore[unresolved-attribute] + template_params = symbol.declaration.templatePrefix.templates # ty: ignore[unresolved-attribute] i_template_params = 0 template_params_prefix = '' prefix = '' @@ -2038,7 +2038,7 @@ class ASTFunctionParameter(ASTBase): # this is not part of the normal name mangling in C++ if symbol: # the anchor will be our parent - return symbol.parent.declaration.get_id(version, prefixed=False) + return symbol.parent.declaration.get_id(version, prefixed=False) # ty: ignore[unresolved-attribute] # else, do the usual if self.ellipsis: return 'z' @@ -3394,7 +3394,7 @@ class ASTType(ASTBase): if objectType: # needs the name if objectType == 'function': # also modifiers res.extend(( - symbol.get_full_nested_name().get_id(version), + symbol.get_full_nested_name().get_id(version), # ty: ignore[unresolved-attribute] self.decl.get_param_id(version), self.decl.get_modifiers_id(version), )) @@ -3404,7 +3404,7 @@ class ASTType(ASTBase): ): res.append('CE') elif objectType == 'type': # just the name - res.append(symbol.get_full_nested_name().get_id(version)) + res.append(symbol.get_full_nested_name().get_id(version)) # ty: ignore[unresolved-attribute] else: raise AssertionError(objectType) else: # only type encoding @@ -3421,10 +3421,10 @@ class ASTType(ASTBase): if objectType: # needs the name if objectType == 'function': # also modifiers modifiers = self.decl.get_modifiers_id(version) - res.append(symbol.get_full_nested_name().get_id(version, modifiers)) + res.append(symbol.get_full_nested_name().get_id(version, modifiers)) # ty: ignore[unresolved-attribute] if version >= 4: # with templates we need to mangle the return type in as well - templ = symbol.declaration.templatePrefix + templ = symbol.declaration.templatePrefix # ty: ignore[unresolved-attribute] if templ is not None: type_id = self.decl.get_ptr_suffix_id(version) if self.trailingReturn: @@ -3435,7 +3435,7 @@ class ASTType(ASTBase): res.append(return_type_id) res.append(self.decl.get_param_id(version)) elif objectType == 'type': # just the name - res.append(symbol.get_full_nested_name().get_id(version)) + res.append(symbol.get_full_nested_name().get_id(version)) # ty: ignore[unresolved-attribute] else: raise AssertionError(objectType) else: # only type encoding @@ -3504,7 +3504,7 @@ class ASTTemplateParamConstrainedTypeWithInit(ASTBase): assert version >= 2 if symbol: # the anchor will be our parent - return symbol.parent.declaration.get_id(version, prefixed=False) + return symbol.parent.declaration.get_id(version, prefixed=False) # ty: ignore[unresolved-attribute] else: return self.type.get_id(version) @@ -3554,11 +3554,11 @@ class ASTTypeWithInit(ASTBase): return self.type.get_id(version, objectType) if version == 1: return ( - symbol.get_full_nested_name().get_id(version) + symbol.get_full_nested_name().get_id(version) # ty: ignore[unresolved-attribute] + '__' + self.type.get_id(version) ) - return symbol.get_full_nested_name().get_id(version) + return symbol.get_full_nested_name().get_id(version) # ty: ignore[unresolved-attribute] def _stringify(self, transform: StringifyTransform) -> str: res = [transform(self.type)] @@ -3593,7 +3593,7 @@ class ASTTypeUsing(ASTBase): ) -> str: if version == 1: raise NoOldIdError - return symbol.get_full_nested_name().get_id(version) + return symbol.get_full_nested_name().get_id(version) # ty: ignore[unresolved-attribute] def _stringify(self, transform: StringifyTransform) -> str: res = [transform(self.name)] @@ -3645,7 +3645,7 @@ class ASTConcept(ASTBase): ) -> str: if version == 1: raise NoOldIdError - return symbol.get_full_nested_name().get_id(version) + return symbol.get_full_nested_name().get_id(version) # ty: ignore[unresolved-attribute] def _stringify(self, transform: StringifyTransform) -> str: res = transform(self.nestedName) @@ -4051,7 +4051,7 @@ class ASTTemplateParamType(ASTTemplateParam): assert version >= 2 if symbol: # the anchor will be our parent - return symbol.parent.declaration.get_id(version, prefixed=False) + return symbol.parent.declaration.get_id(version, prefixed=False) # ty: ignore[unresolved-attribute] else: return self.data.get_id(version) @@ -4100,7 +4100,7 @@ class ASTTemplateParamTemplateType(ASTTemplateParam): # this is not part of the normal name mangling in C++ if symbol: # the anchor will be our parent - return symbol.parent.declaration.get_id(version, prefixed=None) + return symbol.parent.declaration.get_id(version, prefixed=None) # ty: ignore[unresolved-attribute] else: return self.nestedParams.get_id(version) + self.data.get_id(version) @@ -4161,7 +4161,7 @@ class ASTTemplateParamNonType(ASTTemplateParam): # this is not part of the normal name mangling in C++ if symbol: # the anchor will be our parent - return symbol.parent.declaration.get_id(version, prefixed=None) + return symbol.parent.declaration.get_id(version, prefixed=None) # ty: ignore[unresolved-attribute] else: res = '_' if self.parameterPack: @@ -4312,7 +4312,7 @@ class ASTTemplateIntroductionParameter(ASTBase): # this is not part of the normal name mangling in C++ if symbol: # the anchor will be our parent - return symbol.parent.declaration.get_id(version, prefixed=None) + return symbol.parent.declaration.get_id(version, prefixed=None) # ty: ignore[unresolved-attribute] else: if self.parameterPack: return 'Dp' @@ -4584,11 +4584,11 @@ class ASTDeclaration(ASTBase): if self.templatePrefix or self.trailingRequiresClause: raise NoOldIdError if self.objectType == 'enumerator' and self.enumeratorScopedSymbol: - return self.enumeratorScopedSymbol.declaration.get_id(version) + return self.enumeratorScopedSymbol.declaration.get_id(version) # ty: ignore[unresolved-attribute] return self.declaration.get_id(version, self.objectType, self.symbol) # version >= 2 if self.objectType == 'enumerator' and self.enumeratorScopedSymbol: - return self.enumeratorScopedSymbol.declaration.get_id(version, prefixed) + return self.enumeratorScopedSymbol.declaration.get_id(version, prefixed) # ty: ignore[unresolved-attribute] if prefixed: res = [_id_prefix[version]] else: diff --git a/sphinx/domains/cpp/_parser.py b/sphinx/domains/cpp/_parser.py index b6dad6f85d..35decd145d 100644 --- a/sphinx/domains/cpp/_parser.py +++ b/sphinx/domains/cpp/_parser.py @@ -2212,7 +2212,7 @@ class DefinitionParser(BaseParser): name, template_prefix, full_spec_shorthand=False ) res = ASTNamespace(name, template_prefix) - res.objectType = 'namespace' # type: ignore[attr-defined] + res.objectType = 'namespace' # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] return res def parse_xref_object(self) -> tuple[ASTNamespace | ASTDeclaration, bool]: @@ -2230,7 +2230,7 @@ class DefinitionParser(BaseParser): name, template_prefix, full_spec_shorthand=True ) res1 = ASTNamespace(name, template_prefix) - res1.objectType = 'xref' # type: ignore[attr-defined] + res1.objectType = 'xref' # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] return res1, True except DefinitionError as e1: try: diff --git a/sphinx/domains/cpp/_symbol.py b/sphinx/domains/cpp/_symbol.py index edc7ab6885..7d815c071d 100644 --- a/sphinx/domains/cpp/_symbol.py +++ b/sphinx/domains/cpp/_symbol.py @@ -321,7 +321,7 @@ class Symbol: def children_recurse_anon(self) -> Iterator[Symbol]: for c in self._children: yield c - if not c.identOrOp.is_anon(): + if not c.identOrOp.is_anon(): # ty: ignore[unresolved-attribute] continue yield from c.children_recurse_anon @@ -779,10 +779,10 @@ class Symbol: for symbol in with_decl: # but all existing must be functions as well, # otherwise we declare it to be a duplicate - if symbol.declaration.objectType != 'function': + if symbol.declaration.objectType != 'function': # ty: ignore[unresolved-attribute] self._handle_duplicate_declaration(symbol, cand_symbol, declaration) # (not reachable) - old_id = symbol.declaration.get_newest_id() + old_id = symbol.declaration.get_newest_id() # ty: ignore[unresolved-attribute] if Symbol.debug_lookup: Symbol.debug_print('old_id: ', old_id) if cand_id == old_id: @@ -959,8 +959,8 @@ class Symbol: else: our_object_type = our_child.declaration.objectType other_object_type = other_child.declaration.objectType - our_child_parent_decl = our_child.parent.declaration - other_child_parent_decl = other_child.parent.declaration + our_child_parent_decl = our_child.parent.declaration # ty: ignore[unresolved-attribute] + other_child_parent_decl = other_child.parent.declaration # ty: ignore[unresolved-attribute] if ( other_object_type == our_object_type and other_object_type in {'templateParam', 'functionParam'} diff --git a/sphinx/domains/javascript.py b/sphinx/domains/javascript.py index 6702d9566a..350e70c617 100644 --- a/sphinx/domains/javascript.py +++ b/sphinx/domains/javascript.py @@ -141,7 +141,7 @@ class JSObject(ObjectDescription[tuple[str, str]]): trailing_comma=trailing_comma, env=self.env, ) - return fullname, prefix # type: ignore[return-value] + return fullname, prefix # type: ignore[return-value] # ty: ignore[invalid-return-type] def _object_hierarchy_parts(self, sig_node: desc_signature) -> tuple[str, ...]: if 'fullname' not in sig_node: diff --git a/sphinx/domains/python/__init__.py b/sphinx/domains/python/__init__.py index 0603cca43c..cc309e88be 100644 --- a/sphinx/domains/python/__init__.py +++ b/sphinx/domains/python/__init__.py @@ -1029,7 +1029,7 @@ class PythonDomain(Domain): # if not found, use contnode children = [contnode] - role = 'py:' + self.role_for_objtype(obj[2]) # type: ignore[operator] + role = 'py:' + self.role_for_objtype(obj[2]) # type: ignore[operator] # ty: ignore[unsupported-operator] results.append(( role, make_refnode(builder, fromdocname, obj[0], obj[1], children, name), diff --git a/sphinx/domains/python/_annotations.py b/sphinx/domains/python/_annotations.py index 8e2043c98b..8370ad32ff 100644 --- a/sphinx/domains/python/_annotations.py +++ b/sphinx/domains/python/_annotations.py @@ -184,7 +184,7 @@ def _parse_annotation(annotation: str, env: BuildEnvironment) -> list[Node]: addnodes.desc_sig_punctuation('', ')'), ] - return result + return result # ty: ignore[invalid-return-type] if isinstance(node, ast.Call): # Call nodes can be used in Annotated type metadata, # for example Annotated[str, ArbitraryTypeValidator(str, len=10)] diff --git a/sphinx/domains/python/_object.py b/sphinx/domains/python/_object.py index 6a0f0ff733..bc6949a184 100644 --- a/sphinx/domains/python/_object.py +++ b/sphinx/domains/python/_object.py @@ -66,7 +66,7 @@ class PyXrefMixin: ) -> Node: # we use inliner=None to make sure we get the old behaviour with a single # pending_xref node - result = super().make_xref( # type: ignore[misc] + result = super().make_xref( # type: ignore[misc] # ty: ignore[unresolved-attribute] rolename, domain, target, @@ -88,13 +88,13 @@ class PyXrefMixin: result['reftarget'] = reftarget result.clear() - result += innernode(reftitle, reftitle) # type: ignore[call-arg] + result += innernode(reftitle, reftitle) # type: ignore[call-arg] # ty: ignore[too-many-positional-arguments] elif env.config.python_use_unqualified_type_names: children = result.children result.clear() shortname = target.rpartition('.')[-1] - textnode = innernode('', shortname) # type: ignore[call-arg] + textnode = innernode('', shortname) # type: ignore[call-arg] # ty: ignore[too-many-positional-arguments] contnodes = [ pending_xref_condition('', '', textnode, condition='resolved'), pending_xref_condition('', '', *children, condition='*'), @@ -129,7 +129,7 @@ class PyXrefMixin: contnode = nodes.Text(sub_target) if in_literal or self._delimiters_re.match(sub_target): - results.append(contnode or innernode(sub_target, sub_target)) # type: ignore[call-arg] + results.append(contnode or innernode(sub_target, sub_target)) # type: ignore[call-arg] # ty: ignore[too-many-positional-arguments] else: results.append( self.make_xref( diff --git a/sphinx/domains/std/__init__.py b/sphinx/domains/std/__init__.py index 0a26c63e92..290047523a 100644 --- a/sphinx/domains/std/__init__.py +++ b/sphinx/domains/std/__init__.py @@ -808,7 +808,7 @@ class StandardDomain(Domain): # set up enumerable nodes # create a copy for this instance - self.enumerable_nodes = copy(self.enumerable_nodes) # type: ignore[misc] + self.enumerable_nodes = copy(self.enumerable_nodes) # type: ignore[misc] # ty: ignore[invalid-attribute-access] for node, settings in env._registry.enumerable_nodes.items(): self.enumerable_nodes[node] = settings @@ -1113,12 +1113,12 @@ class StandardDomain(Domain): logger.warning( __('numfig is disabled. :numref: is ignored.'), location=node ) - return contnode # type: ignore[return-value] + return contnode # type: ignore[return-value] # ty: ignore[invalid-return-type] try: fignumber = self.get_fignumber(env, builder, figtype, docname, target_node) if fignumber is None: - return contnode # type: ignore[return-value] + return contnode # type: ignore[return-value] # ty: ignore[invalid-return-type] except ValueError: logger.warning( __( @@ -1127,7 +1127,7 @@ class StandardDomain(Domain): labelid, location=node, ) - return contnode # type: ignore[return-value] + return contnode # type: ignore[return-value] # ty: ignore[invalid-return-type] try: if node['refexplicit']: @@ -1137,7 +1137,7 @@ class StandardDomain(Domain): if figname is None and '{name}' in title: logger.warning(__('the link has no caption: %s'), title, location=node) - return contnode # type: ignore[return-value] + return contnode # type: ignore[return-value] # ty: ignore[invalid-return-type] else: fignum = '.'.join(map(str, fignumber)) if '{name}' in title or 'number' in title: @@ -1153,10 +1153,10 @@ class StandardDomain(Domain): logger.warning( __('invalid numfig_format: %s (%r)'), title, exc, location=node ) - return contnode # type: ignore[return-value] + return contnode # type: ignore[return-value] # ty: ignore[invalid-return-type] except TypeError: logger.warning(__('invalid numfig_format: %s'), title, location=node) - return contnode # type: ignore[return-value] + return contnode # type: ignore[return-value] # ty: ignore[invalid-return-type] return self.build_reference_node( fromdocname, @@ -1322,7 +1322,7 @@ class StandardDomain(Domain): key = (objtype, ltarget) if key in self.objects: docname, labelid = self.objects[key] - role = 'std:' + self.role_for_objtype(objtype) # type: ignore[operator] + role = 'std:' + self.role_for_objtype(objtype) # type: ignore[operator] # ty: ignore[unsupported-operator] results.append(( role, make_refnode(builder, fromdocname, docname, labelid, contnode), @@ -1450,7 +1450,7 @@ def warn_missing_reference( return None else: target = node['reftarget'] - if target not in domain.anonlabels: # type: ignore[attr-defined] + if target not in domain.anonlabels: # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] msg = __('undefined label: %r') else: msg = __( diff --git a/sphinx/environment/__init__.py b/sphinx/environment/__init__.py index 16c07b0918..c9bcae71da 100644 --- a/sphinx/environment/__init__.py +++ b/sphinx/environment/__init__.py @@ -670,7 +670,7 @@ class BuildEnvironment: docname: str, builder: Builder, *, - tags: Tags = ..., # type: ignore[assignment] + tags: Tags = ..., # type: ignore[assignment] # ty: ignore[invalid-parameter-default] doctree: nodes.document | None = None, prune_toctrees: bool = True, includehidden: bool = False, diff --git a/sphinx/environment/adapters/toctree.py b/sphinx/environment/adapters/toctree.py index da811b480f..ff93294eea 100644 --- a/sphinx/environment/adapters/toctree.py +++ b/sphinx/environment/adapters/toctree.py @@ -72,7 +72,7 @@ def global_toctree_for_doc( docname: str, builder: Builder, *, - tags: Tags = ..., # type: ignore[assignment] + tags: Tags = ..., # type: ignore[assignment] # ty: ignore[invalid-parameter-default] collapse: bool = False, includehidden: bool = True, maxdepth: int = 0, @@ -196,7 +196,7 @@ def _resolve_toctree( caption_node.rawsource = toctree['rawcaption'] if hasattr(toctree, 'uid'): # move uid to caption_node to translate it - caption_node.uid = toctree.uid # type: ignore[attr-defined] + caption_node.uid = toctree.uid # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] del toctree.uid newnode.append(caption_node) newnode.extend(tocentries) @@ -490,7 +490,7 @@ def _toctree_copy[ET: Element]( depth = max(depth - 1, 1) copied = _toctree_copy_seq(node, depth, maxdepth, collapse, tags, initial_call=True) assert len(copied) == 1 - return copied[0] # type: ignore[return-value] + return copied[0] # type: ignore[return-value] # ty: ignore[invalid-return-type] def _toctree_copy_seq( diff --git a/sphinx/environment/collectors/metadata.py b/sphinx/environment/collectors/metadata.py index f318d5ade6..3fe29badf4 100644 --- a/sphinx/environment/collectors/metadata.py +++ b/sphinx/environment/collectors/metadata.py @@ -42,7 +42,7 @@ class MetadataCollector(EnvironmentCollector): return elif isinstance(doctree[index], nodes.docinfo): md = app.env.metadata[app.env.current_document.docname] - for node in doctree[index]: # type: ignore[attr-defined] + for node in doctree[index]: # type: ignore[attr-defined] # ty: ignore[not-iterable] # nodes are multiply inherited... if isinstance(node, nodes.authors): authors = cast('list[nodes.author]', node) diff --git a/sphinx/ext/autodoc/_dynamic/_loader.py b/sphinx/ext/autodoc/_dynamic/_loader.py index e594009c3a..68055dc542 100644 --- a/sphinx/ext/autodoc/_dynamic/_loader.py +++ b/sphinx/ext/autodoc/_dynamic/_loader.py @@ -177,7 +177,7 @@ def _make_props_from_imported_object( if objtype == 'module': try: - mod_origin = im.module.__spec__.origin # type: ignore[union-attr] + mod_origin = im.module.__spec__.origin # type: ignore[union-attr] # ty: ignore[unresolved-attribute] except AttributeError: file_path = None else: diff --git a/sphinx/ext/autodoc/_dynamic/_member_finder.py b/sphinx/ext/autodoc/_dynamic/_member_finder.py index 47413138f0..ab8e7ffa4e 100644 --- a/sphinx/ext/autodoc/_dynamic/_member_finder.py +++ b/sphinx/ext/autodoc/_dynamic/_member_finder.py @@ -584,7 +584,7 @@ def _best_object_type_for_member( if filtered: # return the highest priority object type - return max(filtered, key=operator.itemgetter(0))[1] # type: ignore[return-value] + return max(filtered, key=operator.itemgetter(0))[1] # type: ignore[return-value] # ty: ignore[invalid-return-type] return None diff --git a/sphinx/ext/autodoc/_dynamic/_preserve_defaults.py b/sphinx/ext/autodoc/_dynamic/_preserve_defaults.py index 082f3382cc..e46ff0b581 100644 --- a/sphinx/ext/autodoc/_dynamic/_preserve_defaults.py +++ b/sphinx/ext/autodoc/_dynamic/_preserve_defaults.py @@ -41,7 +41,7 @@ def _get_arguments(obj: Any, /) -> ast.arguments | None: if source.startswith((' ', '\t')): # 'obj' is in some indented block. module = ast.parse('if True:\n' + source) - subject = module.body[0].body[0] # type: ignore[attr-defined] + subject = module.body[0].body[0] # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] else: module = ast.parse(source) subject = module.body[0] diff --git a/sphinx/ext/autodoc/_dynamic/_signatures.py b/sphinx/ext/autodoc/_dynamic/_signatures.py index 5154b633bf..1389db69bc 100644 --- a/sphinx/ext/autodoc/_dynamic/_signatures.py +++ b/sphinx/ext/autodoc/_dynamic/_signatures.py @@ -626,7 +626,7 @@ def _annotate_to_first_argument( if params[first_arg_idx].annotation is Parameter.empty: params[first_arg_idx] = params[first_arg_idx].replace(annotation=typ) try: - dummy.__signature__ = sig.replace(parameters=params) # type: ignore[attr-defined] + dummy.__signature__ = sig.replace(parameters=params) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] return dummy except (AttributeError, TypeError): # failed to update signature (ex. built-in or extension types) diff --git a/sphinx/ext/autodoc/_dynamic/_type_comments.py b/sphinx/ext/autodoc/_dynamic/_type_comments.py index 30505a431e..fded96d1ef 100644 --- a/sphinx/ext/autodoc/_dynamic/_type_comments.py +++ b/sphinx/ext/autodoc/_dynamic/_type_comments.py @@ -136,7 +136,7 @@ def get_type_comment(obj: Any, bound_method: bool = False) -> Signature | None: # subject is placed inside class or block. To read its docstring, # this adds if-block before the declaration. module = ast.parse('if True:\n' + source, type_comments=True) - subject = cast('ast.FunctionDef', module.body[0].body[0]) # type: ignore[attr-defined] + subject = cast('ast.FunctionDef', module.body[0].body[0]) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] else: module = ast.parse(source, type_comments=True) subject = cast('ast.FunctionDef', module.body[0]) @@ -206,9 +206,9 @@ def signature_from_ast( params.pop(0) # merge type_comment into signature - if not_suppressed(type_comment.argtypes): # type: ignore[attr-defined] + if not_suppressed(type_comment.argtypes): # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] for i, param in enumerate(params): - params[i] = param.replace(annotation=type_comment.argtypes[i]) # type: ignore[attr-defined] + params[i] = param.replace(annotation=type_comment.argtypes[i]) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] if node.returns: return Signature(params, return_annotation=node.returns) diff --git a/sphinx/ext/autodoc/_generate.py b/sphinx/ext/autodoc/_generate.py index b5f9714fb1..f5f2bab191 100644 --- a/sphinx/ext/autodoc/_generate.py +++ b/sphinx/ext/autodoc/_generate.py @@ -210,7 +210,7 @@ def _add_directive_lines( autodoc_typehints=config.autodoc_typehints, directive_name=( 'py:attribute' - if props.obj_type in {'class', 'exception'} and props.doc_as_attr # type: ignore[attr-defined] + if props.obj_type in {'class', 'exception'} and props.doc_as_attr # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] else f'py:{props.obj_type}' ), is_final=is_final, @@ -267,7 +267,7 @@ def _document_members( *self.options.members*. """ has_members = props.obj_type == 'module' or ( - props.obj_type in {'class', 'exception'} and not props.doc_as_attr # type: ignore[attr-defined] + props.obj_type in {'class', 'exception'} and not props.doc_as_attr # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] ) if not has_members: return @@ -294,7 +294,7 @@ def _document_members( members_check_module = bool( props.obj_type == 'module' and want_all - and (options.ignore_module_all or props.all is None) # type: ignore[attr-defined] + and (options.ignore_module_all or props.all is None) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] ) for member_props, is_attr, member_indent in member_documenters: assert member_props.module_name diff --git a/sphinx/ext/autodoc/_legacy_class_based/_documenters.py b/sphinx/ext/autodoc/_legacy_class_based/_documenters.py index 1b72645ca8..b46befe487 100644 --- a/sphinx/ext/autodoc/_legacy_class_based/_documenters.py +++ b/sphinx/ext/autodoc/_legacy_class_based/_documenters.py @@ -1159,7 +1159,7 @@ class DocstringSignatureMixin: def _find_signature(self) -> tuple[str | None, str | None] | None: # candidates of the object name - valid_names = [self.objpath[-1]] # type: ignore[attr-defined] + valid_names = [self.objpath[-1]] # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] if isinstance(self, ClassDocumenter): valid_names.append('__init__') if hasattr(self.object, '__mro__'): @@ -1191,7 +1191,7 @@ class DocstringSignatureMixin: break # re-prepare docstring to ignore more leading indentation - directive = self.directive # type: ignore[attr-defined] + directive = self.directive # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] tab_width = directive.state.document.settings.tab_width self._new_docstrings[i] = prepare_docstring( '\n'.join(doclines[j + 1 :]), tab_width @@ -1213,17 +1213,17 @@ class DocstringSignatureMixin: def get_doc(self) -> list[list[str]] | None: if self._new_docstrings is not None: return self._new_docstrings - return super().get_doc() # type: ignore[misc] + return super().get_doc() # type: ignore[misc] # ty: ignore[unresolved-attribute] def format_signature(self, **kwargs: Any) -> str: self.args: str | None - if self.args is None and self.config.autodoc_docstring_signature: # type: ignore[attr-defined] + if self.args is None and self.config.autodoc_docstring_signature: # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] # only act if a signature is not explicitly given already, and if # the feature is enabled result = self._find_signature() if result is not None: self.args, self.retann = result - sig = super().format_signature(**kwargs) # type: ignore[misc] + sig = super().format_signature(**kwargs) # type: ignore[misc] # ty: ignore[unresolved-attribute] if self._signatures: return '\n'.join((sig, *self._signatures)) else: @@ -1236,7 +1236,7 @@ class DocstringStripSignatureMixin(DocstringSignatureMixin): """ def format_signature(self, **kwargs: Any) -> str: - if self.args is None and self.config.autodoc_docstring_signature: # type: ignore[attr-defined] + if self.args is None and self.config.autodoc_docstring_signature: # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] # only act if a signature is not explicitly given already, and if # the feature is enabled result = self._find_signature() @@ -1385,7 +1385,7 @@ class FunctionDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # typ if params[0].annotation is Parameter.empty: params[0] = params[0].replace(annotation=typ) try: - dummy.__signature__ = sig.replace(parameters=params) # type: ignore[attr-defined] + dummy.__signature__ = sig.replace(parameters=params) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] return dummy except (AttributeError, TypeError): # failed to update signature (ex. built-in or extension types) @@ -1993,7 +1993,7 @@ class UninitializedGlobalVariableMixin(DataDocumenterMixinBase): def import_object(self, raiseerror: bool = False) -> bool: try: - return super().import_object(raiseerror=True) # type: ignore[misc] + return super().import_object(raiseerror=True) # type: ignore[misc] # ty: ignore[unresolved-attribute] except ImportError as exc: # annotation only instance variable (PEP-526) try: @@ -2027,7 +2027,7 @@ class UninitializedGlobalVariableMixin(DataDocumenterMixinBase): if self.object is UNINITIALIZED_ATTR: return [] else: - return super().get_doc() # type: ignore[misc] + return super().get_doc() # type: ignore[misc] # ty: ignore[unresolved-attribute] class DataDocumenter( @@ -2186,11 +2186,11 @@ class MethodDocumenter(DocstringSignatureMixin, ClassLevelDocumenter): # type: obj = self.parent.__dict__.get(self.object_name, self.object) if inspect.isstaticmethod(obj, cls=self.parent, name=self.object_name): # document static members before regular methods - self.member_order -= 1 # type: ignore[misc] + self.member_order -= 1 # type: ignore[misc] # ty: ignore[invalid-attribute-access] elif inspect.isclassmethod(obj): # document class methods before static methods as # they usually behave as alternative constructors - self.member_order -= 2 # type: ignore[misc] + self.member_order -= 2 # type: ignore[misc] # ty: ignore[invalid-attribute-access] return ret def format_args(self, **kwargs: Any) -> str: @@ -2368,7 +2368,7 @@ class MethodDocumenter(DocstringSignatureMixin, ClassLevelDocumenter): # type: if params[1].annotation is Parameter.empty: params[1] = params[1].replace(annotation=typ) try: - dummy.__signature__ = sig.replace( # type: ignore[attr-defined] + dummy.__signature__ = sig.replace( # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] parameters=params ) return dummy @@ -2434,7 +2434,7 @@ class NonDataDescriptorMixin(DataDocumenterMixinBase): """ def import_object(self, raiseerror: bool = False) -> bool: - ret = super().import_object(raiseerror) # type: ignore[misc] + ret = super().import_object(raiseerror) # type: ignore[misc] # ty: ignore[unresolved-attribute] if ret and not inspect.isattributedescriptor(self.object): self.non_data_descriptor = True else: @@ -2454,7 +2454,7 @@ class NonDataDescriptorMixin(DataDocumenterMixinBase): # to display return None else: - return super().get_doc() # type: ignore[misc] + return super().get_doc() # type: ignore[misc] # ty: ignore[unresolved-attribute] class SlotsMixin(DataDocumenterMixinBase): @@ -2471,7 +2471,7 @@ class SlotsMixin(DataDocumenterMixinBase): return False def import_object(self, raiseerror: bool = False) -> bool: - ret = super().import_object(raiseerror) # type: ignore[misc] + ret = super().import_object(raiseerror) # type: ignore[misc] # ty: ignore[unresolved-attribute] if self.isslotsattribute(): self.object = SLOTSATTR @@ -2502,7 +2502,7 @@ class SlotsMixin(DataDocumenterMixinBase): ) return [] else: - return super().get_doc() # type: ignore[misc] + return super().get_doc() # type: ignore[misc] # ty: ignore[unresolved-attribute] class RuntimeInstanceAttributeMixin(DataDocumenterMixinBase): @@ -2521,7 +2521,7 @@ class RuntimeInstanceAttributeMixin(DataDocumenterMixinBase): def is_runtime_instance_attribute(self, parent: Any) -> bool: """Check the subject is an attribute defined in __init__().""" # An instance variable defined in __init__(). - if self.get_attribute_comment(parent, self.objpath[-1]): # type: ignore[attr-defined] + if self.get_attribute_comment(parent, self.objpath[-1]): # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] return True return self.is_runtime_instance_attribute_not_commented(parent) @@ -2548,7 +2548,7 @@ class RuntimeInstanceAttributeMixin(DataDocumenterMixinBase): attribute. """ try: - return super().import_object(raiseerror=True) # type: ignore[misc] + return super().import_object(raiseerror=True) # type: ignore[misc] # ty: ignore[unresolved-attribute] except ImportError as exc: try: with mock(self.config.autodoc_mock_imports): @@ -2556,7 +2556,7 @@ class RuntimeInstanceAttributeMixin(DataDocumenterMixinBase): self.modname, self.objpath[:-1], 'class', - attrgetter=self.get_attr, # type: ignore[attr-defined] + attrgetter=self.get_attr, # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] ) parent = ret[3] if self.is_runtime_instance_attribute(parent): @@ -2585,7 +2585,7 @@ class RuntimeInstanceAttributeMixin(DataDocumenterMixinBase): ): return None else: - return super().get_doc() # type: ignore[misc] + return super().get_doc() # type: ignore[misc] # ty: ignore[unresolved-attribute] class UninitializedInstanceAttributeMixin(DataDocumenterMixinBase): @@ -2610,14 +2610,14 @@ class UninitializedInstanceAttributeMixin(DataDocumenterMixinBase): the attribute. """ try: - return super().import_object(raiseerror=True) # type: ignore[misc] + return super().import_object(raiseerror=True) # type: ignore[misc] # ty: ignore[unresolved-attribute] except ImportError as exc: try: ret = import_object( self.modname, self.objpath[:-1], 'class', - attrgetter=self.get_attr, # type: ignore[attr-defined] + attrgetter=self.get_attr, # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] ) parent = ret[3] if self.is_uninitialized_instance_attribute(parent): @@ -2641,7 +2641,7 @@ class UninitializedInstanceAttributeMixin(DataDocumenterMixinBase): def get_doc(self) -> list[list[str]] | None: if self.object is UNINITIALIZED_ATTR: return None - return super().get_doc() # type: ignore[misc] + return super().get_doc() # type: ignore[misc] # ty: ignore[unresolved-attribute] class AttributeDocumenter( # type: ignore[misc] diff --git a/sphinx/ext/autosummary/generate.py b/sphinx/ext/autosummary/generate.py index dbdb8bd437..a014c279a4 100644 --- a/sphinx/ext/autosummary/generate.py +++ b/sphinx/ext/autosummary/generate.py @@ -136,7 +136,7 @@ class AutosummaryRenderer: if app.translator: self.env.add_extension('jinja2.ext.i18n') # ``install_gettext_translations`` is injected by the ``jinja2.ext.i18n`` extension - self.env.install_gettext_translations(app.translator) # type: ignore[attr-defined] + self.env.install_gettext_translations(app.translator) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] def render(self, template_name: str, context: dict[str, Any]) -> str: """Render a template file.""" diff --git a/sphinx/ext/doctest.py b/sphinx/ext/doctest.py index 96f49512c4..a9a55d53d7 100644 --- a/sphinx/ext/doctest.py +++ b/sphinx/ext/doctest.py @@ -273,7 +273,7 @@ class SphinxDocTestRunner(doctest.DocTestRunner): self, filename: str, module_globals: Any = None ) -> Any: # this is overridden from DocTestRunner adding the try-except below - m = self._DocTestRunner__LINECACHE_FILENAME_RE.match(filename) # type: ignore[attr-defined] + m = self._DocTestRunner__LINECACHE_FILENAME_RE.match(filename) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] if m and m.group('name') == self.test.name: try: example = self.test.examples[int(m.group('examplenum'))] @@ -284,7 +284,7 @@ class SphinxDocTestRunner(doctest.DocTestRunner): pass else: return example.source.splitlines(True) - return self.save_linecache_getlines(filename, module_globals) # type: ignore[attr-defined] + return self.save_linecache_getlines(filename, module_globals) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] # the new builder -- use sphinx-build.py -b doctest to run @@ -308,7 +308,7 @@ class DocTestBuilder(Builder): # for doctest examples but unusable for multi-statement code such # as setup code -- to be able to use doctest error reporting with # that code nevertheless, we monkey-patch the "compile" it uses. - doctest.compile = self.compile # type: ignore[attr-defined] + doctest.compile = self.compile # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] sys.path[0:0] = self.config.doctest_path @@ -433,8 +433,8 @@ class DocTestBuilder(Builder): self.test_runner = SphinxDocTestRunner(verbose=False, optionflags=self.opt) self.cleanup_runner = SphinxDocTestRunner(verbose=False, optionflags=self.opt) - self.test_runner._fakeout = self.setup_runner._fakeout # type: ignore[attr-defined] - self.cleanup_runner._fakeout = self.setup_runner._fakeout # type: ignore[attr-defined] + self.test_runner._fakeout = self.setup_runner._fakeout # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] + self.cleanup_runner._fakeout = self.setup_runner._fakeout # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] if self.config.doctest_test_doctest_blocks: condition = _condition_with_doctest @@ -444,24 +444,24 @@ class DocTestBuilder(Builder): if self.skipped(node): # type: ignore[arg-type] continue - source = node['test'] if 'test' in node else node.astext() # type: ignore[index, operator] + source = node['test'] if 'test' in node else node.astext() # type: ignore[index, operator] # ty: ignore[unsupported-operator] filename = self.get_filename_for_node(node, docname) line_number = self.get_line_number(node) if not source: logger.warning( __('no code/output in %s block at %s:%s'), - node.get('testnodetype', 'doctest'), # type: ignore[attr-defined] + node.get('testnodetype', 'doctest'), # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] filename, line_number, ) code = TestCode( source, - type=node.get('testnodetype', 'doctest'), # type: ignore[attr-defined] + type=node.get('testnodetype', 'doctest'), # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] filename=filename, lineno=line_number, # type: ignore[arg-type] - options=node.get('options'), # type: ignore[attr-defined] + options=node.get('options'), # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] ) - node_groups = node.get('groups', [self.config.doctest_test_doctest_blocks]) # type: ignore[attr-defined] + node_groups = node.get('groups', [self.config.doctest_test_doctest_blocks]) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] if '*' in node_groups: add_to_all_groups.append(code) continue @@ -586,7 +586,7 @@ class DocTestBuilder(Builder): # disable processing as it is not needed options[doctest.DONT_ACCEPT_BLANKLINE] = True # find out if we're testing an exception - m = parser._EXCEPTION_RE.match(output) # type: ignore[attr-defined] + m = parser._EXCEPTION_RE.match(output) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] if m: exc_msg = m.group('msg') else: diff --git a/sphinx/ext/graphviz.py b/sphinx/ext/graphviz.py index bd43e7936e..2c92efaf74 100644 --- a/sphinx/ext/graphviz.py +++ b/sphinx/ext/graphviz.py @@ -332,7 +332,7 @@ def render_dot( ) if not hasattr(self.builder, '_graphviz_warned_dot'): self.builder._graphviz_warned_dot = {} # type: ignore[union-attr] - self.builder._graphviz_warned_dot[graphviz_dot] = True # type: ignore[union-attr] + self.builder._graphviz_warned_dot[graphviz_dot] = True # type: ignore[union-attr] # ty: ignore[unresolved-attribute] return None, None except CalledProcessError as exc: raise GraphvizError( diff --git a/sphinx/ext/inheritance_diagram.py b/sphinx/ext/inheritance_diagram.py index f44bbb860a..6cad006686 100644 --- a/sphinx/ext/inheritance_diagram.py +++ b/sphinx/ext/inheritance_diagram.py @@ -437,7 +437,7 @@ class InheritanceDiagram(SphinxDirective): # references to real URLs later. These nodes will eventually be # removed from the doctree after we're done with them. for name in graph.get_all_class_names(): - refnodes, _x = class_role( # type: ignore[misc] + refnodes, _x = class_role( # type: ignore[misc] # ty: ignore[call-non-callable] 'class', f':class:`{name}`', name, 0, self.state.inliner ) node.extend(refnodes) diff --git a/sphinx/ext/intersphinx/_shared.py b/sphinx/ext/intersphinx/_shared.py index cbedbf1b38..c21c16efe5 100644 --- a/sphinx/ext/intersphinx/_shared.py +++ b/sphinx/ext/intersphinx/_shared.py @@ -119,10 +119,10 @@ class InventoryAdapter: if not hasattr(env, 'intersphinx_cache'): # initial storage when fetching inventories before processing - self.env.intersphinx_cache = {} # type: ignore[attr-defined] + self.env.intersphinx_cache = {} # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] - self.env.intersphinx_inventory = {} # type: ignore[attr-defined] - self.env.intersphinx_named_inventory = {} # type: ignore[attr-defined] + self.env.intersphinx_inventory = {} # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] + self.env.intersphinx_named_inventory = {} # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] @property def cache(self) -> dict[InventoryURI, InventoryCacheEntry]: @@ -133,16 +133,16 @@ class InventoryAdapter: - Element two is a time value for cache invalidation, an integer. - Element three is the loaded remote inventory of type :class:`!Inventory`. """ - return self.env.intersphinx_cache # type: ignore[attr-defined] + return self.env.intersphinx_cache # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] @property def main_inventory(self) -> Inventory: - return self.env.intersphinx_inventory # type: ignore[attr-defined] + return self.env.intersphinx_inventory # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] @property def named_inventory(self) -> dict[InventoryName, Inventory]: - return self.env.intersphinx_named_inventory # type: ignore[attr-defined] + return self.env.intersphinx_named_inventory # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] def clear(self) -> None: - self.env.intersphinx_inventory.clear() # type: ignore[attr-defined] - self.env.intersphinx_named_inventory.clear() # type: ignore[attr-defined] + self.env.intersphinx_inventory.clear() # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] + self.env.intersphinx_named_inventory.clear() # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] diff --git a/sphinx/ext/mathjax.py b/sphinx/ext/mathjax.py index 35766ddcac..8f51afcf8f 100644 --- a/sphinx/ext/mathjax.py +++ b/sphinx/ext/mathjax.py @@ -87,7 +87,7 @@ def install_mathjax( ) -> None: if app.builder.format != 'html': return - if app.builder.math_renderer_name != 'mathjax': # type: ignore[attr-defined] + if app.builder.math_renderer_name != 'mathjax': # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] return if not app.config.mathjax_path: msg = 'mathjax_path config value must be set for the mathjax extension to work' diff --git a/sphinx/ext/napoleon/__init__.py b/sphinx/ext/napoleon/__init__.py index 9509a4f7d5..19006870eb 100644 --- a/sphinx/ext/napoleon/__init__.py +++ b/sphinx/ext/napoleon/__init__.py @@ -272,6 +272,23 @@ class Config: """ + napoleon_google_docstring: bool + napoleon_numpy_docstring: bool + napoleon_include_init_with_doc: bool + napoleon_include_private_with_doc: bool + napoleon_include_special_with_doc: bool + napoleon_use_admonition_for_examples: bool + napoleon_use_admonition_for_notes: bool + napoleon_use_admonition_for_references: bool + napoleon_use_ivar: bool + napoleon_use_param: bool + napoleon_use_rtype: bool + napoleon_use_keyword: bool + napoleon_preprocess_types: bool + napoleon_type_aliases: dict[str, str] | None + napoleon_custom_sections: Sequence[str | tuple[str, str]] | None + napoleon_attr_annotations: bool + _config_values: Sequence[tuple[str, bool | None, _ConfigRebuild, Set[type]]] = ( ('napoleon_google_docstring', True, 'env', frozenset({bool})), ('napoleon_numpy_docstring', True, 'env', frozenset({bool})), diff --git a/sphinx/ext/napoleon/docstring.py b/sphinx/ext/napoleon/docstring.py index 6c866f3db4..3293fd1feb 100644 --- a/sphinx/ext/napoleon/docstring.py +++ b/sphinx/ext/napoleon/docstring.py @@ -21,6 +21,7 @@ if TYPE_CHECKING: from sphinx.application import Sphinx from sphinx.config import Config as SphinxConfig from sphinx.ext.autodoc._property_types import _AutodocObjType + from sphinx.ext.napoleon import Config as NapoleonConfig logger = logging.getLogger(__name__) @@ -234,7 +235,7 @@ def _convert_type_spec( } converted = ''.join( - converters.get(type_)(token) # type: ignore[misc] + converters.get(type_)(token) # type: ignore[misc] # ty: ignore[call-non-callable] for token, type_ in types ) @@ -328,7 +329,7 @@ class GoogleDocstring: def __init__( self, docstring: str | list[str], - config: SphinxConfig | None = None, + config: SphinxConfig | NapoleonConfig | None = None, app: Sphinx | None = None, what: _AutodocObjType | Literal['object'] = 'object', name: str = '', @@ -337,13 +338,13 @@ class GoogleDocstring: ) -> None: self._app = app if config: - self._config = config + self._config: SphinxConfig | NapoleonConfig = config elif app: self._config = app.config else: from sphinx.ext.napoleon import Config - self._config = Config() # type: ignore[assignment] + self._config = Config() if what == 'object': if inspect.isclass(obj): @@ -1210,7 +1211,7 @@ class NumpyDocstring(GoogleDocstring): def __init__( self, docstring: str | list[str], - config: SphinxConfig | None = None, + config: SphinxConfig | NapoleonConfig | None = None, app: Sphinx | None = None, what: _AutodocObjType | Literal['object'] = 'object', name: str = '', diff --git a/sphinx/ext/viewcode.py b/sphinx/ext/viewcode.py index e3e302563c..5ec6800f11 100644 --- a/sphinx/ext/viewcode.py +++ b/sphinx/ext/viewcode.py @@ -118,7 +118,7 @@ def doctree_read(app: Sphinx, doctree: Node) -> None: env._viewcode_modules = {} # type: ignore[attr-defined] def has_tag(modname: str, fullname: str, docname: str, refname: str) -> bool: - entry = env._viewcode_modules.get(modname, None) # type: ignore[attr-defined] + entry = env._viewcode_modules.get(modname, None) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] if entry is False: return False @@ -128,7 +128,7 @@ def doctree_read(app: Sphinx, doctree: Node) -> None: analyzer = ModuleAnalyzer.for_module(modname) analyzer.find_tags() except Exception: - env._viewcode_modules[modname] = False # type: ignore[attr-defined] + env._viewcode_modules[modname] = False # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] return False code = analyzer.code @@ -138,7 +138,7 @@ def doctree_read(app: Sphinx, doctree: Node) -> None: if entry is None or entry[0] != code: entry = code, tags, {}, refname - env._viewcode_modules[modname] = entry # type: ignore[attr-defined] + env._viewcode_modules[modname] = entry # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] _, tags, used, _ = entry if fullname in tags: used[fullname] = docname @@ -188,11 +188,11 @@ def env_merge_info( env._viewcode_modules = {} # type: ignore[attr-defined] # now merge in the information from the subprocess for modname, entry in other._viewcode_modules.items(): # ty: ignore[unresolved-attribute] - if modname not in env._viewcode_modules: # type: ignore[attr-defined] - env._viewcode_modules[modname] = entry # type: ignore[attr-defined] + if modname not in env._viewcode_modules: # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] + env._viewcode_modules[modname] = entry # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] else: - if env._viewcode_modules[modname]: # type: ignore[attr-defined] - used = env._viewcode_modules[modname][2] # type: ignore[attr-defined] + if env._viewcode_modules[modname]: # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] + used = env._viewcode_modules[modname][2] # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] for fullname, docname in entry[2].items(): if fullname not in used: used[fullname] = docname @@ -285,7 +285,7 @@ def collect_pages(app: Sphinx) -> Iterator[tuple[str, dict[str, Any], str]]: return if not is_supported_builder(env._builder_cls, env.config.viewcode_enable_epub): return - highlighter = app.builder.highlighter # type: ignore[attr-defined] + highlighter = app.builder.highlighter # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] urito = app.builder.get_relative_uri modnames = set(env._viewcode_modules) diff --git a/sphinx/highlighting.py b/sphinx/highlighting.py index 29cf9d26e8..ba429f418f 100644 --- a/sphinx/highlighting.py +++ b/sphinx/highlighting.py @@ -36,7 +36,7 @@ if TYPE_CHECKING: if tuple(map(int, pygments.__version__.split('.')[:2])) < (2, 18): from pygments.formatter import Formatter - Formatter.__class_getitem__ = classmethod(lambda cls, name: cls) # type: ignore[attr-defined] + Formatter.__class_getitem__ = classmethod(lambda cls, name: cls) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] logger = logging.getLogger(__name__) diff --git a/sphinx/io.py b/sphinx/io.py index 149083c501..9afab5e834 100644 --- a/sphinx/io.py +++ b/sphinx/io.py @@ -55,7 +55,7 @@ class SphinxBaseReader(standalone.Reader): # type: ignore[type-arg] # remove transforms which is not needed for Sphinx unused: list[type[Transform]] = [references.DanglingReferences] if docutils.__version_info__[:2] >= (1, 0): - unused.append(references.ReportUnreferencedTargets) # type: ignore[attr-defined] + unused.append(references.ReportUnreferencedTargets) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] for transform in unused: if transform in transforms: transforms.remove(transform) diff --git a/sphinx/jinja2glue.py b/sphinx/jinja2glue.py index b5b1de472f..f087234635 100644 --- a/sphinx/jinja2glue.py +++ b/sphinx/jinja2glue.py @@ -57,7 +57,7 @@ def _todim(val: int | str) -> str: return 'initial' elif str(val).isdigit(): return '0' if int(val) == 0 else '%spx' % val - return val # type: ignore[return-value] + return val # type: ignore[return-value] # ty: ignore[invalid-return-type] def _slice_index( @@ -210,7 +210,7 @@ class BuiltinTemplateLoader(TemplateBridge, BaseLoader): self.environment.globals['idgen'] = idgen if use_i18n: # ``install_gettext_translations`` is injected by the ``jinja2.ext.i18n`` extension - self.environment.install_gettext_translations(builder._translator) # type: ignore[attr-defined] + self.environment.install_gettext_translations(builder._translator) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] def render(self, template: str, context: dict[str, Any]) -> str: # type: ignore[override] return self.environment.get_template(template).render(context) @@ -248,5 +248,5 @@ class BuiltinTemplateLoader(TemplateBridge, BaseLoader): return loader.get_source(environment, template) except TemplateNotFound: pass - msg = f'{template!r} not found in {self.environment.loader.pathchain}' # type: ignore[union-attr] + msg = f'{template!r} not found in {self.environment.loader.pathchain}' # type: ignore[union-attr] # ty: ignore[unresolved-attribute] raise TemplateNotFound(msg) diff --git a/sphinx/locale/__init__.py b/sphinx/locale/__init__.py index 7d0586dace..e68e7a6255 100644 --- a/sphinx/locale/__init__.py +++ b/sphinx/locale/__init__.py @@ -207,7 +207,7 @@ def get_translation(catalog: str, namespace: str = 'general') -> Callable[[str], def gettext(message: str) -> str: if not is_translator_registered(catalog, namespace): # not initialized yet - return _TranslationProxy(catalog, namespace, message) # type: ignore[return-value] + return _TranslationProxy(catalog, namespace, message) # type: ignore[return-value] # ty: ignore[invalid-return-type] else: translator = get_translator(catalog, namespace) return translator.gettext(message) diff --git a/sphinx/parsers.py b/sphinx/parsers.py index 5731ccd6f6..80ae4db40a 100644 --- a/sphinx/parsers.py +++ b/sphinx/parsers.py @@ -6,6 +6,7 @@ from typing import TYPE_CHECKING import docutils.parsers import docutils.parsers.rst +import docutils.statemachine from docutils.parsers.rst import states from docutils.statemachine import StringList from docutils.transforms.universal import SmartQuotes diff --git a/sphinx/pycode/ast.py b/sphinx/pycode/ast.py index 7f7850f361..ee19b3df97 100644 --- a/sphinx/pycode/ast.py +++ b/sphinx/pycode/ast.py @@ -183,7 +183,7 @@ class _UnparseVisitor(ast.NodeVisitor): ) if is_simple_tuple(node.slice): - elts = ', '.join(self.visit(e) for e in node.slice.elts) # type: ignore[attr-defined] + elts = ', '.join(self.visit(e) for e in node.slice.elts) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] return f'{self.visit(node.value)}[{elts}]' return f'{self.visit(node.value)}[{self.visit(node.slice)}]' diff --git a/sphinx/pycode/parser.py b/sphinx/pycode/parser.py index f84494f7df..f77e25f099 100644 --- a/sphinx/pycode/parser.py +++ b/sphinx/pycode/parser.py @@ -58,31 +58,31 @@ def get_lvar_names(node: ast.AST, self: ast.arg | None = None) -> list[str]: if node_name in {'Constant', 'Index', 'Slice', 'Subscript'}: raise TypeError('%r does not create new variable' % node) if node_name == 'Name': - if self is None or node.id == self_id: # type: ignore[attr-defined] - return [node.id] # type: ignore[attr-defined] + if self is None or node.id == self_id: # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] + return [node.id] # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] else: raise TypeError('The assignment %r is not instance variable' % node) elif node_name in {'Tuple', 'List'}: members = [] - for elt in node.elts: # type: ignore[attr-defined] + for elt in node.elts: # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] with contextlib.suppress(TypeError): members.extend(get_lvar_names(elt, self)) return members elif node_name == 'Attribute': if ( - node.value.__class__.__name__ == 'Name' # type: ignore[attr-defined] + node.value.__class__.__name__ == 'Name' # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] and self - and node.value.id == self_id # type: ignore[attr-defined] + and node.value.id == self_id # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] ): # instance variable - return ['%s' % get_lvar_names(node.attr, self)[0]] # type: ignore[attr-defined] + return ['%s' % get_lvar_names(node.attr, self)[0]] # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] else: raise TypeError('The assignment %r is not instance variable' % node) elif node_name == 'str': - return [node] # type: ignore[list-item] + return [node] # type: ignore[list-item] # ty: ignore[invalid-return-type] elif node_name == 'Starred': - return get_lvar_names(node.value, self) # type: ignore[attr-defined] + return get_lvar_names(node.value, self) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] else: raise NotImplementedError('Unexpected node name %r' % node_name) @@ -557,22 +557,22 @@ class DefinitionFinder(TokenProcessor): def parse_definition(self, typ: str) -> None: """Parse AST of definition.""" name = self.fetch_token() - self.context.append(name.value) # type: ignore[union-attr] + self.context.append(name.value) # type: ignore[union-attr] # ty: ignore[unresolved-attribute] funcname = '.'.join(self.context) if self.decorator: start_pos = self.decorator.start[0] self.decorator = None else: - start_pos = name.start[0] # type: ignore[union-attr] + start_pos = name.start[0] # type: ignore[union-attr] # ty: ignore[unresolved-attribute] self.fetch_until([OP, ':']) - if self.fetch_token().match(COMMENT, NEWLINE): # type: ignore[union-attr] + if self.fetch_token().match(COMMENT, NEWLINE): # type: ignore[union-attr] # ty: ignore[unresolved-attribute] self.fetch_until(INDENT) self.indents.append((typ, funcname, start_pos)) else: # one-liner - self.add_definition(funcname, (typ, start_pos, name.end[0])) # type: ignore[union-attr] + self.add_definition(funcname, (typ, start_pos, name.end[0])) # type: ignore[union-attr] # ty: ignore[unresolved-attribute] self.context.pop() def finalize_block(self) -> None: @@ -580,7 +580,7 @@ class DefinitionFinder(TokenProcessor): definition = self.indents.pop() if definition[0] != 'other': typ, funcname, start_pos = definition - end_pos = self.current.end[0] - 1 # type: ignore[union-attr] + end_pos = self.current.end[0] - 1 # type: ignore[union-attr] # ty: ignore[unresolved-attribute] while emptyline_re.match(self.get_line(end_pos)): end_pos -= 1 diff --git a/sphinx/roles.py b/sphinx/roles.py index fdb997314f..620da6eb8d 100644 --- a/sphinx/roles.py +++ b/sphinx/roles.py @@ -599,7 +599,7 @@ def code_role( return [node], [] -code_role.options = { # type: ignore[attr-defined] +code_role.options = { # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] 'class': docutils.parsers.rst.directives.class_option, 'language': docutils.parsers.rst.directives.unchanged, } diff --git a/sphinx/search/ja.py b/sphinx/search/ja.py index 7045a31445..bcae7284bb 100644 --- a/sphinx/search/ja.py +++ b/sphinx/search/ja.py @@ -20,14 +20,14 @@ if TYPE_CHECKING: from typing import Any try: - import MeCab # type: ignore[import-not-found] + import MeCab # type: ignore[import-not-found] # ty: ignore[unresolved-import] native_module = True except ImportError: native_module = False try: - import janome.tokenizer # type: ignore[import-not-found] + import janome.tokenizer # type: ignore[import-not-found] # ty: ignore[unresolved-import] janome_module = True except ImportError: diff --git a/sphinx/search/zh.py b/sphinx/search/zh.py index 0fbd08e1a2..45bf68e7e3 100644 --- a/sphinx/search/zh.py +++ b/sphinx/search/zh.py @@ -15,7 +15,7 @@ if TYPE_CHECKING: from collections.abc import Iterator try: - import jieba # type: ignore[import-not-found] + import jieba # type: ignore[import-not-found] # ty: ignore[unresolved-import] jieba_load_userdict = jieba.load_userdict cut_for_search = jieba.cut_for_search diff --git a/sphinx/testing/util.py b/sphinx/testing/util.py index 28336bc86a..dbe27c0075 100644 --- a/sphinx/testing/util.py +++ b/sphinx/testing/util.py @@ -252,8 +252,8 @@ class SphinxTestAppWrapperForSkipBuilding(SphinxTestApp): def _clean_up_global_state() -> None: # clean up Docutils global state - directives._directives.clear() # type: ignore[attr-defined] - roles._roles.clear() # type: ignore[attr-defined] + directives._directives.clear() # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] + roles._roles.clear() # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] for node in additional_nodes: delattr(nodes.GenericNodeVisitor, f'visit_{node.__name__}') delattr(nodes.GenericNodeVisitor, f'depart_{node.__name__}') diff --git a/sphinx/theming.py b/sphinx/theming.py index 7f9212ede5..2200dd1f72 100644 --- a/sphinx/theming.py +++ b/sphinx/theming.py @@ -357,7 +357,7 @@ def _extract_zip(filename: Path, target_dir: Path, /) -> None: def _load_theme_toml(config_file_path: Path, /) -> _ThemeToml: c = tomllib.loads(config_file_path.read_text(encoding='utf-8')) - return {s: c[s] for s in ('theme', 'options') if s in c} # type: ignore[return-value] + return {s: c[s] for s in ('theme', 'options') if s in c} # type: ignore[return-value] # ty: ignore[invalid-return-type] def _validate_theme_toml(cfg: _ThemeToml, name: str) -> str: diff --git a/sphinx/transforms/__init__.py b/sphinx/transforms/__init__.py index f9f8765c4b..82ff33243b 100644 --- a/sphinx/transforms/__init__.py +++ b/sphinx/transforms/__init__.py @@ -386,7 +386,7 @@ class SphinxSmartQuotes(SmartQuotes, SphinxTransform): # TODO: TYPING: Upstream docutils should be updated so that # smartquotes_action accepts any iterable of characters # and can be overridden per-instance. - self.smartquotes_action = self.config.smartquotes_action # type: ignore[misc] + self.smartquotes_action = self.config.smartquotes_action # type: ignore[misc] # ty: ignore[invalid-attribute-access] super().apply() diff --git a/sphinx/transforms/i18n.py b/sphinx/transforms/i18n.py index b26a9217fa..e59c16d724 100644 --- a/sphinx/transforms/i18n.py +++ b/sphinx/transforms/i18n.py @@ -87,7 +87,7 @@ def _publish_msgstr( config.rst_prolog = rst_prolog try: - return doc[0] # type: ignore[return-value] + return doc[0] # type: ignore[return-value] # ty: ignore[invalid-return-type] except IndexError: # empty node return doc @@ -417,7 +417,7 @@ class Locale(SphinxTransform): return catalogues = [getattr(catalog, '_catalog', None)] - while (catalog := catalog._fallback) is not None: # type: ignore[attr-defined] + while (catalog := catalog._fallback) is not None: # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] catalogues.append(getattr(catalog, '_catalog', None)) merged: dict[str, str] = {} catalogue: dict[str, str] diff --git a/sphinx/util/_serialise.py b/sphinx/util/_serialise.py index 667028a3eb..fd984f2355 100644 --- a/sphinx/util/_serialise.py +++ b/sphinx/util/_serialise.py @@ -46,7 +46,7 @@ def _stable_str_prep(obj: Any) -> dict[str, Any] | list[Any] | str: return dict(lst) if isinstance(obj, (list, tuple, set, frozenset)): # Convert to a sorted list - return sorted(map(_stable_str_prep, obj), key=str) # ty: ignore[no-matching-overload] + return sorted(map(_stable_str_prep, obj), key=str) if isinstance(obj, (type, types.FunctionType)): # The default repr() of functions includes the ID, which is not ideal. # We use the fully qualified name instead. diff --git a/sphinx/util/display.py b/sphinx/util/display.py index 0ba5e1c70c..be1b36c654 100644 --- a/sphinx/util/display.py +++ b/sphinx/util/display.py @@ -88,7 +88,7 @@ class progress_message: def __call__[**P, R](self, f: Callable[P, R]) -> Callable[P, R]: @functools.wraps(f) - def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: # type: ignore[return] + def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: # type: ignore[return] # ty: ignore[invalid-return-type] with self: return f(*args, **kwargs) diff --git a/sphinx/util/docfields.py b/sphinx/util/docfields.py index 7644694823..45f3e914a4 100644 --- a/sphinx/util/docfields.py +++ b/sphinx/util/docfields.py @@ -90,7 +90,7 @@ class Field: assert env is not None assert (inliner is None) == (location is None), (inliner, location) if not rolename: - return contnode or innernode(target, target) # type: ignore[call-arg] + return contnode or innernode(target, target) # type: ignore[call-arg] # ty: ignore[too-many-positional-arguments] # The domain is passed from DocFieldTransformer. So it surely exists. # So we don't need to take care the env.get_domain() raises an exception. role = env.get_domain(domain).role(rolename) @@ -108,7 +108,7 @@ class Field: reftype=rolename, reftarget=target, ) - refnode += contnode or innernode(target, target) # type: ignore[call-arg] + refnode += contnode or innernode(target, target) # type: ignore[call-arg] # ty: ignore[too-many-positional-arguments] env.get_domain(domain).process_field_xref(refnode) return refnode lineno = -1 diff --git a/sphinx/util/docutils.py b/sphinx/util/docutils.py index 1a32232301..daf9806be3 100644 --- a/sphinx/util/docutils.py +++ b/sphinx/util/docutils.py @@ -12,6 +12,9 @@ from typing import TYPE_CHECKING import docutils import docutils.frontend +import docutils.languages +import docutils.parsers.rst.languages +import docutils.utils import docutils.writers from docutils import nodes from docutils.io import FileOutput @@ -81,7 +84,7 @@ if docutils.__version_info__[:2] >= (1, 0): _READER_TRANSFORMS = [ transform for transform in standalone.Reader().get_transforms() - if transform is not references.ReportUnreferencedTargets # type: ignore[attr-defined] + if transform is not references.ReportUnreferencedTargets # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] ] else: _READER_TRANSFORMS = [ @@ -98,13 +101,13 @@ additional_nodes: set[type[Element]] = set() def docutils_namespace() -> Generator[None]: """Create namespace for reST parsers.""" try: - _directives = copy(directives._directives) # type: ignore[attr-defined] - _roles = copy(roles._roles) # type: ignore[attr-defined] + _directives = copy(directives._directives) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] + _roles = copy(roles._roles) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] yield finally: - directives._directives = _directives # type: ignore[attr-defined] - roles._roles = _roles # type: ignore[attr-defined] + directives._directives = _directives # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] + roles._roles = _roles # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] for node in list(additional_nodes): unregister_node(node) @@ -113,7 +116,7 @@ def docutils_namespace() -> Generator[None]: def is_directive_registered(name: str) -> bool: """Check the *name* directive is already registered.""" - return name in directives._directives # type: ignore[attr-defined] + return name in directives._directives # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] def register_directive(name: str, directive: type[Directive]) -> None: @@ -127,7 +130,7 @@ def register_directive(name: str, directive: type[Directive]) -> None: def is_role_registered(name: str) -> bool: """Check the *name* role is already registered.""" - return name in roles._roles # type: ignore[attr-defined] + return name in roles._roles # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] def register_role(name: str, role: RoleFunction) -> None: @@ -141,7 +144,7 @@ def register_role(name: str, role: RoleFunction) -> None: def unregister_role(name: str) -> None: """Unregister a role from docutils.""" - roles._roles.pop(name, None) # type: ignore[attr-defined] + roles._roles.pop(name, None) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] def is_node_registered(node: type[Element]) -> bool: @@ -156,7 +159,7 @@ def register_node(node: type[Element]) -> None: inside ``docutils_namespace()`` to prevent side-effects. """ if not hasattr(nodes.GenericNodeVisitor, 'visit_' + node.__name__): - nodes._add_node_class_names([node.__name__]) # type: ignore[attr-defined] + nodes._add_node_class_names([node.__name__]) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] additional_nodes.add(node) @@ -446,17 +449,17 @@ def switch_source_input( """Switch current source input of state temporarily.""" try: # remember the original ``get_source_and_line()`` method - gsal = state.memo.reporter.get_source_and_line # type: ignore[attr-defined] + gsal = state.memo.reporter.get_source_and_line # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] # replace it by new one state_machine: StateMachine[None] = StateMachine([], None) # type: ignore[arg-type] state_machine.input_lines = content - state.memo.reporter.get_source_and_line = state_machine.get_source_and_line # type: ignore[attr-defined] + state.memo.reporter.get_source_and_line = state_machine.get_source_and_line # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] yield finally: # restore the method - state.memo.reporter.get_source_and_line = gsal # type: ignore[attr-defined] + state.memo.reporter.get_source_and_line = gsal # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] class SphinxFileOutput(FileOutput): @@ -960,5 +963,5 @@ if docutils.__version_info__[:2] < (0, 22): else: from docutils.parsers.rst.roles import ( - normalize_options as _normalize_options, # ruff: ignore[unused-import] # ty: ignore[unresolved-import] + normalize_options as _normalize_options, # ruff: ignore[unused-import] ) diff --git a/sphinx/util/inspect.py b/sphinx/util/inspect.py index 7e251b50ca..140d95948e 100644 --- a/sphinx/util/inspect.py +++ b/sphinx/util/inspect.py @@ -446,7 +446,7 @@ def isproperty(obj: Any) -> TypeIs[property | cached_property[Any]]: def isgenericalias(obj: Any) -> TypeIs[types.GenericAlias]: """Check if the object is a generic alias.""" - return isinstance(obj, (types.GenericAlias, typing._BaseGenericAlias)) # type: ignore[attr-defined] + return isinstance(obj, (types.GenericAlias, typing._BaseGenericAlias)) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] def safe_getattr(obj: Any, name: str, *defargs: Any) -> Any: diff --git a/sphinx/util/matching.py b/sphinx/util/matching.py index 65cdb3e847..8b666ea26e 100644 --- a/sphinx/util/matching.py +++ b/sphinx/util/matching.py @@ -109,7 +109,7 @@ def patfilter(names: Iterable[str], pat: str) -> list[str]: if pat not in _pat_cache: _pat_cache[pat] = re.compile(_translate_pattern(pat)) match = _pat_cache[pat].match - return list(filter(match, names)) # ty: ignore[no-matching-overload] + return list(filter(match, names)) def get_matching_files( diff --git a/sphinx/util/nodes.py b/sphinx/util/nodes.py index b0acc320b6..c1c0131eec 100644 --- a/sphinx/util/nodes.py +++ b/sphinx/util/nodes.py @@ -139,7 +139,7 @@ def apply_source_workaround(node: Element) -> None: ) definition_list_item = node.parent node.source = definition_list_item.source - node.line = definition_list_item.line - 1 # type: ignore[operator] + node.line = definition_list_item.line - 1 # type: ignore[operator] # ty: ignore[unsupported-operator] node.rawsource = node.astext() # set 'classifier1' (or 'classifier2') elif isinstance(node, nodes.classifier) and not node.source: # docutils-0.15 fills in rawsource attribute, but not in source. @@ -235,7 +235,7 @@ def is_translatable(node: Node) -> bool: if isinstance(node, nodes.image) and (node.get('translatable') or node.get('alt')): return True - if isinstance(node, nodes.Inline) and 'translatable' not in node: # type: ignore[operator] + if isinstance(node, nodes.Inline) and 'translatable' not in node: # type: ignore[operator] # ty: ignore[unsupported-operator] # inline node must not be translated if 'translatable' is not set return False @@ -348,7 +348,7 @@ def extract_messages(doctree: Element) -> Iterable[tuple[Element, str]]: elif isinstance(node, nodes.meta): msg = node['content'] else: - text = node.rawsource # type: ignore[attr-defined] + text = node.rawsource # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] msg = _clean_extracted_message(text) # XXX nodes rendering empty are likely a bug in sphinx.addnodes diff --git a/sphinx/util/parallel.py b/sphinx/util/parallel.py index af50907ef1..11f0da7be0 100644 --- a/sphinx/util/parallel.py +++ b/sphinx/util/parallel.py @@ -41,9 +41,9 @@ class SerialTasks: result_func: Callable[[Any], Any] | None = None, ) -> None: if arg is not None: - res = task_func(arg) # type: ignore[call-arg] + res = task_func(arg) # type: ignore[call-arg] # ty: ignore[too-many-positional-arguments] else: - res = task_func() # type: ignore[call-arg] + res = task_func() # type: ignore[call-arg] # ty: ignore[missing-argument] if result_func: result_func(res) @@ -78,9 +78,9 @@ class ParallelTasks: collector = logging.LogCollector() with collector.collect(): if arg is None: - ret = func() # type: ignore[call-arg] + ret = func() # type: ignore[call-arg] # ty: ignore[missing-argument] else: - ret = func(arg) # type: ignore[call-arg] + ret = func(arg) # type: ignore[call-arg] # ty: ignore[too-many-positional-arguments] failed = False except BaseException as err: failed = True @@ -101,7 +101,7 @@ class ParallelTasks: self._args[tid] = arg precv, psend = multiprocessing.Pipe(False) context: Any = multiprocessing.get_context('fork') - proc = context.Process(target=self._process, args=(psend, task_func, arg)) # ty: ignore[unresolved-attribute] + proc = context.Process(target=self._process, args=(psend, task_func, arg)) self._procs[tid] = proc self._precvs_waiting[tid] = precv try: diff --git a/sphinx/util/requests.py b/sphinx/util/requests.py index dd39ca83ff..571e1ee3e3 100644 --- a/sphinx/util/requests.py +++ b/sphinx/util/requests.py @@ -86,7 +86,7 @@ class _Session(requests.Session): method: str, url: str, _user_agent: str = '', - _tls_info: tuple[bool, str | dict[str, str] | None] = (), # type: ignore[assignment] + _tls_info: tuple[bool, str | dict[str, str] | None] = (), # type: ignore[assignment] # ty: ignore[invalid-parameter-default] **kwargs: Any, ) -> requests.Response: """Sends a request with an HTTP verb and url. diff --git a/sphinx/util/rst.py b/sphinx/util/rst.py index d6639b3c7a..b96ede95e8 100644 --- a/sphinx/util/rst.py +++ b/sphinx/util/rst.py @@ -57,7 +57,7 @@ def heading(env: Environment, text: str, level: int = 1) -> str: """Create a heading for *level*.""" assert level <= 3 # ``env.language`` is injected by ``sphinx.util.template.ReSTRenderer`` - width = textwidth(text, WIDECHARS[env.language]) # type: ignore[attr-defined] + width = textwidth(text, WIDECHARS[env.language]) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] sectioning_char = SECTIONING_CHARS[level - 1] return f'{text}\n{sectioning_char * width}' diff --git a/sphinx/util/template.py b/sphinx/util/template.py index c7bb399330..10f4124488 100644 --- a/sphinx/util/template.py +++ b/sphinx/util/template.py @@ -31,7 +31,7 @@ class BaseRenderer: self.env = SandboxedEnvironment(loader=loader, extensions=['jinja2.ext.i18n']) self.env.filters['repr'] = repr # ``install_gettext_translations`` is injected by the ``jinja2.ext.i18n`` extension - self.env.install_gettext_translations(get_translator()) # type: ignore[attr-defined] + self.env.install_gettext_translations(get_translator()) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] def render(self, template_name: str, context: dict[str, Any]) -> str: return self.env.get_template(template_name).render(context) diff --git a/sphinx/util/typing.py b/sphinx/util/typing.py index 3d25454723..04a08ab398 100644 --- a/sphinx/util/typing.py +++ b/sphinx/util/typing.py @@ -541,7 +541,7 @@ def stringify_annotation( and all(getattr(a, '__origin__', ...) is typing.Literal for a in annotation_args) ): # fmt: skip # special case to flatten a Union of Literals into a literal - flattened_args = typing.Literal[annotation_args].__args__ # type: ignore[attr-defined] + flattened_args = typing.Literal[annotation_args].__args__ # type: ignore[attr-defined] # ty: ignore[invalid-type-form] args = ', '.join( _format_literal_arg_stringify(a, mode=mode) for a in flattened_args ) diff --git a/sphinx/versioning.py b/sphinx/versioning.py index 02bc6edd05..5f53f43e8d 100644 --- a/sphinx/versioning.py +++ b/sphinx/versioning.py @@ -20,7 +20,7 @@ if TYPE_CHECKING: from sphinx.util.typing import ExtensionMetadata try: - import Levenshtein # type: ignore[import-not-found] + import Levenshtein # type: ignore[import-not-found] # ty: ignore[unresolved-import] IS_SPEEDUP = True except ImportError: @@ -41,7 +41,7 @@ def add_uids(doctree: Node, condition: Callable[[Node], bool]) -> Iterator[Node] A callable which returns either ``True`` or ``False`` for a given node. """ for node in doctree.findall(condition): - node.uid = uuid4().hex # type: ignore[attr-defined] + node.uid = uuid4().hex # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] yield node @@ -74,9 +74,9 @@ def merge_doctrees( if new_node is None: old_nodes.append(old_node) continue - ratio = get_ratio(old_node.rawsource, new_node.rawsource) # type: ignore[union-attr] + ratio = get_ratio(old_node.rawsource, new_node.rawsource) # type: ignore[union-attr] # ty: ignore[unresolved-attribute] if ratio == 0: - new_node.uid = old_node.uid # type: ignore[union-attr] + new_node.uid = old_node.uid # type: ignore[union-attr] # ty: ignore[unresolved-attribute] seen.add(new_node) else: ratios[old_node, new_node] = ratio @@ -87,9 +87,9 @@ def merge_doctrees( for old_node, new_node in product(old_nodes, new_nodes): if new_node in seen or (old_node, new_node) in ratios: continue - ratio = get_ratio(old_node.rawsource, new_node.rawsource) # type: ignore[union-attr] + ratio = get_ratio(old_node.rawsource, new_node.rawsource) # type: ignore[union-attr] # ty: ignore[unresolved-attribute] if ratio == 0: - new_node.uid = old_node.uid # type: ignore[union-attr] + new_node.uid = old_node.uid # type: ignore[union-attr] # ty: ignore[unresolved-attribute] seen.add(new_node) else: ratios[old_node, new_node] = ratio @@ -102,7 +102,7 @@ def merge_doctrees( else: seen.add(new_node) if ratio < VERSIONING_RATIO: - new_node.uid = old_node.uid # type: ignore[union-attr] + new_node.uid = old_node.uid # type: ignore[union-attr] # ty: ignore[unresolved-attribute] else: new_node.uid = uuid4().hex # type: ignore[union-attr] yield new_node diff --git a/sphinx/writers/html5.py b/sphinx/writers/html5.py index 6271f1f92f..fdb979aac9 100644 --- a/sphinx/writers/html5.py +++ b/sphinx/writers/html5.py @@ -984,7 +984,7 @@ class HTML5Translator(SphinxTranslator, BaseTranslator): else: node['classes'].append('row-odd') self.body.append(self.starttag(node, 'tr', '')) - node.column = 0 # type: ignore[attr-defined] + node.column = 0 # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] def visit_field_list(self, node: nodes.field_list) -> None: self._fieldlist_row_indices.append(0) diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py index a77b7f671f..ba7b3e9391 100644 --- a/sphinx/writers/latex.py +++ b/sphinx/writers/latex.py @@ -1315,7 +1315,7 @@ class LaTeXTranslator(SphinxTranslator): assert self.table is not None cells = [self.table.cell(self.table.row, i) for i in range(self.table.colcount)] underlined = [ - cell.row + cell.height == self.table.row + 1 # type: ignore[union-attr] + cell.row + cell.height == self.table.row + 1 # type: ignore[union-attr] # ty: ignore[unresolved-attribute] for cell in cells ] if all(underlined): @@ -1328,7 +1328,7 @@ class LaTeXTranslator(SphinxTranslator): if underlined[0] is False: i = 1 while i < self.table.colcount and underlined[i] is False: - if cells[i - 1].cell_id != cells[i].cell_id: # type: ignore[union-attr] + if cells[i - 1].cell_id != cells[i].cell_id: # type: ignore[union-attr] # ty: ignore[unresolved-attribute] self.body.append(r'\sphinxvlinecrossing{%d}' % i) i += 1 while i < self.table.colcount: @@ -1338,7 +1338,7 @@ class LaTeXTranslator(SphinxTranslator): i += j i += 1 while i < self.table.colcount and underlined[i] is False: - if cells[i - 1].cell_id != cells[i].cell_id: # type: ignore[union-attr] + if cells[i - 1].cell_id != cells[i].cell_id: # type: ignore[union-attr] # ty: ignore[unresolved-attribute] self.body.append(r'\sphinxvlinecrossing{%d}' % i) i += 1 self.body.append(r'\sphinxfixclines{%d}' % self.table.colcount) diff --git a/sphinx/writers/texinfo.py b/sphinx/writers/texinfo.py index e984defa15..0a391e2c23 100644 --- a/sphinx/writers/texinfo.py +++ b/sphinx/writers/texinfo.py @@ -293,7 +293,7 @@ class TexinfoTranslator(SphinxTranslator): for section in self.document.findall(nodes.section): # TODO: TYPING: Node.next_node() should accept the non-Node # mixin classes in docutils.nodes. - title = section.next_node(nodes.Titular) # type: ignore[type-var] + title = section.next_node(nodes.Titular) # type: ignore[type-var] # ty: ignore[no-matching-overload] assert isinstance(title, nodes.Node) name = title.astext() if title else '' section['node_name'] = add_node_name(name) @@ -894,7 +894,7 @@ class TexinfoTranslator(SphinxTranslator): except (KeyError, IndexError) as exc: raise nodes.SkipNode from exc # footnotes are repeated for each reference - footnode.walkabout(self) # type: ignore[union-attr] + footnode.walkabout(self) # type: ignore[union-attr] # ty: ignore[unresolved-attribute] raise nodes.SkipChildren def visit_citation(self, node: Element) -> None: diff --git a/sphinx/writers/text.py b/sphinx/writers/text.py index d0d7f1639f..9dcf050b0b 100644 --- a/sphinx/writers/text.py +++ b/sphinx/writers/text.py @@ -563,7 +563,7 @@ class TextTranslator(SphinxTranslator): else: char = '^' text = '' - text = ''.join(x[1] for x in self.states.pop() if x[0] == -1) # type: ignore[misc] + text = ''.join(x[1] for x in self.states.pop() if x[0] == -1) # type: ignore[misc] # ty: ignore[no-matching-overload] if self.add_secnumbers: text = self.get_section_number_string(node) + text self.stateindent.pop() diff --git a/tests/test_builders/test_build_linkcheck.py b/tests/test_builders/test_build_linkcheck.py index 1baf51145b..44b10f9cea 100644 --- a/tests/test_builders/test_build_linkcheck.py +++ b/tests/test_builders/test_build_linkcheck.py @@ -1346,7 +1346,7 @@ def test_connection_contention( get_adapter: mock.Mock, app: SphinxTestApp, capsys: pytest.CaptureFixture[str] ) -> None: # Create a shared, but limited-size, connection pool - import requests + import requests.adapters get_adapter.return_value = requests.adapters.HTTPAdapter(pool_maxsize=1) diff --git a/tests/test_builders/xpath_util.py b/tests/test_builders/xpath_util.py index 6ea0891478..c345926ed2 100644 --- a/tests/test_builders/xpath_util.py +++ b/tests/test_builders/xpath_util.py @@ -70,7 +70,7 @@ def check_xpath( # https://github.com/astral-sh/ty/issues/117 # callable(...) does not currently narrow in ty. - rex = re.compile(check) # ty: ignore[no-matching-overload] + rex = re.compile(check) if be_found: if any(rex.search(_get_text(node)) for node in nodes): return diff --git a/tests/test_directives/test_directive_only.py b/tests/test_directives/test_directive_only.py index d5451c6b7c..c59de9f97f 100644 --- a/tests/test_directives/test_directive_only.py +++ b/tests/test_directives/test_directive_only.py @@ -23,7 +23,7 @@ def test_sectioning(app: SphinxTestApp) -> None: parts = [_get_sections(n) for n in doctree.children if isinstance(n, nodes.section)] for i, section in enumerate(parts): _test_sections(f'{i + 1}.', section, 4) - actual_headings = '\n'.join(p[0] for p in parts) # type: ignore[misc] + actual_headings = '\n'.join(p[0] for p in parts) # type: ignore[misc] # ty: ignore[no-matching-overload] assert len(parts) == 4, ( f'Expected 4 document level headings, got:\n{actual_headings}' ) diff --git a/tests/test_ext_autodoc/test_ext_autodoc_automodule.py b/tests/test_ext_autodoc/test_ext_autodoc_automodule.py index 6fad349a13..4a2b05de66 100644 --- a/tests/test_ext_autodoc/test_ext_autodoc_automodule.py +++ b/tests/test_ext_autodoc/test_ext_autodoc_automodule.py @@ -230,7 +230,7 @@ def test_subclass_of_mocked_object() -> None: for name in ('args', 'kwargs'): parameters[name] = parameters[name].replace(annotation=typing.Any) sig = sig.replace(parameters=tuple(parameters.values())) - _MockObject.__new__.__signature__ = sig # type: ignore[attr-defined] + _MockObject.__new__.__signature__ = sig # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] options = {'members': None} actual = do_autodoc('module', 'target.need_mocks', config=config, options=options) diff --git a/tests/test_ext_autodoc/test_ext_autodoc_mock.py b/tests/test_ext_autodoc/test_ext_autodoc_mock.py index 01498f418e..2f3d42f45a 100644 --- a/tests/test_ext_autodoc/test_ext_autodoc_mock.py +++ b/tests/test_ext_autodoc/test_ext_autodoc_mock.py @@ -131,10 +131,10 @@ def test_abc_MockObject(): def __init__(self): pass - class Derived(Base, mock.SubClass): # ty: ignore[unsupported-base] + class Derived(Base, mock.SubClass): pass - obj = Derived() + obj = Derived() # ty: ignore[call-non-callable] assert isinstance(obj, Base) assert isinstance(obj, _MockObject) assert isinstance(obj.some_method(), Derived) diff --git a/tests/test_ext_autodoc/test_ext_autodoc_signatures.py b/tests/test_ext_autodoc/test_ext_autodoc_signatures.py index e260257e5f..2492375a88 100644 --- a/tests/test_ext_autodoc/test_ext_autodoc_signatures.py +++ b/tests/test_ext_autodoc/test_ext_autodoc_signatures.py @@ -324,7 +324,7 @@ def test_autodoc_process_signature_typehints() -> None: events = FakeEvents() events.connect('autodoc-process-signature', process_signature) - def func(x: int, y: int) -> int: # type: ignore[empty-body] + def func(x: int, y: int) -> int: # type: ignore[empty-body] # ty: ignore[empty-body] pass props = _FunctionDefProperties( diff --git a/tests/test_ext_autosummary/test_ext_autosummary.py b/tests/test_ext_autosummary/test_ext_autosummary.py index 1f48193045..9794de1fe0 100644 --- a/tests/test_ext_autosummary/test_ext_autosummary.py +++ b/tests/test_ext_autosummary/test_ext_autosummary.py @@ -246,7 +246,7 @@ def test_escaping(app): @pytest.mark.sphinx('html', testroot='ext-autosummary', copy_test_root=True) def test_autosummary_generate_content_for_module(app): - import autosummary_dummy_module # type: ignore[import-not-found] + import autosummary_dummy_module # type: ignore[import-not-found] # ty: ignore[unresolved-import] template = Mock() @@ -471,7 +471,7 @@ def test_autosummary_generate_content_for_module_imported_members(app): @pytest.mark.sphinx('html', testroot='ext-autosummary', copy_test_root=True) def test_autosummary_generate_content_for_module_imported_members_inherited_module(app): - import autosummary_dummy_inherited_module # type: ignore[import-not-found] + import autosummary_dummy_inherited_module # type: ignore[import-not-found] # ty: ignore[unresolved-import] template = Mock() diff --git a/tests/test_ext_intersphinx/test_ext_intersphinx.py b/tests/test_ext_intersphinx/test_ext_intersphinx.py index 35f897045e..70a5038fb4 100644 --- a/tests/test_ext_intersphinx/test_ext_intersphinx.py +++ b/tests/test_ext_intersphinx/test_ext_intersphinx.py @@ -277,12 +277,14 @@ def test_missing_reference_pydomain(tmp_path, app): kwargs = {'py:module': 'module1'} node, contnode = fake_node('py', 'func', 'func', 'func()', **kwargs) rn = missing_reference(app, app.env, node, contnode) + assert isinstance(rn, nodes.reference) assert rn.astext() == 'func()' # py:attr context helps to search objects kwargs = {'py:module': 'module1'} node, contnode = fake_node('py', 'attr', 'Foo.bar', 'Foo.bar', **kwargs) rn = missing_reference(app, app.env, node, contnode) + assert isinstance(rn, nodes.reference) assert rn.astext() == 'Foo.bar' @@ -311,32 +313,38 @@ def test_missing_reference_stddomain(tmp_path, app): kwargs = {'std:program': 'ls'} node, contnode = fake_node('std', 'option', '-l', 'ls -l', **kwargs) rn = missing_reference(app, app.env, node, contnode) + assert isinstance(rn, nodes.reference) assert rn.astext() == 'ls -l' # refers inventory by name kwargs = {} node, contnode = fake_node('std', 'option', 'cmd:ls -l', '-l', **kwargs) rn = missing_reference(app, app.env, node, contnode) + assert isinstance(rn, nodes.reference) assert rn.astext() == '-l' # term reference (normal) node, contnode = fake_node('std', 'term', 'a term', 'a term') rn = missing_reference(app, app.env, node, contnode) + assert isinstance(rn, nodes.reference) assert rn.astext() == 'a term' # term reference (case insensitive) node, contnode = fake_node('std', 'term', 'A TERM', 'A TERM') rn = missing_reference(app, app.env, node, contnode) + assert isinstance(rn, nodes.reference) assert rn.astext() == 'A TERM' # label reference (normal) node, contnode = fake_node('std', 'ref', 'The-Julia-Domain', 'The-Julia-Domain') rn = missing_reference(app, app.env, node, contnode) + assert isinstance(rn, nodes.reference) assert rn.astext() == 'The Julia Domain' # label reference (case insensitive) node, contnode = fake_node('std', 'ref', 'the-julia-domain', 'the-julia-domain') rn = missing_reference(app, app.env, node, contnode) + assert isinstance(rn, nodes.reference) assert rn.astext() == 'The Julia Domain' @@ -431,6 +439,7 @@ def test_missing_reference_jsdomain(tmp_path, app): kwargs = {'js:module': 'foo', 'js:object': 'bar'} node, contnode = fake_node('js', 'meth', 'baz', 'baz()', **kwargs) rn = missing_reference(app, app.env, node, contnode) + assert isinstance(rn, nodes.reference) assert rn.astext() == 'baz()' @@ -801,7 +810,7 @@ def test_intersphinx_cache_limit(app, monkeypatch, cache_limit, expected_expired 'sphinx.ext.intersphinx._load._load_inventory', mock_fetch_inventory ) - for name, (uri, locations) in app.config.intersphinx_mapping.values(): + for name, (uri, locations) in app.config.intersphinx_mapping.values(): # ty: ignore[not-iterable] project = _IntersphinxProject(name=name, target_uri=uri, locations=locations) updated = _fetch_inventory_group( project=project, diff --git a/tests/test_extensions/test_ext_inheritance_diagram.py b/tests/test_extensions/test_ext_inheritance_diagram.py index ea43cea744..940e3fb3f3 100644 --- a/tests/test_extensions/test_ext_inheritance_diagram.py +++ b/tests/test_extensions/test_ext_inheritance_diagram.py @@ -333,7 +333,7 @@ def test_import_classes(rootdir): saved_path = sys.path.copy() sys.path.insert(0, str(rootdir / 'test-ext-inheritance_diagram')) try: - from example.sphinx import DummyClass # type: ignore[import-not-found] + from example.sphinx import DummyClass # type: ignore[import-not-found] # ty: ignore[unresolved-import] # got exception for unknown class or module with pytest.raises(InheritanceException): diff --git a/tests/test_highlighting.py b/tests/test_highlighting.py index 1fe1f59347..95485eab5f 100644 --- a/tests/test_highlighting.py +++ b/tests/test_highlighting.py @@ -24,7 +24,7 @@ if TYPE_CHECKING: if tuple(map(int, pygments.__version__.split('.')[:2])) < (2, 18): from pygments.formatter import Formatter - Formatter.__class_getitem__ = classmethod(lambda cls, name: cls) # type: ignore[attr-defined] + Formatter.__class_getitem__ = classmethod(lambda cls, name: cls) # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] if tuple(map(int, pygments.__version__.split('.')[:2])) < (2, 21): hsw = '"Hello sphinx world"' diff --git a/tests/test_intl/test_intl.py b/tests/test_intl/test_intl.py index db0598e7e5..3617032419 100644 --- a/tests/test_intl/test_intl.py +++ b/tests/test_intl/test_intl.py @@ -911,7 +911,7 @@ def mock_time_and_i18n() -> Iterator[tuple[pytest.MonkeyPatch, _MockClock]]: # see: https://github.com/pytest-dev/pytest/issues/363 # see: https://github.com/astral-sh/ty/issues/1787 - with pytest.MonkeyPatch.context() as mock: # ty: ignore[missing-argument] + with pytest.MonkeyPatch.context() as mock: clock: _MockClock if os.name == 'posix': clock = _MockUnixClock() diff --git a/tests/test_pycode/test_pycode.py b/tests/test_pycode/test_pycode.py index 4caf5019b9..738d5326b5 100644 --- a/tests/test_pycode/test_pycode.py +++ b/tests/test_pycode/test_pycode.py @@ -3,7 +3,7 @@ from __future__ import annotations import sys -from importlib.machinery import SourceFileLoader +from importlib.machinery import ModuleSpec, SourceFileLoader from pathlib import Path import pytest @@ -16,6 +16,7 @@ SPHINX_MODULE_PATH = Path(sphinx.__file__).resolve().with_suffix('.py') def test_ModuleAnalyzer_get_module_source() -> None: + assert isinstance(sphinx.__spec__, ModuleSpec) # type checking assert isinstance(sphinx.__spec__.loader, SourceFileLoader) # type checking assert ModuleAnalyzer.get_module_source('sphinx') == ( Path(sphinx.__file__), diff --git a/tests/test_transforms/test_transforms_post_transforms.py b/tests/test_transforms/test_transforms_post_transforms.py index de0b5510f2..96f94f0491 100644 --- a/tests/test_transforms/test_transforms_post_transforms.py +++ b/tests/test_transforms/test_transforms_post_transforms.py @@ -188,7 +188,7 @@ class TestSigElementFallbackTransform: visitor_methods = {f'visit_{tp.__name__}' for tp in desc_sig_elements_list} visitor_methods.update(f'visit_{name}' for name in add_visitor_method_for) class_dict = dict.fromkeys(visitor_methods, BaseCustomTranslatorClass.mark_node) - return type('CustomTranslatorClass', (BaseCustomTranslatorClass,), class_dict) # ty: ignore[invalid-return-type] + return type('CustomTranslatorClass', (BaseCustomTranslatorClass,), class_dict) @pytest.mark.parametrize( 'add_visitor_method_for', diff --git a/tests/test_util/test_util_inspect.py b/tests/test_util/test_util_inspect.py index 2deed7d5c2..b93cd2fea0 100644 --- a/tests/test_util/test_util_inspect.py +++ b/tests/test_util/test_util_inspect.py @@ -106,11 +106,11 @@ def _decorator(f): return wrapper -def forward_reference_in_args(x: Foo) -> None: # type: ignore[name-defined] # ruff: ignore[undefined-name] +def forward_reference_in_args(x: Foo) -> None: # type: ignore[name-defined] # ty: ignore[unresolved-reference] # ruff: ignore[undefined-name] pass -def forward_reference_in_return() -> Foo: # type: ignore[name-defined] # ruff: ignore[undefined-name] +def forward_reference_in_return() -> Foo: # type: ignore[name-defined] # ty: ignore[unresolved-reference] # ruff: ignore[undefined-name] pass @@ -119,7 +119,7 @@ def test_TypeAliasForwardRef(): sig_str = stringify_annotation(alias, 'fully-qualified-except-typing') assert sig_str == "TypeAliasForwardRef('example')" - alias = Optional[alias] # ruff: ignore[non-pep604-annotation-optional] + alias = Optional[alias] # ty: ignore[invalid-type-form] # ruff: ignore[non-pep604-annotation-optional] sig_str = stringify_annotation(alias, 'fully-qualified-except-typing') assert sig_str == "TypeAliasForwardRef('example') | None" @@ -913,7 +913,7 @@ def test_isattributedescriptor() -> None: try: # _testcapi module cannot be importable in some distro # See: https://github.com/sphinx-doc/sphinx/issues/9868 - import _testcapi # type: ignore[import-not-found] + import _testcapi # type: ignore[import-not-found] # ty: ignore[unresolved-import] # instancemethod (C-API) testinstancemethod = _testcapi.instancemethod(str.__repr__) diff --git a/tests/test_util/test_util_inspect_py314.py b/tests/test_util/test_util_inspect_py314.py index 154193e73a..7ee26fe93c 100644 --- a/tests/test_util/test_util_inspect_py314.py +++ b/tests/test_util/test_util_inspect_py314.py @@ -7,16 +7,16 @@ from sphinx.util import inspect from sphinx.util.typing import stringify_annotation try: - from annotationlib import ForwardRef # type: ignore[import-not-found] + from annotationlib import ForwardRef # type: ignore[import-not-found] # ty: ignore[unresolved-import] except ImportError: pytest.skip('Requires annotationlib (Python 3.14+).', allow_module_level=True) -def forward_reference_in_args(x: Foo) -> None: # type: ignore[name-defined] # ruff: ignore[undefined-name] +def forward_reference_in_args(x: Foo) -> None: # type: ignore[name-defined] # ty: ignore[unresolved-reference] # ruff: ignore[undefined-name] pass -def forward_reference_in_return() -> Foo: # type: ignore[name-defined] # ruff: ignore[undefined-name] +def forward_reference_in_return() -> Foo: # type: ignore[name-defined] # ty: ignore[unresolved-reference] # ruff: ignore[undefined-name] pass diff --git a/tests/test_util/test_util_rst.py b/tests/test_util/test_util_rst.py index 41854c2aec..26ff71a2a5 100644 --- a/tests/test_util/test_util_rst.py +++ b/tests/test_util/test_util_rst.py @@ -183,5 +183,5 @@ def test_heading() -> None: assert heading(env, 'русский язык', 1) == 'русский язык\n============' # language=ja: ambiguous - env.language = 'ja' # type: ignore[attr-defined] + env.language = 'ja' # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] assert heading(env, 'русский язык', 1) == 'русский язык\n=======================' diff --git a/tests/test_util/test_util_template.py b/tests/test_util/test_util_template.py index 03445653a0..76380f0af5 100644 --- a/tests/test_util/test_util_template.py +++ b/tests/test_util/test_util_template.py @@ -24,6 +24,6 @@ def test_ReSTRenderer_heading() -> None: assert r.render_string(template, {}) == 'русский язык\n------------' # language: ja - r.env.language = 'ja' # type: ignore[attr-defined] + r.env.language = 'ja' # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] template = '{{ "русский язык" | heading }}' assert r.render_string(template, {}) == 'русский язык\n=======================' diff --git a/tests/test_util/test_util_typing.py b/tests/test_util/test_util_typing.py index 5a36253ea4..d344c3e63d 100644 --- a/tests/test_util/test_util_typing.py +++ b/tests/test_util/test_util_typing.py @@ -514,7 +514,7 @@ def test_restify_broken_type_hints() -> None: def test_restify_mock() -> None: with mock(['unknown']): - import unknown # type: ignore[import-not-found] + import unknown # type: ignore[import-not-found] # ty: ignore[unresolved-import] assert restify(unknown) == ':py:class:`unknown`' assert restify(unknown.secret.Class) == ':py:class:`unknown.secret.Class`' @@ -730,10 +730,11 @@ def test_stringify_type_hints_pep_585(): # Mix typing and pep 585 ann_str = stringify_annotation( - tuple[List[dict[int, str]], str, ...], 'fully-qualified-except-typing' + tuple[List[dict[int, str]], str, ...], # ty: ignore[invalid-type-form] + 'fully-qualified-except-typing', ) assert ann_str == 'tuple[List[dict[int, str]], str, ...]' - ann_str = stringify_annotation(tuple[List[dict[int, str]], str, ...], 'smart') + ann_str = stringify_annotation(tuple[List[dict[int, str]], str, ...], 'smart') # ty: ignore[invalid-type-form] assert ann_str == 'tuple[~typing.List[dict[int, str]], str, ...]' diff --git a/tests/test_versioning.py b/tests/test_versioning.py index be88c02036..c4c9404e0f 100644 --- a/tests/test_versioning.py +++ b/tests/test_versioning.py @@ -35,7 +35,7 @@ def _setup_module(rootdir: Path, sphinx_test_tempdir: Path) -> Iterator[None]: app.connect('doctree-resolved', on_doctree_resolved) app.build() original = doctrees['original'] - original_uids = [n.uid for n in add_uids(original, is_paragraph)] # type: ignore[attr-defined] + original_uids = [n.uid for n in add_uids(original, is_paragraph)] # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] yield app.cleanup() @@ -128,6 +128,6 @@ def test_insert_similar() -> None: new_nodes = list(merge_doctrees(original, insert_similar, is_paragraph)) uids = [n.uid for n in insert_similar.findall(is_paragraph)] # type: ignore[attr-defined] assert len(new_nodes) == 1 - assert new_nodes[0].rawsource == 'Anyway I need more' # type: ignore[attr-defined] + assert new_nodes[0].rawsource == 'Anyway I need more' # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] assert original_uids[0] == uids[0] assert original_uids[1:] == uids[2:] diff --git a/ty.toml b/ty.toml index af28eb822d..6693210a1c 100644 --- a/ty.toml +++ b/ty.toml @@ -22,5 +22,7 @@ exclude = [ invalid-argument-type = "ignore" invalid-assignment = "ignore" invalid-method-override = "ignore" +invalid-mutable-override = "ignore" not-subscriptable = "ignore" possibly-missing-attribute = "ignore" +redundant-condition = "ignore" diff --git a/uv.lock b/uv.lock index 3c1fd5a676..5be3deeee9 100644 --- a/uv.lock +++ b/uv.lock @@ -1300,7 +1300,7 @@ types = [ { name = "mypy", specifier = "==1.19.1" }, { name = "pyrefly" }, { name = "pyright", specifier = "==1.1.407" }, - { name = "ty", specifier = "==0.0.10" }, + { name = "ty", specifier = "==0.0.90" }, { name = "types-colorama", specifier = "==0.4.15.20250801" }, { name = "types-defusedxml", specifier = "==0.7.0.20250822" }, { name = "types-docutils", specifier = "==0.22.3.20251115" }, @@ -1426,26 +1426,27 @@ wheels = [ [[package]] name = "ty" -version = "0.0.10" +version = "0.0.90" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/b7/85/97b5276baa217e05db2fe3d5c61e4dfd35d1d3d0ec95bfca1986820114e0/ty-0.0.10.tar.gz", hash = "sha256:0a1f9f7577e56cd508a8f93d0be2a502fdf33de6a7d65a328a4c80b784f4ac5f", size = 4892892, upload-time = "2026-01-07T23:00:23.572Z" } +sdist = { url = "https://files.pythonhosted.org/packages/68/b1/613b5534624442a9118828d7a9e54d50b16f0f5c8b67c80eb6623f33b921/ty-0.0.90.tar.gz", hash = "sha256:25cef63ec07a0254c2f5d885a63b001d0bfa437b20caa0a408f4f52e66b133e7", size = 7996206, upload-time = "2026-10-20T14:25:19.477Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/0c/7a/5a7147ce5231c3ccc55d6f945dabd7412e233e755d28093bfdec988ba595/ty-0.0.10-py3-none-linux_armv6l.whl", hash = "sha256:406a8ea4e648551f885629b75dc3f070427de6ed099af45e52051d4c68224829", size = 9835881, upload-time = "2026-01-07T22:08:17.492Z" }, - { url = "https://files.pythonhosted.org/packages/3e/7d/89f4d2277c938332d047237b47b11b82a330dbff4fff0de8574cba992128/ty-0.0.10-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:d6e0a733e3d6d3bce56d6766bc61923e8b130241088dc2c05e3c549487190096", size = 9696404, upload-time = "2026-01-07T22:08:37.965Z" }, - { url = "https://files.pythonhosted.org/packages/e8/cd/9dd49e6d40e54d4b7d563f9e2a432c4ec002c0673a81266e269c4bc194ce/ty-0.0.10-py3-none-macosx_11_0_arm64.whl", hash = "sha256:e4832f8879cb95fc725f7e7fcab4f22be0cf2550f3a50641d5f4409ee04176d4", size = 9181195, upload-time = "2026-01-07T22:59:07.187Z" }, - { url = "https://files.pythonhosted.org/packages/d2/b8/3e7c556654ba0569ed5207138d318faf8633d87e194760fc030543817c26/ty-0.0.10-py3-none-manylinux_2_24_aarch64.whl", hash = "sha256:6b58cc78e5865bc908f053559a80bb77cab0dc168aaad2e88f2b47955694b138", size = 9665002, upload-time = "2026-01-07T22:08:30.782Z" }, - { url = "https://files.pythonhosted.org/packages/98/96/410a483321406c932c4e3aa1581d1072b72cdcde3ae83cd0664a65c7b254/ty-0.0.10-py3-none-manylinux_2_24_armv7l.whl", hash = "sha256:83c6a514bb86f05005fa93e3b173ae3fde94d291d994bed6fe1f1d2e5c7331cf", size = 9664948, upload-time = "2026-01-07T23:04:14.655Z" }, - { url = "https://files.pythonhosted.org/packages/1f/5d/cba2ab3e2f660763a72ad12620d0739db012e047eaa0ceaa252bf5e94ebb/ty-0.0.10-py3-none-manylinux_2_24_i686.whl", hash = "sha256:2e43f71e357f8a4f7fc75e4753b37beb2d0f297498055b1673a9306aa3e21897", size = 10125401, upload-time = "2026-01-07T22:08:28.171Z" }, - { url = "https://files.pythonhosted.org/packages/a7/67/29536e0d97f204a2933122239298e754db4564f4ed7f34e2153012b954be/ty-0.0.10-py3-none-manylinux_2_24_ppc64le.whl", hash = "sha256:18be3c679965c23944c8e574be0635504398c64c55f3f0c46259464e10c0a1c7", size = 10714052, upload-time = "2026-01-07T22:08:20.098Z" }, - { url = "https://files.pythonhosted.org/packages/63/c8/82ac83b79a71c940c5dcacb644f526f0c8fdf4b5e9664065ab7ee7c0e4ec/ty-0.0.10-py3-none-manylinux_2_24_s390x.whl", hash = "sha256:5477981681440a35acdf9b95c3097410c547abaa32b893f61553dbc3b0096fff", size = 10395924, upload-time = "2026-01-07T22:08:22.839Z" }, - { url = "https://files.pythonhosted.org/packages/9e/4c/2f9ac5edbd0e67bf82f5cd04275c4e87cbbf69a78f43e5dcf90c1573d44e/ty-0.0.10-py3-none-manylinux_2_24_x86_64.whl", hash = "sha256:e206a23bd887574302138b33383ae1edfcc39d33a06a12a5a00803b3f0287a45", size = 10220096, upload-time = "2026-01-07T22:08:13.171Z" }, - { url = "https://files.pythonhosted.org/packages/04/13/3be2b7bfd53b9952b39b6f2c2ef55edeb1a2fea3bf0285962736ee26731c/ty-0.0.10-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:4e09ddb0d3396bd59f645b85eab20f9a72989aa8b736b34338dcb5ffecfe77b6", size = 9649120, upload-time = "2026-01-07T22:08:34.003Z" }, - { url = "https://files.pythonhosted.org/packages/93/e3/edd58547d9fd01e4e584cec9dced4f6f283506b422cdd953e946f6a8e9f0/ty-0.0.10-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:139d2a741579ad86a044233b5d7e189bb81f427eebce3464202f49c3ec0eba3b", size = 9686033, upload-time = "2026-01-07T22:08:40.967Z" }, - { url = "https://files.pythonhosted.org/packages/cc/bc/9d2f5fec925977446d577fb9b322d0e7b1b1758709f23a6cfc10231e9b84/ty-0.0.10-py3-none-musllinux_1_2_i686.whl", hash = "sha256:6bae10420c0abfe4601fbbc6ce637b67d0b87a44fa520283131a26da98f2e74c", size = 9841905, upload-time = "2026-01-07T23:04:21.694Z" }, - { url = "https://files.pythonhosted.org/packages/7c/b8/5acd3492b6a4ef255ace24fcff0d4b1471a05b7f3758d8910a681543f899/ty-0.0.10-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:7358bbc5d037b9c59c3a48895206058bcd583985316c4125a74dd87fd1767adb", size = 10320058, upload-time = "2026-01-07T22:08:25.645Z" }, - { url = "https://files.pythonhosted.org/packages/35/67/5b6906fccef654c7e801d6ac8dcbe0d493e1f04c38127f82a5e6d7e0aa0e/ty-0.0.10-py3-none-win32.whl", hash = "sha256:f51b6fd485bc695d0fdf555e69e6a87d1c50f14daef6cb980c9c941e12d6bcba", size = 9271806, upload-time = "2026-01-07T22:08:10.08Z" }, - { url = "https://files.pythonhosted.org/packages/42/36/82e66b9753a76964d26fd9bc3514ea0abce0a5ba5ad7d5f084070c6981da/ty-0.0.10-py3-none-win_amd64.whl", hash = "sha256:16deb77a72cf93b89b4d29577829613eda535fbe030513dfd9fba70fe38bc9f5", size = 10130520, upload-time = "2026-01-07T23:04:11.759Z" }, - { url = "https://files.pythonhosted.org/packages/63/52/89da123f370e80b587d2db8551ff31562c882d87b32b0e92b59504b709ae/ty-0.0.10-py3-none-win_arm64.whl", hash = "sha256:7495288bca7afba9a4488c9906466d648ffd3ccb6902bc3578a6dbd91a8f05f0", size = 9626026, upload-time = "2026-01-07T23:04:17.91Z" }, + { url = "https://files.pythonhosted.org/packages/b2/33/0e3395afa2c31c0e8e91547629858d2a5de213c69af237e6e50f37545565/ty-0.0.90-py3-none-linux_armv6l.whl", hash = "sha256:0dedb54977b40bc86638fec2c90eefd593f3a6683003a86b7e6cb67c17bcc476", size = 14281945, upload-time = "2026-10-20T14:24:21.018Z" }, + { url = "https://files.pythonhosted.org/packages/d7/fd/5d632b2f88d5c18991a4936da8643c7f204cfbc4980f8c7cd9080af988ad/ty-0.0.90-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:3d7c30ceaac76dfbfcf36b72d36272d21c3898e98fc4de296aa9cbae956dec9d", size = 13786355, upload-time = "2026-10-20T14:24:24.392Z" }, + { url = "https://files.pythonhosted.org/packages/79/08/0d2f37bb4f766ab9630f01b07f4d11f1f7a6a6188f920d5ca9fa8a4676b1/ty-0.0.90-py3-none-macosx_11_0_arm64.whl", hash = "sha256:c0b7e4d9ae0939294f0a18652de9ad7d81da2d7f567cf93f1edda1263008c124", size = 12856535, upload-time = "2026-10-20T14:24:27.386Z" }, + { url = "https://files.pythonhosted.org/packages/e4/77/70658f6b80c345ae0c12f2192a5cc89b8ca13eccfe06616b0fac3806c261/ty-0.0.90-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:76c4a095a86a132df374e652894fe08392aeb1601d6347e1eb4b58808094a302", size = 13696342, upload-time = "2026-10-20T14:24:30.413Z" }, + { url = "https://files.pythonhosted.org/packages/b9/3e/693049f93653d2f6412bb0c2c0af1d01675e31643af29bef7177d3ff7e79/ty-0.0.90-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4e24a8aa07c05d9d14648289e79a88b7c7c2c522c58b53bb5f466a6ba4704e22", size = 14014180, upload-time = "2026-10-20T14:24:33.783Z" }, + { url = "https://files.pythonhosted.org/packages/27/08/19e373f97501eaadc8fc42e8c07cd54a64e375fbcf1470797be13590d5ba/ty-0.0.90-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:40c3ea8fc1dfcf7502f71b93b12e80da1f7a8a5fd7e55ec9feabcf4ac39f72ea", size = 14935189, upload-time = "2026-10-20T14:24:37.459Z" }, + { url = "https://files.pythonhosted.org/packages/33/54/3331984f2c896a7383b6b18c86e968a63dd046baf503119a8e8e7682c752/ty-0.0.90-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1af75532bbe3e305089c30806fa5e804f8b01de231c1fa07918f7f3b335626da", size = 15311482, upload-time = "2026-10-20T14:24:40.87Z" }, + { url = "https://files.pythonhosted.org/packages/bf/f3/179acf8d730c2c864767ffcc9081f5ea6fdb1b34ef711f1bd226200e9cff/ty-0.0.90-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f09449b34d837a044dab043aeb2b4b6ff2d2cef5eaf8116c7c19d34cc2a16a21", size = 15278844, upload-time = "2026-10-20T14:24:44.539Z" }, + { url = "https://files.pythonhosted.org/packages/71/7e/661bc2fa20e0ac84c4d5f92e4c098ec667a0e920851a6d10c10a0251f0dc/ty-0.0.90-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cc868ffa7dfcb3169eea3ba7d634e5a3283c7133fb932c6e47a2e16620d26ca5", size = 14558774, upload-time = "2026-10-20T14:24:47.814Z" }, + { url = "https://files.pythonhosted.org/packages/f4/2e/3f65f61f4545f75255373be7646a606e004bb4cdc851e236bf17ca94bdc2/ty-0.0.90-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:e2405206533dc896a2b711e781f2955d5883d85536f4df0ac262fca6517103c2", size = 14788158, upload-time = "2026-10-20T14:24:51.223Z" }, + { url = "https://files.pythonhosted.org/packages/1e/10/3c91a529591667b89d63c86806bfe2ac56d6989c7e0a09ee0964b7512deb/ty-0.0.90-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:0dca4a29e8778285d2fc204af19254571486106fd14aed60769bfd272c795f6f", size = 13687177, upload-time = "2026-10-20T14:24:54.611Z" }, + { url = "https://files.pythonhosted.org/packages/21/b2/1b6d48606c67614bfb0c8e61a5d67a053ca1e3c5956ddb584f8569b8dc3d/ty-0.0.90-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:d004b8e4e898fead929eceea669b73936444671748e0dd44e624cc109346c0dd", size = 14027780, upload-time = "2026-10-20T14:24:59.045Z" }, + { url = "https://files.pythonhosted.org/packages/4f/c4/a0771debf725312524ca1434f8a146d37e573d45257ca4bebb9cc8e35bbc/ty-0.0.90-py3-none-musllinux_1_2_i686.whl", hash = "sha256:a6be182da4281b4581c4a1b27c6a0caebeed7212e4bdc98c6b8fe0d9bc36dea0", size = 14355890, upload-time = "2026-10-20T14:25:03.034Z" }, + { url = "https://files.pythonhosted.org/packages/a7/4c/036724b6936ffc38e28ff5e20ab7972d609c65a3dd9645f3d10f57cfd16f/ty-0.0.90-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:0ba6fe0a24ff4cbc5034f3aa1c88b3ad1397315dd3369357e694fd157a11864e", size = 14692306, upload-time = "2026-10-20T14:25:07.461Z" }, + { url = "https://files.pythonhosted.org/packages/a8/2a/c74fd5fc3fb5b046fe06a9067cabf5417b73e28249dc9af90ef72700f8fd/ty-0.0.90-py3-none-win32.whl", hash = "sha256:4c46a79caf84c4da0f7293e16bd769bd467c7cbc38015cac7608ab4e5ec8ba9c", size = 13235434, upload-time = "2026-10-20T14:25:10.545Z" }, + { url = "https://files.pythonhosted.org/packages/d2/54/be5cd6b17d8087a5e4c26892311c07e39d42b66c925b0f06cfc51a9ce83b/ty-0.0.90-py3-none-win_amd64.whl", hash = "sha256:8d77c16d20201b7a07ccaafb610eaf60488783dbba9865c4f9182e584f1426f8", size = 13855668, upload-time = "2026-10-20T14:25:13.648Z" }, + { url = "https://files.pythonhosted.org/packages/33/68/6dea089a897e8b314504eecc2633de3c8fe14f70e71a35606d14a2ba169e/ty-0.0.90-py3-none-win_arm64.whl", hash = "sha256:bfb63e74eeedb0a29d49cf58d611c540bfdfc0975dfce26efc6575bcf439208d", size = 13330853, upload-time = "2026-10-20T14:25:16.642Z" }, ] [[package]]