diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 04c3ec45b7..7a073f7f39 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -98,8 +98,9 @@ jobs: enable-cache: false - name: Install dependencies run: uv pip install -r pyproject.toml --group package --group test --group types + - run: echo "$(which python)" - name: Type check with ty - run: ty check --color=always + run: ty check --color=always --python="$(which python)" docs-lint: runs-on: ubuntu-latest diff --git a/sphinx/builders/html/__init__.py b/sphinx/builders/html/__init__.py index 16bf66aa9c..37becdeb92 100644 --- a/sphinx/builders/html/__init__.py +++ b/sphinx/builders/html/__init__.py @@ -1180,21 +1180,20 @@ class StandaloneHTMLBuilder(Builder): templatename = new_template # sort JS/CSS before rendering HTML - try: # NoQA: SIM105 + script_files: list[_JavaScript] = ctx['script_files'] + css_files: list[_CascadingStyleSheet] = ctx['css_files'] + + # Skip sorting if users modifies script_files directly (maybe via `html_context`). + # See: https://github.com/sphinx-doc/sphinx/issues/8885 + # + # Note: priority sorting feature will not work in this case. + with contextlib.suppress(AttributeError): # Convert script_files to list to support non-list script_files # See: https://github.com/sphinx-doc/sphinx/issues/8889 - ctx['script_files'] = sorted( - ctx['script_files'], key=lambda js: js.priority - ) - except AttributeError: - # Skip sorting if users modifies script_files directly (maybe via `html_context`). - # See: https://github.com/sphinx-doc/sphinx/issues/8885 - # - # Note: priority sorting feature will not work in this case. - pass + ctx['script_files'] = sorted(script_files, key=lambda js: js.priority) with contextlib.suppress(AttributeError): - ctx['css_files'] = sorted(ctx['css_files'], key=lambda css: css.priority) + ctx['css_files'] = sorted(css_files, key=lambda css: css.priority) try: output = self.templates.render(templatename, ctx) @@ -1242,7 +1241,8 @@ class StandaloneHTMLBuilder(Builder): logger.warning(__('error writing file %s: %s'), output_path, err) if self.copysource and ctx.get('sourcename'): # copy the source file for the "show source" link - source_file_path = self._sources_dir / ctx['sourcename'] + sourcename: str = ctx['sourcename'] + source_file_path = self._sources_dir / sourcename source_file_path.parent.mkdir(parents=True, exist_ok=True) copyfile(self.env.doc2path(pagename), source_file_path, force=True) diff --git a/sphinx/builders/xml.py b/sphinx/builders/xml.py index 7d8fa0636e..e1a50ca45b 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) + return ''.join(visitor.output) # ty: ignore[unresolved-attribute] def finish(self) -> None: pass diff --git a/sphinx/cmd/build.py b/sphinx/cmd/build.py index 58f3ad2674..a73717a71d 100644 --- a/sphinx/cmd/build.py +++ b/sphinx/cmd/build.py @@ -358,7 +358,7 @@ def _parse_logging( warning = TeeStripANSI(warning, warnfp) # type: ignore[assignment] error = warning - return status, warning, error, warnfp + return status, warning, error, warnfp # ty: ignore[invalid-return-type] def _parse_confoverrides( diff --git a/sphinx/cmd/quickstart.py b/sphinx/cmd/quickstart.py index a11856e497..a376270af7 100644 --- a/sphinx/cmd/quickstart.py +++ b/sphinx/cmd/quickstart.py @@ -245,8 +245,9 @@ def ask_user(d: dict[str, Any]) -> None: print(__('Enter the root path for documentation.')) d['path'] = do_prompt(__('Root path for the documentation'), '.', is_path) - while os.path.isfile(os.path.join(d['path'], 'conf.py')) or os.path.isfile( - os.path.join(d['path'], 'source', 'conf.py') + d_path: str = d['path'] + while os.path.isfile(os.path.join(d_path, 'conf.py')) or os.path.isfile( + os.path.join(d_path, 'source', 'conf.py') ): print() print( @@ -357,9 +358,12 @@ def ask_user(d: dict[str, Any]) -> None: __('Name of your master document (without suffix)'), 'index' ) + d_path = d['path'] + d_master: str = d['master'] + d_suffix: str = d['suffix'] while ( - os.path.isfile(os.path.join(d['path'], d['master'] + d['suffix'])) - or os.path.isfile(os.path.join(d['path'], 'source', d['master'] + d['suffix'])) + os.path.isfile(os.path.join(d_path, d_master + d_suffix)) + or os.path.isfile(os.path.join(d_path, 'source', d_master + d_suffix)) ): # fmt: skip print() print( @@ -368,7 +372,7 @@ def ask_user(d: dict[str, Any]) -> None: 'Error: the master file %s has already been found in the ' 'selected root path.' ) - % (d['master'] + d['suffix']) + % (d_master + d_suffix) ) ) print(__('sphinx-quickstart will not overwrite the existing file.')) diff --git a/sphinx/config.py b/sphinx/config.py index d7518f8cba..9b791702ec 100644 --- a/sphinx/config.py +++ b/sphinx/config.py @@ -162,7 +162,7 @@ class _Opt: other.valid_types, other.description, ) - return self_tpl > other_tpl + return self_tpl > other_tpl # ty: ignore[unsupported-operator] return NotImplemented def __hash__(self) -> int: @@ -619,7 +619,7 @@ def _validate_valid_types( if not valid_types: return frozenset() if isinstance(valid_types, (frozenset, ENUM)): - return valid_types + return valid_types # ty: ignore[invalid-return-type] if isinstance(valid_types, type): return frozenset((valid_types,)) if valid_types is Any: diff --git a/sphinx/domains/c/_symbol.py b/sphinx/domains/c/_symbol.py index 7ac555415a..0494305dd3 100644 --- a/sphinx/domains/c/_symbol.py +++ b/sphinx/domains/c/_symbol.py @@ -148,7 +148,8 @@ class Symbol: # Duplicate so don't add - will be reported in _add_symbols() return self._children_by_name[name] = child - self._children_by_docname.setdefault(child.docname, {})[name] = child + child_docname: str = child.docname + self._children_by_docname.setdefault(child_docname, {})[name] = child if child.ident.is_anonymous: self._anon_children.add(child) diff --git a/sphinx/domains/cpp/_ast.py b/sphinx/domains/cpp/_ast.py index d66a28ba21..90730196a2 100644 --- a/sphinx/domains/cpp/_ast.py +++ b/sphinx/domains/cpp/_ast.py @@ -4152,7 +4152,7 @@ class ASTTemplateParamNonType(ASTTemplateParam): assert isinstance(res, ASTIdentifier) return res else: - return None + return None # ty: ignore[invalid-return-type] def get_id( self, version: int, objectType: str | None = None, symbol: Symbol | None = None @@ -4576,7 +4576,7 @@ class ASTDeclaration(ASTBase): @property def function_params(self) -> list[ASTFunctionParameter]: if self.objectType != 'function': - return None + return None # ty: ignore[invalid-return-type] return self.declaration.function_params def get_id(self, version: int, prefixed: bool = True) -> str: diff --git a/sphinx/domains/cpp/_parser.py b/sphinx/domains/cpp/_parser.py index 2055a942c6..44e282a17a 100644 --- a/sphinx/domains/cpp/_parser.py +++ b/sphinx/domains/cpp/_parser.py @@ -151,7 +151,7 @@ class DefinitionParser(BaseParser): def _parse_string(self) -> str: if self.current_char != '"': - return None + return None # ty: ignore[invalid-return-type] start_pos = self.pos self.pos += 1 escape = False @@ -234,7 +234,7 @@ class DefinitionParser(BaseParser): ' resulting in multiple decoded characters.' ) return _udl(char_lit) - return None + return None # ty: ignore[invalid-return-type] def _parse_fold_or_paren_expression(self) -> ASTExpression | None: # "(" expression ")" @@ -323,7 +323,7 @@ class DefinitionParser(BaseParser): nn = self._parse_nested_name() if nn is not None: return ASTIdExpression(nn) - return None + return None # ty: ignore[invalid-return-type] def _parse_initializer_list( self, name: str, open: str, close: str @@ -333,7 +333,7 @@ class DefinitionParser(BaseParser): # | initializer-list ',' initializer-clause '...'[opt] self.skip_ws() if not self.skip_string_and_ws(open): - return None, None + return None, None # ty: ignore[invalid-return-type] if self.skip_string(close): return [], False @@ -369,7 +369,7 @@ class DefinitionParser(BaseParser): 'parenthesized expression-list', '(', ')' ) if exprs is None: - return None + return None # ty: ignore[invalid-return-type] return ASTParenExprList(exprs) def _parse_initializer_clause(self) -> ASTExpression | ASTBracedInitList: @@ -385,7 +385,7 @@ class DefinitionParser(BaseParser): 'braced-init-list', '{', '}' ) if exprs is None: - return None + return None # ty: ignore[invalid-return-type] return ASTBracedInitList(exprs, trailing_comma) def _parse_expression_list_or_braced_init_list( @@ -889,7 +889,7 @@ class DefinitionParser(BaseParser): # id-expression self.skip_ws() if not self.skip_string_and_ws('<'): - return None + return None # ty: ignore[invalid-return-type] if self.skip_string('>'): return ASTTemplateArgs([], False) prev_errors = [] @@ -1038,7 +1038,7 @@ class DefinitionParser(BaseParser): modifier = t self.skip_ws() if len(names) == 0: - return None + return None # ty: ignore[invalid-return-type] if typ in { 'auto', 'void', 'bool', diff --git a/sphinx/domains/cpp/_symbol.py b/sphinx/domains/cpp/_symbol.py index 7449e616a0..edc7ab6885 100644 --- a/sphinx/domains/cpp/_symbol.py +++ b/sphinx/domains/cpp/_symbol.py @@ -1103,7 +1103,7 @@ class Symbol: if s is None: if Symbol.debug_lookup: Symbol.debug_indent -= 2 - return None + return None # ty: ignore[invalid-return-type] if Symbol.debug_lookup: Symbol.debug_indent -= 2 return s @@ -1155,13 +1155,13 @@ class Symbol: # if it was a part of the qualification that could not be found if Symbol.debug_lookup: Symbol.debug_indent -= 2 - return None, None + return None, None # ty: ignore[invalid-return-type] res = list(lookup_result.symbols) if len(res) != 0: if Symbol.debug_lookup: Symbol.debug_indent -= 2 - return res, None + return res, None # ty: ignore[invalid-return-type] if lookup_result.parent_symbol.declaration is not None: if lookup_result.parent_symbol.declaration.objectType == 'templateParam': @@ -1180,9 +1180,9 @@ class Symbol: if Symbol.debug_lookup: Symbol.debug_indent -= 2 if symbol is not None: - return [symbol], None + return [symbol], None # ty: ignore[invalid-return-type] else: - return None, None + return None, None # ty: ignore[invalid-return-type] def find_declaration( self, diff --git a/sphinx/domains/std/__init__.py b/sphinx/domains/std/__init__.py index 3afad70d60..f88aa97b40 100644 --- a/sphinx/domains/std/__init__.py +++ b/sphinx/domains/std/__init__.py @@ -436,6 +436,7 @@ class Glossary(SphinxDirective): in_comment = False was_empty = True messages: list[Node] = [] + indent_len = 0 for line, (source, lineno) in zip( self.content, self.content.items, strict=True ): @@ -945,7 +946,7 @@ class StandardDomain(Domain): node = document.ids[labelid] if isinstance(node, nodes.target) and 'refid' in node: # indirect hyperlink targets - node = document.ids.get(node['refid']) # type: ignore[assignment] + node = document.ids[node['refid']] labelid = node['names'][0] if ( node.tagname == 'footnote' @@ -1043,7 +1044,7 @@ class StandardDomain(Domain): if typ == 'ref': resolver = self._resolve_ref_xref elif typ == 'numref': - resolver = self._resolve_numref_xref # type: ignore[assignment] + resolver = self._resolve_numref_xref elif typ == 'keyword': resolver = self._resolve_keyword_xref elif typ == 'doc': @@ -1092,7 +1093,7 @@ class StandardDomain(Domain): target: str, node: pending_xref, contnode: Element, - ) -> nodes.reference | Element | None: + ) -> nodes.reference | None: if target in self.labels: docname, labelid, figname = self.labels.get(target, ('', '', '')) else: @@ -1112,12 +1113,12 @@ class StandardDomain(Domain): logger.warning( __('numfig is disabled. :numref: is ignored.'), location=node ) - return contnode + return contnode # type: ignore[return-value] try: fignumber = self.get_fignumber(env, builder, figtype, docname, target_node) if fignumber is None: - return contnode + return contnode # type: ignore[return-value] except ValueError: logger.warning( __( @@ -1126,7 +1127,7 @@ class StandardDomain(Domain): labelid, location=node, ) - return contnode + return contnode # type: ignore[return-value] try: if node['refexplicit']: @@ -1136,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 + return contnode # type: ignore[return-value] else: fignum = '.'.join(map(str, fignumber)) if '{name}' in title or 'number' in title: @@ -1152,10 +1153,10 @@ class StandardDomain(Domain): logger.warning( __('invalid numfig_format: %s (%r)'), title, exc, location=node ) - return contnode + return contnode # type: ignore[return-value] except TypeError: logger.warning(__('invalid numfig_format: %s'), title, location=node) - return contnode + return contnode # type: ignore[return-value] return self.build_reference_node( fromdocname, diff --git a/sphinx/ext/autodoc/_sentinels.py b/sphinx/ext/autodoc/_sentinels.py index 5eb41daded..b7025163db 100644 --- a/sphinx/ext/autodoc/_sentinels.py +++ b/sphinx/ext/autodoc/_sentinels.py @@ -27,12 +27,12 @@ class _Sentinel: def __or__(self, other: object) -> _SpecialForm: from typing import Union - return Union[self, other] # NoQA: UP007 + return Union[self, other] # NoQA: UP007 # ty: ignore[invalid-type-form, invalid-return-type] def __ror__(self, other: object) -> _SpecialForm: from typing import Union - return Union[other, self] # NoQA: UP007 + return Union[other, self] # NoQA: UP007 # ty: ignore[invalid-type-form, invalid-return-type] def __getstate__(self) -> NoReturn: msg = f'Cannot pickle {self._name}' diff --git a/sphinx/ext/viewcode.py b/sphinx/ext/viewcode.py index af352eaaab..e3e302563c 100644 --- a/sphinx/ext/viewcode.py +++ b/sphinx/ext/viewcode.py @@ -187,7 +187,7 @@ def env_merge_info( if not hasattr(env, '_viewcode_modules'): env._viewcode_modules = {} # type: ignore[attr-defined] # now merge in the information from the subprocess - for modname, entry in other._viewcode_modules.items(): + 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] else: @@ -291,7 +291,7 @@ def collect_pages(app: Sphinx) -> Iterator[tuple[str, dict[str, Any], str]]: modnames = set(env._viewcode_modules) for modname, entry in status_iterator( - sorted(env._viewcode_modules.items()), + sorted(env._viewcode_modules.items()), # ty: ignore[unresolved-attribute] __('highlighting module code... '), 'blue', len(env._viewcode_modules), diff --git a/sphinx/search/zh.py b/sphinx/search/zh.py index 464e1e1fd4..0fbd08e1a2 100644 --- a/sphinx/search/zh.py +++ b/sphinx/search/zh.py @@ -16,8 +16,9 @@ if TYPE_CHECKING: try: import jieba # type: ignore[import-not-found] - from jieba import cut_for_search - from jieba import load_userdict as jieba_load_userdict + + jieba_load_userdict = jieba.load_userdict + cut_for_search = jieba.cut_for_search except ImportError: JIEBA_DEFAULT_DICT = '' diff --git a/sphinx/testing/fixtures.py b/sphinx/testing/fixtures.py index 255bc589de..c6fdebe6e2 100644 --- a/sphinx/testing/fixtures.py +++ b/sphinx/testing/fixtures.py @@ -143,7 +143,7 @@ def test_params(request: Any) -> dict[str, Any]: if result['shared_result'] and not isinstance(result['shared_result'], str): msg = 'You can only provide a string type of value for "shared_result"' - raise pytest.Exception(msg) + pytest.fail(msg) return result diff --git a/sphinx/util/_io.py b/sphinx/util/_io.py index 94ad9f8f0d..f363e1fc58 100644 --- a/sphinx/util/_io.py +++ b/sphinx/util/_io.py @@ -28,6 +28,6 @@ class TeeStripANSI: def flush(self) -> None: if hasattr(self.stream_term, 'flush'): - self.stream_term.flush() + self.stream_term.flush() # ty: ignore[call-non-callable] if hasattr(self.stream_file, 'flush'): - self.stream_file.flush() + self.stream_file.flush() # ty: ignore[call-non-callable] diff --git a/sphinx/util/_serialise.py b/sphinx/util/_serialise.py index 501a13bd71..fd984f2355 100644 --- a/sphinx/util/_serialise.py +++ b/sphinx/util/_serialise.py @@ -39,9 +39,11 @@ def stable_str(obj: Any, *, indent: int | None = None) -> str: def _stable_str_prep(obj: Any) -> dict[str, Any] | list[Any] | str: if isinstance(obj, dict): # Convert to a sorted dict - obj = [(_stable_str_prep(k), _stable_str_prep(v)) for k, v in obj.items()] - obj.sort() - return dict(obj) + lst: list[tuple[Any, Any]] = [ + (_stable_str_prep(k), _stable_str_prep(v)) for k, v in obj.items() + ] + lst.sort() + return dict(lst) if isinstance(obj, (list, tuple, set, frozenset)): # Convert to a sorted list return sorted(map(_stable_str_prep, obj), key=str) diff --git a/sphinx/util/docutils.py b/sphinx/util/docutils.py index 6aa7e324d4..e307d8829b 100644 --- a/sphinx/util/docutils.py +++ b/sphinx/util/docutils.py @@ -287,7 +287,7 @@ class CustomReSTDispatcher: lineno: int, reporter: Reporter, ) -> tuple[RoleFunction, list[system_message]]: - return self.role_func( + return self.role_func( # ty: ignore[invalid-return-type] role_name, language_module, # type: ignore[return-value] lineno, @@ -939,5 +939,5 @@ if docutils.__version_info__[:2] < (0, 22): else: from docutils.parsers.rst.roles import ( - normalize_options as _normalize_options, # NoQA: F401 + normalize_options as _normalize_options, # NoQA: F401 # ty: ignore[unresolved-import] ) diff --git a/sphinx/util/parallel.py b/sphinx/util/parallel.py index 3dd5e574c5..af50907ef1 100644 --- a/sphinx/util/parallel.py +++ b/sphinx/util/parallel.py @@ -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)) + proc = context.Process(target=self._process, args=(psend, task_func, arg)) # ty: ignore[unresolved-attribute] self._procs[tid] = proc self._precvs_waiting[tid] = precv try: diff --git a/tests/test_builders/xpath_util.py b/tests/test_builders/xpath_util.py index b926c1aefe..6ea0891478 100644 --- a/tests/test_builders/xpath_util.py +++ b/tests/test_builders/xpath_util.py @@ -68,7 +68,9 @@ def check_xpath( check(nodes) return - rex = re.compile(check) + # https://github.com/astral-sh/ty/issues/117 + # callable(...) does not currently narrow in ty. + rex = re.compile(check) # ty: ignore[no-matching-overload] if be_found: if any(rex.search(_get_text(node)) for node in nodes): return diff --git a/tests/test_directives/test_directive_other.py b/tests/test_directives/test_directive_other.py index 319f18f0b5..1aa370cce8 100644 --- a/tests/test_directives/test_directive_other.py +++ b/tests/test_directives/test_directive_other.py @@ -147,6 +147,7 @@ def test_toctree_class(app): app.env.find_files(app.config, app.builder) doctree = restructuredtext.parse(app, text, 'index') assert_node(doctree, [nodes.document, nodes.compound, addnodes.toctree]) + assert isinstance(doctree[0], nodes.compound) assert doctree[0].attributes['classes'] == ['toctree-wrapper', 'custom-toc'] @@ -209,5 +210,5 @@ def test_include_include_read_event_nested_includes(app): doctree = restructuredtext.parse(app, text, 'index') assert_node(doctree, addnodes.document) assert len(doctree.children) == 3 - assert_node(doctree.children[1], nodes.paragraph) + assert isinstance(doctree.children[1], nodes.paragraph) assert doctree.children[1].rawsource == 'The amazing foo.' diff --git a/tests/test_domains/test_domain_cpp.py b/tests/test_domains/test_domain_cpp.py index 5b056c6434..856f904430 100644 --- a/tests/test_domains/test_domain_cpp.py +++ b/tests/test_domains/test_domain_cpp.py @@ -51,7 +51,8 @@ def parse(name, string): parser.assert_end() # The scopedness would usually have been set by CPPEnumObject if name == 'enum': - ast.scoped = None # simulate unscoped enum + # simulate unscoped enum + ast.scoped = None # ty: ignore[unresolved-attribute] return ast diff --git a/tests/test_ext_autosummary/test_ext_autosummary.py b/tests/test_ext_autosummary/test_ext_autosummary.py index bb0c700815..af4ce87c22 100644 --- a/tests/test_ext_autosummary/test_ext_autosummary.py +++ b/tests/test_ext_autosummary/test_ext_autosummary.py @@ -301,7 +301,7 @@ def test_autosummary_generate_content_for_module(app): @pytest.mark.sphinx('html', testroot='ext-autosummary', copy_test_root=True) def test_autosummary_generate_content_for_module___all__(app): - import autosummary_dummy_module + import autosummary_dummy_module # ty: ignore[unresolved-import] template = Mock() app.config.autosummary_ignore_module_all = False @@ -347,7 +347,7 @@ def test_autosummary_generate_content_for_module___all__(app): @pytest.mark.sphinx('html', testroot='ext-autosummary', copy_test_root=True) def test_autosummary_generate_content_for_module_skipped(app): - import autosummary_dummy_module + import autosummary_dummy_module # ty: ignore[unresolved-import] template = Mock() @@ -394,7 +394,7 @@ def test_autosummary_generate_content_for_module_skipped(app): @pytest.mark.sphinx('html', testroot='ext-autosummary', copy_test_root=True) def test_autosummary_generate_content_for_module_imported_members(app): - import autosummary_dummy_module + import autosummary_dummy_module # ty: ignore[unresolved-import] template = Mock() diff --git a/tests/test_ext_napoleon/test_ext_napoleon_docstring.py b/tests/test_ext_napoleon/test_ext_napoleon_docstring.py index d582208f85..f894be526d 100644 --- a/tests/test_ext_napoleon/test_ext_napoleon_docstring.py +++ b/tests/test_ext_napoleon/test_ext_napoleon_docstring.py @@ -1862,7 +1862,7 @@ arg_ : type """ config = Config(napoleon_use_ivar=True) - config.strip_signature_backslash = True + config.strip_signature_backslash = True # ty: ignore[unresolved-attribute] app = mock.Mock() actual = NumpyDocstring(docstring, config, app, 'class') diff --git a/tests/test_extensions/test_ext_inheritance_diagram.py b/tests/test_extensions/test_ext_inheritance_diagram.py index f98d424eda..ea43cea744 100644 --- a/tests/test_extensions/test_ext_inheritance_diagram.py +++ b/tests/test_extensions/test_ext_inheritance_diagram.py @@ -9,6 +9,7 @@ from pathlib import Path from typing import TYPE_CHECKING import pytest +from docutils import nodes from sphinx.ext.inheritance_diagram import ( InheritanceDiagram, @@ -32,6 +33,7 @@ def test_inheritance_diagram(app: SphinxTestApp) -> None: def new_run(self): result = orig_run(self) node = result[0] + assert isinstance(node.document, nodes.document) source = Path(node.document.current_source).stem graphs[source] = node['graph'] return result diff --git a/tests/test_transforms/test_transforms_post_transforms.py b/tests/test_transforms/test_transforms_post_transforms.py index 1132a51e9a..2b839af336 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) + return type('CustomTranslatorClass', (BaseCustomTranslatorClass,), class_dict) # ty: ignore[invalid-return-type] @pytest.mark.parametrize( 'add_visitor_method_for', diff --git a/tests/test_util/test_util_typing.py b/tests/test_util/test_util_typing.py index 8ccf874ec9..d5fd2b1092 100644 --- a/tests/test_util/test_util_typing.py +++ b/tests/test_util/test_util_typing.py @@ -416,10 +416,10 @@ def test_restify_type_ForwardRef(): assert restify(ForwardRef('MyInt')) == ':py:class:`MyInt`' assert ( - restify(list[ForwardRef('MyInt')]) == ':py:class:`list`\\ [:py:class:`MyInt`]' + restify(list[ForwardRef('MyInt')]) == ':py:class:`list`\\ [:py:class:`MyInt`]' # ty: ignore[invalid-type-form] ) - ann_rst = restify(Tuple[dict[ForwardRef('MyInt'), str], list[List[int]]]) + ann_rst = restify(Tuple[dict[ForwardRef('MyInt'), str], list[List[int]]]) # ty: ignore[invalid-type-form] assert ann_rst == ( ':py:class:`~typing.Tuple`\\ [:py:class:`dict`\\ [:py:class:`MyInt`, :py:class:`str`], :py:class:`list`\\ [:py:class:`~typing.List`\\ [:py:class:`int`]]]' ) @@ -978,7 +978,7 @@ def test_stringify_broken_type_hints() -> None: def test_stringify_mock() -> None: with mock(['unknown']): - import unknown + import unknown # ty: ignore[unresolved-import] ann_str = stringify_annotation(unknown, 'fully-qualified-except-typing') assert ann_str == 'unknown' @@ -994,20 +994,21 @@ def test_stringify_type_ForwardRef(): assert stringify_annotation(ForwardRef('MyInt')) == 'MyInt' assert stringify_annotation(ForwardRef('MyInt'), 'smart') == 'MyInt' - assert stringify_annotation(list[ForwardRef('MyInt')]) == 'list[MyInt]' - assert stringify_annotation(list[ForwardRef('MyInt')], 'smart') == 'list[MyInt]' + assert stringify_annotation(list[ForwardRef('MyInt')]) == 'list[MyInt]' # ty: ignore[invalid-type-form] + assert stringify_annotation(list[ForwardRef('MyInt')], 'smart') == 'list[MyInt]' # ty: ignore[invalid-type-form] ann_str = stringify_annotation( - Tuple[dict[ForwardRef('MyInt'), str], list[List[int]]] + Tuple[dict[ForwardRef('MyInt'), str], list[List[int]]] # ty: ignore[invalid-type-form] ) assert ann_str == 'Tuple[dict[MyInt, str], list[List[int]]]' ann_str = stringify_annotation( - Tuple[dict[ForwardRef('MyInt'), str], list[List[int]]], + Tuple[dict[ForwardRef('MyInt'), str], list[List[int]]], # ty: ignore[invalid-type-form] 'fully-qualified-except-typing', ) assert ann_str == 'Tuple[dict[MyInt, str], list[List[int]]]' ann_str = stringify_annotation( - Tuple[dict[ForwardRef('MyInt'), str], list[List[int]]], 'smart' + Tuple[dict[ForwardRef('MyInt'), str], list[List[int]]], # ty: ignore[invalid-type-form] + 'smart', ) assert ann_str == '~typing.Tuple[dict[MyInt, str], list[~typing.List[int]]]' diff --git a/tests/test_versioning.py b/tests/test_versioning.py index 1fb8849afd..03d5e00750 100644 --- a/tests/test_versioning.py +++ b/tests/test_versioning.py @@ -6,6 +6,7 @@ import pickle import shutil import pytest +from docutils.utils import DependencyList from sphinx.testing.util import SphinxTestApp from sphinx.versioning import add_uids, get_ratio, merge_doctrees @@ -19,7 +20,8 @@ if TYPE_CHECKING: from sphinx.application import Sphinx -original = original_uids = None +original: nodes.document +original_uids: list[str] @pytest.fixture(scope='module', autouse=True) @@ -61,11 +63,11 @@ def test_add_uids() -> None: def test_pickleablility() -> None: # we have to modify the doctree so we can pickle it copy = original.copy() - copy.reporter = None - copy.transformer = None + copy.reporter = None # type: ignore[assignment] + copy.transformer = None # type: ignore[assignment] copy.settings.warning_stream = None copy.settings.env = None - copy.settings.record_dependencies = None + copy.settings.record_dependencies = DependencyList() loaded = pickle.loads(pickle.dumps(copy, pickle.HIGHEST_PROTOCOL)) assert all(getattr(n, 'uid', False) for n in loaded.findall(is_paragraph)) diff --git a/ty.toml b/ty.toml index b1a9298aba..6a5c8bf1fe 100644 --- a/ty.toml +++ b/ty.toml @@ -15,20 +15,12 @@ include = [ ] exclude = [ "tests/roots", + "tests/test_util/typing_test_data.py", ] [rules] -call-non-callable = "ignore" -inconsistent-mro = "ignore" invalid-argument-type = "ignore" invalid-assignment = "ignore" invalid-method-override = "ignore" -invalid-return-type = "ignore" -invalid-type-form = "ignore" -no-matching-overload = "ignore" non-subscriptable = "ignore" possibly-missing-attribute = "ignore" -unresolved-attribute = "ignore" -unresolved-import = "ignore" -unresolved-reference = "ignore" -unsupported-operator = "ignore"