From 943bf0d191e8e3fada0c7cf0ecd90a066f2e622d Mon Sep 17 00:00:00 2001 From: Adam Turner <9087854+AA-Turner@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:23:50 -0700 Subject: [PATCH] Use Ruff rule names in place of codes (#14761) --- .ruff.toml | 294 +++++++++--------- doc/conf.py | 4 +- sphinx/__init__.py | 2 +- sphinx/_cli/util/colour.py | 4 +- sphinx/addnodes.py | 2 +- sphinx/builders/__init__.py | 8 +- sphinx/builders/html/__init__.py | 6 +- sphinx/builders/latex/__init__.py | 2 +- sphinx/builders/linkcheck.py | 10 +- sphinx/builders/singlehtml.py | 2 +- sphinx/cmd/build.py | 2 +- sphinx/cmd/quickstart.py | 6 +- sphinx/config.py | 6 +- sphinx/directives/code.py | 2 +- sphinx/directives/patches.py | 2 +- sphinx/domains/c/__init__.py | 2 +- sphinx/domains/c/_parser.py | 2 +- sphinx/domains/cpp/__init__.py | 4 +- sphinx/domains/python/__init__.py | 4 +- sphinx/domains/python/_annotations.py | 2 +- sphinx/domains/std/__init__.py | 2 +- sphinx/environment/__init__.py | 2 +- sphinx/environment/collectors/asset.py | 2 +- sphinx/ext/apidoc/_generate.py | 2 +- sphinx/ext/autodoc/_directive.py | 4 +- sphinx/ext/autodoc/_dynamic/_importer.py | 4 +- sphinx/ext/autodoc/_dynamic/_member_finder.py | 2 +- sphinx/ext/autodoc/_dynamic/_mock.py | 2 +- sphinx/ext/autodoc/_dynamic/_signatures.py | 6 +- sphinx/ext/autodoc/_event_listeners.py | 8 +- .../_legacy_class_based/_directive_options.py | 2 +- .../_legacy_class_based/_documenters.py | 10 +- sphinx/ext/autodoc/_sentinels.py | 4 +- sphinx/ext/autodoc/_shared.py | 2 +- sphinx/ext/autodoc/directive.py | 4 +- sphinx/ext/autodoc/importer.py | 8 +- sphinx/ext/autodoc/mock.py | 18 +- sphinx/ext/autodoc/preserve_defaults.py | 10 +- sphinx/ext/autodoc/type_comment.py | 4 +- sphinx/ext/autosummary/__init__.py | 2 +- sphinx/ext/autosummary/generate.py | 4 +- sphinx/ext/coverage.py | 10 +- sphinx/ext/doctest.py | 6 +- sphinx/ext/graphviz.py | 2 +- sphinx/ext/ifconfig.py | 2 +- sphinx/ext/imgmath.py | 2 +- sphinx/ext/intersphinx/_load.py | 2 +- sphinx/jinja2glue.py | 2 +- sphinx/pycode/parser.py | 2 +- sphinx/search/__init__.py | 4 +- sphinx/testing/fixtures.py | 2 +- sphinx/theming.py | 10 +- sphinx/util/_files.py | 4 +- sphinx/util/_lines.py | 6 +- sphinx/util/_pathlib.py | 4 +- sphinx/util/cfamily.py | 2 +- sphinx/util/console.py | 2 +- sphinx/util/display.py | 8 +- sphinx/util/docutils.py | 4 +- sphinx/util/inspect.py | 4 +- sphinx/util/nodes.py | 2 +- sphinx/util/texescape.py | 4 +- sphinx/util/typing.py | 6 +- sphinx/writers/html5.py | 2 +- sphinx/writers/latex.py | 2 +- sphinx/writers/text.py | 2 +- .../enumerable_node.py | 2 +- .../test-ext-autodoc/autodoc_dummy_module.py | 4 +- .../test-ext-autodoc/target/TYPE_CHECKING.py | 6 +- .../roots/test-ext-autodoc/target/__init__.py | 8 +- .../target/autodoc_type_aliases.py | 4 +- .../roots/test-ext-autodoc/target/classes.py | 4 +- .../test-ext-autodoc/target/coroutine.py | 2 +- .../target/docstring_signature.py | 4 +- tests/roots/test-ext-autodoc/target/enums.py | 2 +- tests/roots/test-ext-autodoc/target/final.py | 2 +- .../test-ext-autodoc/target/functions.py | 4 +- .../test-ext-autodoc/target/generic_class.py | 2 +- .../test-ext-autodoc/target/inheritance.py | 4 +- .../test-ext-autodoc/target/need_mocks.py | 8 +- .../test-ext-autodoc/target/overload3.py | 2 +- tests/roots/test-ext-autodoc/target/pep695.py | 6 +- .../target/preserve_defaults.py | 12 +- .../preserve_defaults_special_constructs.py | 4 +- tests/roots/test-ext-autodoc/target/slots.py | 2 +- .../test-ext-autodoc/target/typed_vars.py | 2 +- .../test-ext-autodoc/target/typehints.py | 9 +- .../roots/test-ext-autodoc/target/typevar.py | 4 +- .../target/wrappedfunction.py | 6 +- .../test-ext-autosummary-ext/dummy_module.py | 2 +- .../underscore_module_.py | 2 +- .../autosummary_dummy_module.py | 2 +- .../autosummary_dummy_package_all/__init__.py | 2 +- .../package/module.py | 2 +- .../package/package/module.py | 2 +- .../package2/module.py | 2 +- .../autosummary_dummy_module.py | 4 +- .../test-ext-inheritance_diagram/test.py | 2 +- tests/roots/test-ext-math-compat/conf.py | 2 +- .../test-ext-viewcode-find-package/conf.py | 2 +- .../not_a_package/submodule.py | 6 +- tests/roots/test-ext-viewcode/conf.py | 2 +- tests/roots/test-inheritance/dummy/test.py | 2 +- .../test-inheritance/dummy/test_nested.py | 2 +- tests/roots/test-root/autodoc_target.py | 8 +- tests/roots/test-root/conf.py | 2 +- tests/test_builders/test_build_epub.py | 10 +- tests/test_builders/test_build_latex.py | 2 +- tests/test_domains/test_domain_c.py | 2 +- tests/test_ext_autodoc/test_ext_autodoc.py | 2 +- .../test_ext_autodoc_autoclass.py | 2 +- .../test_ext_autodoc/test_ext_autodoc_mock.py | 2 +- .../test_ext_autodoc_signatures.py | 12 +- .../test_ext_autodoc_typehints.py | 14 +- .../test_ext_autosummary.py | 2 +- .../test_ext_intersphinx.py | 2 +- tests/test_ext_napoleon/test_ext_napoleon.py | 16 +- .../test_ext_napoleon_docstring.py | 4 +- tests/test_extensions/test_ext_apidoc.py | 2 +- tests/test_extensions/test_ext_doctest.py | 6 +- tests/test_quickstart.py | 8 +- tests/test_util/test_util_display.py | 4 +- tests/test_util/test_util_i18n.py | 4 +- tests/test_util/test_util_inspect.py | 20 +- tests/test_util/test_util_inspect_py314.py | 6 +- tests/test_util/typing_test_data.py | 6 +- tests/test_versioning.py | 2 +- utils/bump_docker.py | 2 +- 128 files changed, 427 insertions(+), 416 deletions(-) diff --git a/.ruff.toml b/.ruff.toml index 43f94d2a6f..acb0af8627 100644 --- a/.ruff.toml +++ b/.ruff.toml @@ -17,134 +17,132 @@ quote-style = "single" preview = true ignore = [ # flake8-builtins - "A001", # Variable `{name}` is shadowing a Python builtin - "A002", # Function argument `{name}` is shadowing a Python builtin - "A005", # Module `{name}` is shadowing a Python builtin module + "builtin-variable-shadowing", # Variable `{name}` is shadowing a Python builtin + "builtin-argument-shadowing", # Function argument `{name}` is shadowing a Python builtin + "stdlib-module-shadowing", # Module `{name}` is shadowing a Python builtin module # flake8-annotations - "ANN401", # Dynamically typed expressions (typing.Any) are disallowed in `{name}` + "any-type", # Dynamically typed expressions (typing.Any) are disallowed in `{name}` # flake8-unused-arguments ('ARG') - "ARG001", # Unused function argument: `{name}` - "ARG002", # Unused method argument: `{name}` - "ARG003", # Unused class method argument: `{name}` - "ARG005", # Unused lambda argument: `{name}` + "unused-function-argument", # Unused function argument: `{name}` + "unused-method-argument", # Unused method argument: `{name}` + "unused-class-method-argument", # Unused class method argument: `{name}` + "unused-lambda-argument", # Unused lambda argument: `{name}` # flake8-blind-except - "BLE001", # Do not catch blind exception: `{name}` + "blind-except", # Do not catch blind exception: `{name}` # flake8-commas - "COM812", # Trailing comma missing + "missing-trailing-comma", # Trailing comma missing # flake8-copyright - "CPY001", # Missing copyright notice at top of file + "missing-copyright-notice", # Missing copyright notice at top of file # pydocstyle ('D') - "D100", # Missing docstring in public module - "D101", # Missing docstring in public class - "D102", # Missing docstring in public method - "D103", # Missing docstring in public function - "D104", # Missing docstring in public package - "D105", # Missing docstring in magic method - "D107", # Missing docstring in `__init__` - "D200", # One-line docstring should fit on one line - "D205", # 1 blank line required between summary line and description - "D400", # First line should end with a period - "D401", # First line of docstring should be in imperative mood: "{first_line}" + "undocumented-public-module", # Missing docstring in public module + "undocumented-public-class", # Missing docstring in public class + "undocumented-public-method", # Missing docstring in public method + "undocumented-public-function", # Missing docstring in public function + "undocumented-public-package", # Missing docstring in public package + "undocumented-magic-method", # Missing docstring in magic method + "undocumented-public-init", # Missing docstring in `__init__` + "unnecessary-multiline-docstring", # One-line docstring should fit on one line + "missing-blank-line-after-summary", # 1 blank line required between summary line and description + "missing-trailing-period", # First line should end with a period + "non-imperative-mood", # First line of docstring should be in imperative mood: "{first_line}" # pydoclint - "DOC201", # `return` is not documented in docstring - "DOC402", # `yield` is not documented in docstring - "DOC501", # Raised exception `{id}` missing from docstring + "docstring-missing-returns", # `return` is not documented in docstring + "docstring-missing-yields", # `yield` is not documented in docstring + "docstring-missing-exception", # Raised exception `{id}` missing from docstring # pycodestyle - "E741", # Ambiguous variable name: `{name}` + "ambiguous-variable-name", # Ambiguous variable name: `{name}` # eradicate - "ERA001", # Found commented-out code + "commented-out-code", # Found commented-out code # pyflakes - "F841", # Local variable `{name}` is assigned to but never used + "unused-variable", # Local variable `{name}` is assigned to but never used # flake8-boolean-trap - "FBT001", # Boolean-typed positional argument in function definition - "FBT002", # Boolean default positional argument in function definition - "FBT003", # Boolean positional value in function call + "boolean-type-hint-positional-argument", # Boolean-typed positional argument in function definition + "boolean-default-value-positional-argument", # Boolean default positional argument in function definition + "boolean-positional-value-in-call", # Boolean positional value in function call # flake8-fixme - "FIX001", # Line contains FIXME, consider resolving the issue - "FIX002", # Line contains TODO, consider resolving the issue - "FIX003", # Line contains XXX, consider resolving the issue - "FIX004", # Line contains HACK, consider resolving the issue + "line-contains-fixme", # Line contains FIXME, consider resolving the issue + "line-contains-todo", # Line contains TODO, consider resolving the issue + "line-contains-xxx", # Line contains XXX, consider resolving the issue + "line-contains-hack", # Line contains HACK, consider resolving the issue # refurb - "FURB101", # `open` and `read` should be replaced by `Path(...).read_text(...)` - "FURB103", # `open` and `write` should be replaced by `Path(...).write_text(...)` + "read-whole-file", # `open` and `read` should be replaced by `Path(...).read_text(...)` + "write-whole-file", # `open` and `write` should be replaced by `Path(...).write_text(...)` # flake8-implicit-str-concat # pep8-naming - "N801", # Class name `{name}` should use CapWords convention - "N802", # Function name `{name}` should be lowercase - "N803", # Argument name `{name}` should be lowercase - "N806", # Variable `{name}` in function should be lowercase - "N818", # Exception name `{name}` should be named with an Error suffix + "invalid-class-name", # Class name `{name}` should use CapWords convention + "invalid-function-name", # Function name `{name}` should be lowercase + "invalid-argument-name", # Argument name `{name}` should be lowercase + "non-lowercase-variable-in-function", # Variable `{name}` in function should be lowercase + "error-suffix-on-exception-name", # Exception name `{name}` should be named with an Error suffix # perflint - "PERF203", # `try`-`except` within a loop incurs performance overhead + "try-except-in-loop", # `try`-`except` within a loop incurs performance overhead # flake8-pie - "PIE790", # Unnecessary `pass` statement + "unnecessary-placeholder", # Unnecessary `pass` statement # pylint - "PLC0415", # `import` should be at the top-level of a file - "PLC2701", # Private name import `{name}` from external module `{module}` - "PLR0904", # Too many public methods ({methods} > {max_methods}) - "PLR0911", # Too many return statements ({returns} > {max_returns}) - "PLR0912", # Too many branches ({branches} > {max_branches}) - "PLR0913", # Too many arguments in function definition ({c_args} > {max_args}) - "PLR0914", # Too many local variables ({current_amount}/{max_amount}) - "PLR0915", # Too many statements ({statements} > {max_statements}) - "PLR0916", # Too many Boolean expressions ({expressions} > {max_expressions}) - "PLR0917", # Too many positional arguments ({c_pos}/{max_pos}) - "PLR1702", # Too many nested blocks ({nested_blocks} > {max_nested_blocks}) - "PLR2004", # Magic value used in comparison, consider replacing `{value}` with a constant variable - "PLR5501", # Use `elif` instead of `else` then `if`, to reduce indentation - "PLR6104", # Use `{operator}` to perform an augmented assignment directly - "PLR6301", # Method `{method_name}` could be a function, class method, or static method - "PLW0717", # Try clause contains too many statements ({} > 5) - "PLW2901", # Outer {outer_kind} variable `{name}` overwritten by inner {inner_kind} target + "import-outside-top-level", # `import` should be at the top-level of a file + "import-private-name", # Private name import `{name}` from external module `{module}` + "too-many-public-methods", # Too many public methods ({methods} > {max_methods}) + "too-many-return-statements", # Too many return statements ({returns} > {max_returns}) + "too-many-branches", # Too many branches ({branches} > {max_branches}) + "too-many-arguments", # Too many arguments in function definition ({c_args} > {max_args}) + "too-many-locals", # Too many local variables ({current_amount}/{max_amount}) + "too-many-statements", # Too many statements ({statements} > {max_statements}) + "too-many-boolean-expressions", # Too many Boolean expressions ({expressions} > {max_expressions}) + "too-many-positional-arguments", # Too many positional arguments ({c_pos}/{max_pos}) + "too-many-nested-blocks", # Too many nested blocks ({nested_blocks} > {max_nested_blocks}) + "magic-value-comparison", # Magic value used in comparison, consider replacing `{value}` with a constant variable + "collapsible-else-if", # Use `elif` instead of `else` then `if`, to reduce indentation + "non-augmented-assignment", # Use `{operator}` to perform an augmented assignment directly + "no-self-use", # Method `{method_name}` could be a function, class method, or static method + "too-many-statements-in-try-clause", # Try clause contains too many statements ({} > 5) + "redefined-loop-name", # Outer {outer_kind} variable `{name}` overwritten by inner {inner_kind} target # flake8-use-pathlib - "PTH100", # `os.path.abspath()` should be replaced by `Path.resolve()` - "PTH110", # `os.path.exists()` should be replaced by `Path.exists()` - "PTH113", # `os.path.isfile()` should be replaced by `Path.is_file()` - "PTH118", # `os.{module}.join()` should be replaced by `Path` with `/` operator - "PTH119", # `os.path.basename()` should be replaced by `Path.name` - "PTH120", # `os.path.dirname()` should be replaced by `Path.parent` - "PTH122", # `os.path.splitext()` should be replaced by `Path.suffix`, `Path.stem`, and `Path.parent` - "PTH123", # `open()` should be replaced by `Path.open()` + "os-path-abspath", # `os.path.abspath()` should be replaced by `Path.resolve()` + "os-path-exists", # `os.path.exists()` should be replaced by `Path.exists()` + "os-path-isfile", # `os.path.isfile()` should be replaced by `Path.is_file()` + "os-path-join", # `os.{module}.join()` should be replaced by `Path` with `/` operator + "os-path-basename", # `os.path.basename()` should be replaced by `Path.name` + "os-path-dirname", # `os.path.dirname()` should be replaced by `Path.parent` + "os-path-splitext", # `os.path.splitext()` should be replaced by `Path.suffix`, `Path.stem`, and `Path.parent` + "builtin-open", # `open()` should be replaced by `Path.open()` # flake8-pyi ('PYI') - "PYI025", # Use `from collections.abc import Set as AbstractSet` to avoid confusion with the `set` builtin + "unaliased-collections-abc-set-import", # Use `from collections.abc import Set as AbstractSet` to avoid confusion with the `set` builtin # flake8-return - "RET504", # Unnecessary assignment to `{name}` before `return` statement - "RET505", # Unnecessary `{branch}` after `return` statement - "RET506", # Unnecessary `{branch}` after `raise` statement + "unnecessary-assign", # Unnecessary assignment to `{name}` before `return` statement + "superfluous-else-return", # Unnecessary `{branch}` after `return` statement + "superfluous-else-raise", # Unnecessary `{branch}` after `raise` statement # flake8-bandit ('S') - "S101", # Use of `assert` detected - "S110", # `try`-`except`-`pass` detected, consider logging the exception - "S404", # `subprocess` module is possibly insecure - "S405", # `xml.etree` methods are vulnerable to XML attacks - "S603", # `subprocess` call: check for execution of untrusted input + "assert", # Use of `assert` detected + "try-except-pass", # `try`-`except`-`pass` detected, consider logging the exception + "suspicious-subprocess-import", # `subprocess` module is possibly insecure + "suspicious-xml-etree-import", # `xml.etree` methods are vulnerable to XML attacks + "subprocess-without-shell-equals-true", # `subprocess` call: check for execution of untrusted input # flake8-simplify - "SIM102", # Use a single `if` statement instead of nested `if` statements - "SIM108", # Use ternary operator `{contents}` instead of `if`-`else`-block + "collapsible-if", # Use a single `if` statement instead of nested `if` statements + "if-else-block-instead-of-if-exp", # Use ternary operator `{contents}` instead of `if`-`else`-block # flake8-self - "SLF001", # Private member accessed: `{access}` + "private-member-access", # Private member accessed: `{access}` # flake8-todos ('TD') - "TD001", # Invalid TODO tag: `{tag}` - "TD002", # Missing author in TODO; try: `# TODO(): ...` or `# TODO @: ...` - "TD003", # Missing issue link on the line following this TODO - "TD004", # Missing colon in TODO + "invalid-todo-tag", # Invalid TODO tag: `{tag}` + "missing-todo-author", # Missing author in TODO; try: `# TODO(): ...` or `# TODO @: ...` + "missing-todo-link", # Missing issue link on the line following this TODO + "missing-todo-colon", # Missing colon in TODO # tryceratops - "TRY002", # Create your own exception - "TRY300", # Consider moving this statement to an `else` block + "raise-vanilla-class", # Create your own exception + "try-consider-else", # Consider moving this statement to an `else` block # pyupgrade - "UP031", # Use format specifiers instead of percent format - "UP032", # Use f-string instead of `format` call + "printf-string-formatting", # Use format specifiers instead of percent format + "f-string", # Use f-string instead of `format` call # Ruff-specific rules ('RUF') - "RUF012", # Mutable class attributes should be annotated with `typing.ClassVar` - "RUF021", # Parenthesize `a and b` expressions when chaining `and` and `or` together, to make the precedence clear - "RUF022", # `__all__` is not sorted - "RUF023", # `{}.__slots__` is not sorted - "RUF027", # Possible f-string without an `f` prefix - "RUF039", # First argument to {call} is not raw string - "RUF052", # Local dummy variable `{}` is accessed - "RUF067", # `__init__` module should only contain docstrings and re-exports - "RUF069", # Unreliable floating point equality comparison `{}` - "RUF105", # `noqa` comment used instead of `{}` - "RUF201", # Rule code used instead of name in `{}` + "mutable-class-default", # Mutable class attributes should be annotated with `typing.ClassVar` + "parenthesize-chained-operators", # Parenthesize `a and b` expressions when chaining `and` and `or` together, to make the precedence clear + "unsorted-dunder-all", # `__all__` is not sorted + "unsorted-dunder-slots", # `{}.__slots__` is not sorted + "missing-f-string-syntax", # Possible f-string without an `f` prefix + "unraw-re-pattern", # First argument to {call} is not raw string + "used-dummy-variable", # Local dummy variable `{}` is accessed + "non-empty-init-module", # `__init__` module should only contain docstrings and re-exports + "float-equality-comparison", # Unreliable floating point equality comparison `{}` ] external = [ # Whitelist for RUF100 unknown code warnings "SIM113", @@ -174,10 +172,10 @@ select = [ "CPY", # pydocstyle ('D') "D", - "D212", # Multi-line docstring summary should start at the first line + "multi-line-summary-first-line", # Multi-line docstring summary should start at the first line # "D404", # First word of the docstring should not be "This" # "D415", # First line should end with a period, question mark, or exclamation point - "D417", # Missing argument description in the docstring for `{definition}`: `{name}` + "undocumented-param", # Missing argument description in the docstring for `{definition}`: `{name}` # pydoclint ('DOC') "DOC", # flake8-django ('DJ') @@ -287,104 +285,104 @@ logger-objects = [ [lint.per-file-ignores] "doc/*" = [ "ANN", # documentation doesn't need annotations - "TC001", # documentation doesn't need type-checking blocks + "typing-only-first-party-import", # documentation doesn't need type-checking blocks ] "doc/conf.py" = [ - "INP001", # doc/ is not a namespace package + "implicit-namespace-package", # doc/ is not a namespace package ] "doc/development/tutorials/examples/*" = [ - "I002", # we don't need the annotations future - "INP001", # examples/ is not a namespace package + "missing-required-import", # we don't need the annotations future + "implicit-namespace-package", # examples/ is not a namespace package ] "doc/development/tutorials/examples/recipe.py" = [ - "FURB118", # keep the tutorial simple: no itemgetter - "T201" # allow print() in the tutorial + "reimplemented-operator", # keep the tutorial simple: no itemgetter + "print" # allow print() in the tutorial ] "doc/usage/extensions/example_{google,numpy}.py" = [ - "D416", # Section name should end with a colon ("{name}") - "DOC502", # Raised exception is not explicitly raised: `{id}` - "I002", # Missing required import: {name} - "INP001", # File {filename} is part of an implicit namespace package. Add an __init__.py. - "PLW3201", # Dunder method {name} has no special meaning in Python 3 + "missing-section-name-colon", # Section name should end with a colon ("{name}") + "docstring-extraneous-exception", # Raised exception is not explicitly raised: `{id}` + "missing-required-import", # Missing required import: {name} + "implicit-namespace-package", # File {filename} is part of an implicit namespace package. Add an __init__.py. + "bad-dunder-method-name", # Dunder method {name} has no special meaning in Python 3 ] # whitelist ``print`` for stdout messages -"sphinx/_cli/__init__.py" = ["T201"] +"sphinx/_cli/__init__.py" = ["print"] # allow use of ``pickle`` "sphinx/{application,builders/__init__,environment/__init__,ext/coverage,search/__init__,versioning}.py" = [ - "S301", - "S403", + "suspicious-pickle-usage", + "suspicious-pickle-import", ] # whitelist ``print`` for stdout messages -"sphinx/cmd/build.py" = ["T201"] -"sphinx/cmd/make_mode.py" = ["T201"] +"sphinx/cmd/build.py" = ["print"] +"sphinx/cmd/make_mode.py" = ["print"] "sphinx/cmd/quickstart.py" = [ "PTH", - "T201", + "print", ] -"sphinx/environment/collectors/toctree.py" = ["B026"] -"sphinx/environment/adapters/toctree.py" = ["B026"] +"sphinx/environment/collectors/toctree.py" = ["star-arg-unpacking-after-keyword-arg"] +"sphinx/environment/adapters/toctree.py" = ["star-arg-unpacking-after-keyword-arg"] # whitelist ``print`` for stdout messages -"sphinx/ext/intersphinx/_cli.py" = ["T201"] +"sphinx/ext/intersphinx/_cli.py" = ["print"] # whitelist ``token`` in docstring parsing -"sphinx/ext/napoleon/docstring.py" = ["S105"] +"sphinx/ext/napoleon/docstring.py" = ["hardcoded-password-string"] -"sphinx/search/*" = ["RUF001"] +"sphinx/search/*" = ["ambiguous-unicode-character-string"] # whitelist ``print`` for stdout messages -"sphinx/testing/fixtures.py" = ["T201"] +"sphinx/testing/fixtures.py" = ["print"] # whitelist ``os.path`` for deprecated ``sphinx.testing.path`` "sphinx/testing/path.py" = ["PTH"] # whitelist ``token`` in date format parsing -"sphinx/util/i18n.py" = ["S105"] +"sphinx/util/i18n.py" = ["hardcoded-password-string"] # whitelist ``os.path`` for ``sphinx.util.osutil`` "sphinx/util/osutil.py" = ["PTH"] # whitelist ``token`` in literal parsing -"sphinx/writers/html5.py" = ["S105"] +"sphinx/writers/html5.py" = ["hardcoded-password-string"] "tests/*" = [ - "E501", + "line-too-long", "ANN", # tests don't need annotations - "D402", - "PLC1901", # whitelist comparisons to the empty string ('') - "RUF001", # ambiguous unicode character - "S301", # allow use of ``pickle`` - "S403", # allow use of ``pickle`` - "T201", # whitelist ``print`` for tests + "signature-in-docstring", + "compare-to-empty-string", # whitelist comparisons to the empty string ('') + "ambiguous-unicode-character-string", # ambiguous unicode character + "suspicious-pickle-usage", # allow use of ``pickle`` + "suspicious-pickle-import", # allow use of ``pickle`` + "print", # whitelist ``print`` for tests ] # test roots are not packages -"tests/js/roots/*" = ["I002", "INP001"] +"tests/js/roots/*" = ["missing-required-import", "implicit-namespace-package"] "tests/roots/*" = [ - "D403", # permit uncapitalised docstrings - "F401", # names may be unused in test roots - "I002", # we don't need the annotations future - "INP001", # test roots are not packages + "first-word-uncapitalized", # permit uncapitalised docstrings + "unused-import", # names may be unused in test roots + "missing-required-import", # we don't need the annotations future + "implicit-namespace-package", # test roots are not packages ] # these tests need old ``typing`` generic aliases -"tests/roots/test-ext-autodoc/target/genericalias.py" = ["UP006", "UP007", "UP035", "UP045"] -"tests/test_util/test_util_typing.py" = ["RUF036", "UP006", "UP007", "UP035", "UP045"] -"tests/test_util/typing_test_data.py" = ["FA100", "I002", "PYI030", "UP006", "UP007", "UP035", "UP045"] +"tests/roots/test-ext-autodoc/target/genericalias.py" = ["non-pep585-annotation", "non-pep604-annotation-union", "deprecated-import", "non-pep604-annotation-optional"] +"tests/test_util/test_util_typing.py" = ["none-not-at-end-of-union", "non-pep585-annotation", "non-pep604-annotation-union", "deprecated-import", "non-pep604-annotation-optional"] +"tests/test_util/typing_test_data.py" = ["future-rewritable-type-annotation", "missing-required-import", "unnecessary-literal-union", "non-pep585-annotation", "non-pep604-annotation-union", "deprecated-import", "non-pep604-annotation-optional"] # these tests need old-style type comments -"tests/roots/test-ext-autodoc/target/autodoc_type_aliases.py" = ["PYI033"] -"tests/roots/test-ext-autodoc/target/cached_property.py" = ["PYI033"] -"tests/roots/test-ext-autodoc/target/properties.py" = ["PYI033"] -"tests/roots/test-ext-autodoc/target/typed_vars.py" = ["PYI033"] -"tests/roots/test-ext-autodoc/target/typehints.py" = ["PYI033"] +"tests/roots/test-ext-autodoc/target/autodoc_type_aliases.py" = ["legacy-type-comment"] +"tests/roots/test-ext-autodoc/target/cached_property.py" = ["legacy-type-comment"] +"tests/roots/test-ext-autodoc/target/properties.py" = ["legacy-type-comment"] +"tests/roots/test-ext-autodoc/target/typed_vars.py" = ["legacy-type-comment"] +"tests/roots/test-ext-autodoc/target/typehints.py" = ["legacy-type-comment"] "utils/*" = [ - "T201", # whitelist ``print`` for stdout messages + "print", # whitelist ``print`` for stdout messages "ANN", # utilities don't need annotations ] diff --git a/doc/conf.py b/doc/conf.py index 8e9e5241ca..b499668943 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -272,7 +272,7 @@ nitpick_ignore = { # -- Extension interface ------------------------------------------------------- -from sphinx import addnodes # NoQA: E402 +from sphinx import addnodes # ruff: ignore[module-import-not-at-top-of-file] if TYPE_CHECKING: from pathlib import Path @@ -328,7 +328,7 @@ REDIRECT_TEMPLATE = """ If not, click here to continue. -""" # NoQA: E501 +""" # ruff: ignore[line-too-long] def build_redirects(app: Sphinx, exception: Exception | None) -> None: diff --git a/sphinx/__init__.py b/sphinx/__init__.py index 210ca1c507..9ecc88fbe5 100644 --- a/sphinx/__init__.py +++ b/sphinx/__init__.py @@ -34,7 +34,7 @@ if _in_development: try: if ret := subprocess.run( - ('git', 'rev-parse', '--short', 'HEAD'), # NoQA: S607 + ('git', 'rev-parse', '--short', 'HEAD'), # ruff: ignore[start-process-with-partial-path] capture_output=True, check=False, cwd=package_dir, diff --git a/sphinx/_cli/util/colour.py b/sphinx/_cli/util/colour.py index 355b701333..c38f45f2dc 100644 --- a/sphinx/_cli/util/colour.py +++ b/sphinx/_cli/util/colour.py @@ -43,12 +43,12 @@ def terminal_supports_colour() -> bool: def disable_colour() -> None: - global _COLOURING_DISABLED # NoQA: PLW0603 + global _COLOURING_DISABLED # ruff: ignore[global-statement] _COLOURING_DISABLED = True def enable_colour() -> None: - global _COLOURING_DISABLED # NoQA: PLW0603 + global _COLOURING_DISABLED # ruff: ignore[global-statement] _COLOURING_DISABLED = False diff --git a/sphinx/addnodes.py b/sphinx/addnodes.py index 4ce85dabcf..68cd86242e 100644 --- a/sphinx/addnodes.py +++ b/sphinx/addnodes.py @@ -5,7 +5,7 @@ from __future__ import annotations from typing import TYPE_CHECKING from docutils import nodes -from docutils.nodes import document # NoQA: F401 +from docutils.nodes import document # ruff: ignore[unused-import] if TYPE_CHECKING: from collections.abc import Sequence diff --git a/sphinx/builders/__init__.py b/sphinx/builders/__init__.py index ad7523927f..54f84316a8 100644 --- a/sphinx/builders/__init__.py +++ b/sphinx/builders/__init__.py @@ -38,8 +38,8 @@ from sphinx.util.parallel import ( ) # side effect: registers roles and directives -from sphinx import directives # NoQA: F401 isort:skip -from sphinx import roles # NoQA: F401 isort:skip +from sphinx import directives # ruff: ignore[unused-import] isort:skip +from sphinx import roles # ruff: ignore[unused-import] isort:skip if TYPE_CHECKING: from collections.abc import Iterable, Sequence, Set @@ -258,7 +258,7 @@ class Builder: def cat2relpath(cat: CatalogInfo, srcdir: Path = self.srcdir) -> str: return Path(relpath(cat.mo_path, srcdir)).as_posix() - logger.info(bold(__('building [mo]: ')) + message) # NoQA: G003 + logger.info(bold(__('building [mo]: ')) + message) # ruff: ignore[logging-string-concat] for catalog in status_iterator( catalogs, __('writing output... '), @@ -398,7 +398,7 @@ class Builder: :meth:`!write`. """ if summary: - logger.info(bold(__('building [%s]: ')) + summary, self.name) # NoQA: G003 + logger.info(bold(__('building [%s]: ')) + summary, self.name) # ruff: ignore[logging-string-concat] # while reading, collect all warnings from docutils with ( diff --git a/sphinx/builders/html/__init__.py b/sphinx/builders/html/__init__.py index 153cfa141c..35190c368e 100644 --- a/sphinx/builders/html/__init__.py +++ b/sphinx/builders/html/__init__.py @@ -352,7 +352,7 @@ class StandaloneHTMLBuilder(Builder): msg = __( 'build_info mismatch, copying .buildinfo to .buildinfo.bak' ) - logger.info(bold(__('building [html]: ')) + msg) # NoQA: G003 + logger.info(bold(__('building [html]: ')) + msg) # ruff: ignore[logging-string-concat] yield from self.env.found_docs return @@ -367,7 +367,7 @@ class StandaloneHTMLBuilder(Builder): # Let users know they have a newer template if template_mtime > old_mtime: logger.info( - bold('building [html]: ') # NoQA: G003 + bold('building [html]: ') # ruff: ignore[logging-string-concat] + __( 'template %s has been changed since the previous build, ' 'all docs will be rebuilt' @@ -1024,7 +1024,7 @@ class StandaloneHTMLBuilder(Builder): ) -> str: if 'includehidden' not in kwargs: kwargs['includehidden'] = False - if kwargs.get('maxdepth') == '': # NoQA: PLC1901 + if kwargs.get('maxdepth') == '': # ruff: ignore[compare-to-empty-string] kwargs.pop('maxdepth') toctree = global_toctree_for_doc( self.env, docname, self, tags=self.tags, collapse=collapse, **kwargs diff --git a/sphinx/builders/latex/__init__.py b/sphinx/builders/latex/__init__.py index 69c11d515b..373756985b 100644 --- a/sphinx/builders/latex/__init__.py +++ b/sphinx/builders/latex/__init__.py @@ -7,7 +7,7 @@ import os.path from pathlib import Path from typing import TYPE_CHECKING -import sphinx.builders.latex.nodes # NoQA: F401 # Workaround: import this before writer to avoid ImportError +import sphinx.builders.latex.nodes # ruff: ignore[unused-import] # Workaround: import this before writer to avoid ImportError from sphinx import addnodes, highlighting, package_dir from sphinx._cli.util.colour import darkgreen from sphinx.builders import Builder diff --git a/sphinx/builders/linkcheck.py b/sphinx/builders/linkcheck.py index 5889e75d12..0b0101e4e6 100644 --- a/sphinx/builders/linkcheck.py +++ b/sphinx/builders/linkcheck.py @@ -16,7 +16,7 @@ from urllib.parse import quote, unquote, urlparse, urlsplit, urlunparse from docutils import nodes from requests.exceptions import ( - ConnectionError, # NoQA: A004 + ConnectionError, # ruff: ignore[builtin-import-shadowing] HTTPError, SSLError, TooManyRedirects, @@ -135,9 +135,9 @@ class CheckExternalLinksBuilder(DummyBuilder): msg = f'{res_uri}: {result.message}' else: msg = res_uri - logger.info(darkgray('-ignored- ') + msg) # NoQA: G003 + logger.info(darkgray('-ignored- ') + msg) # ruff: ignore[logging-string-concat] case _Status.WORKING: - logger.info(darkgreen('ok ') + f'{res_uri}{result.message}') # NoQA: G003 + logger.info(darkgreen('ok ') + f'{res_uri}{result.message}') # ruff: ignore[logging-string-concat] case _Status.TIMEOUT: if self.config.verbosity < 0: msg = 'timeout ' + f'{res_uri}{result.message}' @@ -449,7 +449,7 @@ class HyperlinkAvailabilityCheckWorker(Thread): status, info, code = self._check(docname, uri, hyperlink) if status == _Status.RATE_LIMITED: logger.info( - darkgray('-rate limited- ') + uri + darkgray(' | sleeping...') # NoQA: G003 + darkgray('-rate limited- ') + uri + darkgray(' | sleeping...') # ruff: ignore[logging-string-concat] ) else: self.rqueue.put(CheckResult(uri, docname, lineno, status, info, code)) @@ -517,7 +517,7 @@ class HyperlinkAvailabilityCheckWorker(Thread): req_url = encode_uri(req_url) # Get auth info, if any - for pattern, auth_info in self.auth: # NoQA: B007 (false positive) + for pattern, auth_info in self.auth: # ruff: ignore[unused-loop-control-variable] (false positive) if pattern.match(uri): break else: diff --git a/sphinx/builders/singlehtml.py b/sphinx/builders/singlehtml.py index 1888f6679d..387776db98 100644 --- a/sphinx/builders/singlehtml.py +++ b/sphinx/builders/singlehtml.py @@ -81,7 +81,7 @@ class SingleFileHTMLBuilder(StandaloneHTMLBuilder): kwargs['includehidden'] = False elif includehidden.lower() == 'true': kwargs['includehidden'] = True - if kwargs.get('maxdepth') == '': # NoQA: PLC1901 + if kwargs.get('maxdepth') == '': # ruff: ignore[compare-to-empty-string] kwargs.pop('maxdepth') toctree = global_toctree_for_doc( self.env, docname, self, tags=self.tags, collapse=collapse, **kwargs diff --git a/sphinx/cmd/build.py b/sphinx/cmd/build.py index a73717a71d..82a4ca963a 100644 --- a/sphinx/cmd/build.py +++ b/sphinx/cmd/build.py @@ -352,7 +352,7 @@ def _parse_logging( warn_file = Path(warnfile).resolve() ensuredir(warn_file.parent) # the caller is responsible for closing this file descriptor - warnfp = open(warn_file, 'w', encoding='utf-8') # NoQA: SIM115 + warnfp = open(warn_file, 'w', encoding='utf-8') # ruff: ignore[open-file-with-context-handler] except Exception as exc: parser.error(__("cannot open warning file '%s': %s") % (warn_file, exc)) warning = TeeStripANSI(warning, warnfp) # type: ignore[assignment] diff --git a/sphinx/cmd/quickstart.py b/sphinx/cmd/quickstart.py index a376270af7..0a15791aa5 100644 --- a/sphinx/cmd/quickstart.py +++ b/sphinx/cmd/quickstart.py @@ -37,7 +37,7 @@ try: # MyPy doesn't realise that this raises a ModuleNotFoundError # on Windows, and complains that 'parse_and_bind' is not defined. # This condition is always False at runtime, but tricks type checkers. - raise ImportError # NoQA: TRY301 + raise ImportError # ruff: ignore[raise-within-try] except ImportError: READLINE_AVAILABLE = USE_LIBEDIT = False else: @@ -285,8 +285,8 @@ def ask_user(d: dict[str, Any]) -> None: print() print( __( - 'Inside the root directory, two more directories will be created; "_templates"\n' # NoQA: E501 - 'for custom HTML templates and "_static" for custom stylesheets and other static\n' # NoQA: E501 + 'Inside the root directory, two more directories will be created; "_templates"\n' # ruff: ignore[line-too-long] + 'for custom HTML templates and "_static" for custom stylesheets and other static\n' # ruff: ignore[line-too-long] 'files. You can enter another prefix (such as ".") to replace the underscore.' ) ) diff --git a/sphinx/config.py b/sphinx/config.py index 9b791702ec..979d350608 100644 --- a/sphinx/config.py +++ b/sphinx/config.py @@ -85,7 +85,7 @@ class ENUM: def __repr__(self) -> str: return f'ENUM({", ".join(sorted(map(repr, self._candidates)))})' - def match(self, value: str | bool | None | Sequence[str | bool | None]) -> bool: # NoQA: RUF036 + def match(self, value: str | bool | None | Sequence[str | bool | None]) -> bool: # ruff: ignore[none-not-at-end-of-union] if isinstance(value, (str, bool, types.NoneType)): return value in self._candidates return all(item in self._candidates for item in value) @@ -373,7 +373,7 @@ class Config: msg = __("'%s' must be '0' or '1', got '%s'") % (name, value) raise ConfigError(msg) if isinstance(default, dict): - raise ValueError( # NoQA: TRY004 + raise ValueError( # ruff: ignore[type-check-without-type-error] __( 'cannot override dictionary config setting %r, ' 'ignoring (use %r to set individual elements)' @@ -593,7 +593,7 @@ def eval_config_file(filename: Path, tags: Tags) -> dict[str, Any]: # during executing config file, current dir is changed to ``confdir``. try: code = compile(filename.read_bytes(), filename, 'exec') - exec(code, namespace) # NoQA: S102 + exec(code, namespace) # ruff: ignore[exec-builtin] except SyntaxError as err: msg = __('There is a syntax error in your configuration file: %s\n') raise ConfigError(msg % err) from err diff --git a/sphinx/directives/code.py b/sphinx/directives/code.py index e8f9d6ddf8..6753cbdf1e 100644 --- a/sphinx/directives/code.py +++ b/sphinx/directives/code.py @@ -85,7 +85,7 @@ def container_wrapper( node = parsed[0] if isinstance(node, nodes.system_message): msg = __('Invalid caption: %s') % node.astext() - raise ValueError(msg) # NoQA: TRY004 + raise ValueError(msg) # ruff: ignore[type-check-without-type-error] if isinstance(node, nodes.Element): caption_node = nodes.caption(node.rawsource, '', *node.children) caption_node.source = literal_node.source diff --git a/sphinx/directives/patches.py b/sphinx/directives/patches.py index 578263dcf8..5979b2d8ae 100644 --- a/sphinx/directives/patches.py +++ b/sphinx/directives/patches.py @@ -178,7 +178,7 @@ class MathDirective(SphinxDirective): node = cast('nodes.math_block', ret[0]) # assign label automatically if math_number_all enabled - if node['label'] == '' or (self.config.math_number_all and not node['label']): # NoQA: PLC1901 + if node['label'] == '' or (self.config.math_number_all and not node['label']): # ruff: ignore[compare-to-empty-string] seq = self.env.new_serialno('sphinx.ext.math#equations') node['label'] = f'{self.env.current_document.docname}:{seq}' diff --git a/sphinx/domains/c/__init__.py b/sphinx/domains/c/__init__.py index 194916122c..91f548d402 100644 --- a/sphinx/domains/c/__init__.py +++ b/sphinx/domains/c/__init__.py @@ -48,7 +48,7 @@ if TYPE_CHECKING: # re-export objects for backwards compatibility # See: https://github.com/sphinx-doc/sphinx/issues/12295 -from sphinx.domains.c._ast import ( # NoQA: F401 +from sphinx.domains.c._ast import ( # ruff: ignore[unused-import] ASTAlignofExpr, ASTArray, ASTAssignmentExpr, diff --git a/sphinx/domains/c/_parser.py b/sphinx/domains/c/_parser.py index 17800e55f9..1f6da643ca 100644 --- a/sphinx/domains/c/_parser.py +++ b/sphinx/domains/c/_parser.py @@ -865,7 +865,7 @@ class DefinitionParser(BaseParser): self, outer: str | None = None, allow_fallback: bool = True ) -> ASTInitializer | None: self.skip_ws() - if outer == 'member' and False: # NoQA: SIM223,TD005 # TODO + if outer == 'member' and False: # ruff: ignore[expr-and-false, missing-todo-description] # TODO braced_init = self._parse_braced_init_list() if braced_init is not None: return ASTInitializer(braced_init, hasAssign=False) diff --git a/sphinx/domains/cpp/__init__.py b/sphinx/domains/cpp/__init__.py index 0ccdc106c4..6334fabd0e 100644 --- a/sphinx/domains/cpp/__init__.py +++ b/sphinx/domains/cpp/__init__.py @@ -52,7 +52,7 @@ if TYPE_CHECKING: # re-export objects for backwards compatibility # See: https://github.com/sphinx-doc/sphinx/issues/12295 -from sphinx.domains.cpp._ast import ( # NoQA: F401 +from sphinx.domains.cpp._ast import ( # ruff: ignore[unused-import] ASTAlignofExpr, ASTArray, ASTAssignmentExpr, @@ -1064,7 +1064,7 @@ class CPPDomain(Domain): objtypes = self.objtypes_for_role(typ) if objtypes: return decl_typ in objtypes - logger.debug(f'Type is {typ}, declaration type is {decl_typ}') # NoQA: G004 + logger.debug(f'Type is {typ}, declaration type is {decl_typ}') # ruff: ignore[logging-f-string] raise AssertionError def _resolve_xref_inner( diff --git a/sphinx/domains/python/__init__.py b/sphinx/domains/python/__init__.py index a23207ea3c..0603cca43c 100644 --- a/sphinx/domains/python/__init__.py +++ b/sphinx/domains/python/__init__.py @@ -40,11 +40,11 @@ if TYPE_CHECKING: # re-export objects for backwards compatibility # See: https://github.com/sphinx-doc/sphinx/issues/12295 -from sphinx.domains.python._annotations import ( # NoQA: F401 +from sphinx.domains.python._annotations import ( # ruff: ignore[unused-import] _parse_arglist, # for sphinx-immaterial type_to_xref, ) -from sphinx.domains.python._object import ( # NoQA: F401 +from sphinx.domains.python._object import ( # ruff: ignore[unused-import] PyField, PyGroupedField, PyTypedField, diff --git a/sphinx/domains/python/_annotations.py b/sphinx/domains/python/_annotations.py index f476ff22fd..8e2043c98b 100644 --- a/sphinx/domains/python/_annotations.py +++ b/sphinx/domains/python/_annotations.py @@ -607,7 +607,7 @@ def _pseudo_parse_arglist( stack.pop() ends_close -= 1 if len(stack) != 1: - raise IndexError # NoQA: TRY301 + raise IndexError # ruff: ignore[raise-within-try] except IndexError: # if there are too few or too many elements on the stack, just give up # and treat the whole argument list as one argument, discarding the diff --git a/sphinx/domains/std/__init__.py b/sphinx/domains/std/__init__.py index f88aa97b40..0a26c63e92 100644 --- a/sphinx/domains/std/__init__.py +++ b/sphinx/domains/std/__init__.py @@ -634,7 +634,7 @@ class ProductionList(SphinxDirective): def production_group( *, lines: MutableSequence[str], - options: dict[str, Any], # NoQA: ARG004 + options: dict[str, Any], # ruff: ignore[unused-static-method-argument] ) -> str: # get production_group if not lines or ':' in lines[0]: diff --git a/sphinx/environment/__init__.py b/sphinx/environment/__init__.py index a5cb87e8eb..16c07b0918 100644 --- a/sphinx/environment/__init__.py +++ b/sphinx/environment/__init__.py @@ -1178,7 +1178,7 @@ class _CurrentDocument: return self._extension_data.setdefault(key, default) def clear(self) -> None: - _CurrentDocument.__init__(self) # NoQA: PLC2801 + _CurrentDocument.__init__(self) # ruff: ignore[unnecessary-dunder-call] def update(self, other: Iterable[tuple[str, Any]] = (), /, **kwargs: Any) -> None: other_dict = dict(other) if not isinstance(other, dict) else other diff --git a/sphinx/environment/collectors/asset.py b/sphinx/environment/collectors/asset.py index a1af7c3347..e57d2c7cda 100644 --- a/sphinx/environment/collectors/asset.py +++ b/sphinx/environment/collectors/asset.py @@ -112,7 +112,7 @@ class ImageCollector(EnvironmentCollector): node: Node, ) -> None: globbed: dict[str, list[str]] = {} - for filename in glob(imgpath): # NoQA: PTH207 + for filename in glob(imgpath): # ruff: ignore[glob] new_imgpath = _relative_path(Path(filename), srcdir) try: mimetype = guess_mimetype(filename) diff --git a/sphinx/ext/apidoc/_generate.py b/sphinx/ext/apidoc/_generate.py index 131f53cad3..ad1995d816 100644 --- a/sphinx/ext/apidoc/_generate.py +++ b/sphinx/ext/apidoc/_generate.py @@ -208,7 +208,7 @@ def is_skipped_package( if not Path(dirname).is_dir(): return False - files = glob.glob(str(Path(dirname, '*.py'))) # NoQA: PTH207 + files = glob.glob(str(Path(dirname, '*.py'))) # ruff: ignore[glob] regular_package = any(f for f in files if is_initpy(f)) if not regular_package and not opts.implicit_namespaces: # *dirname* is not both a regular package and an implicit namespace package diff --git a/sphinx/ext/autodoc/_directive.py b/sphinx/ext/autodoc/_directive.py index 7b90c0a3a8..9f6eb53ca4 100644 --- a/sphinx/ext/autodoc/_directive.py +++ b/sphinx/ext/autodoc/_directive.py @@ -20,7 +20,7 @@ if TYPE_CHECKING: from sphinx.ext.autodoc._property_types import _AutodocObjType -class DummyOptionSpec(dict[str, 'Callable[[str], str]']): # NoQA: FURB189 +class DummyOptionSpec(dict[str, 'Callable[[str], str]']): # ruff: ignore[subclass-builtin] """An option_spec allows any options.""" def __bool__(self) -> bool: @@ -81,7 +81,7 @@ class AutodocDirective(SphinxDirective): ) except (KeyError, ValueError, TypeError) as exc: # an option is either unknown or has a wrong type - LOGGER.error( # NoQA: TRY400 + LOGGER.error( # ruff: ignore[error-instead-of-exception] 'An option to %s is either unknown or has an invalid value: %s', self.name, exc, diff --git a/sphinx/ext/autodoc/_dynamic/_importer.py b/sphinx/ext/autodoc/_dynamic/_importer.py index 276c5c22af..468289a60b 100644 --- a/sphinx/ext/autodoc/_dynamic/_importer.py +++ b/sphinx/ext/autodoc/_dynamic/_importer.py @@ -217,14 +217,14 @@ def _import_module(modname: str, try_reload: bool = False) -> Any: spec = find_spec(modname) if spec is None: msg = f'No module named {modname!r}' - raise ModuleNotFoundError(msg, name=modname) # NoQA: TRY301 + raise ModuleNotFoundError(msg, name=modname) # ruff: ignore[raise-within-try] spec, pyi_path = _find_type_stub_spec(spec, modname) if skip_pyi or pyi_path is None: module = importlib.import_module(modname) else: if spec.loader is None: msg = 'missing loader' - raise ImportError(msg, name=spec.name) # NoQA: TRY301 + raise ImportError(msg, name=spec.name) # ruff: ignore[raise-within-try] sys.modules[modname] = module = module_from_spec(spec) spec.loader.exec_module(module) except ImportError: diff --git a/sphinx/ext/autodoc/_dynamic/_member_finder.py b/sphinx/ext/autodoc/_dynamic/_member_finder.py index 9fc54467d8..47413138f0 100644 --- a/sphinx/ext/autodoc/_dynamic/_member_finder.py +++ b/sphinx/ext/autodoc/_dynamic/_member_finder.py @@ -832,7 +832,7 @@ def _should_keep_member( if is_private: if has_attr_doc or has_doc: - if private_members is None: # NoQA: SIM114 + if private_members is None: # ruff: ignore[if-with-same-arms] return False elif has_doc and is_filtered_inherited_member: return False diff --git a/sphinx/ext/autodoc/_dynamic/_mock.py b/sphinx/ext/autodoc/_dynamic/_mock.py index 99314b7a11..c575a34ce5 100644 --- a/sphinx/ext/autodoc/_dynamic/_mock.py +++ b/sphinx/ext/autodoc/_dynamic/_mock.py @@ -30,7 +30,7 @@ class _MockObject: # Attributes listed here should not be mocked and rather raise an Attribute error: __sphinx_empty_attrs__: Set[str] = frozenset(('__typing_subst__',)) - def __new__(cls, *args: Any, **kwargs: Any) -> Any: # NoQA: ARG004 + def __new__(cls, *args: Any, **kwargs: Any) -> Any: # ruff: ignore[unused-static-method-argument] if len(args) == 3 and isinstance(args[1], tuple): superclass = args[1][-1].__class__ if superclass is cls: diff --git a/sphinx/ext/autodoc/_dynamic/_signatures.py b/sphinx/ext/autodoc/_dynamic/_signatures.py index de55c44fb9..219e9325eb 100644 --- a/sphinx/ext/autodoc/_dynamic/_signatures.py +++ b/sphinx/ext/autodoc/_dynamic/_signatures.py @@ -349,7 +349,7 @@ def _extract_signatures_from_docstrings( stripped_docstrings = [list(l) for l in (docstrings or ())] for i, doclines in enumerate(docstrings): j = 0 - for j, line in enumerate(doclines): # NoQA: B007 + for j, line in enumerate(doclines): # ruff: ignore[unused-loop-control-variable] if not line: # no lines in docstring, no match break @@ -583,7 +583,7 @@ def _get_object_for_signature( return obj, False if props.obj_type == 'method': - if obj == object.__init__ and parent != object: # NoQA: E721 + if obj == object.__init__ and parent != object: # ruff: ignore[type-comparison] # Classes not having own __init__() method are shown as no arguments. # # Note: The signature of object.__init__() is (self, /, *args, **kwargs). @@ -619,7 +619,7 @@ def _annotate_to_first_argument( if len(sig.parameters) == first_arg_idx: return None - def dummy(): # type: ignore[no-untyped-def] # NoQA: ANN202 + def dummy(): # type: ignore[no-untyped-def] # ruff: ignore[missing-return-type-private-function] pass params = list(sig.parameters.values()) diff --git a/sphinx/ext/autodoc/_event_listeners.py b/sphinx/ext/autodoc/_event_listeners.py index ec04fbec2f..2bd2d86247 100644 --- a/sphinx/ext/autodoc/_event_listeners.py +++ b/sphinx/ext/autodoc/_event_listeners.py @@ -25,7 +25,7 @@ if TYPE_CHECKING: /, ) -> None: ... - class _AutodocBeforeProcessSignatureListener(Protocol): # NoQA: PYI046 + class _AutodocBeforeProcessSignatureListener(Protocol): # ruff: ignore[unused-private-protocol] # parameter names are non-normative def __call__( self, @@ -35,7 +35,7 @@ if TYPE_CHECKING: /, ) -> None: ... - class _AutodocProcessSignatureListener(Protocol): # NoQA: PYI046 + class _AutodocProcessSignatureListener(Protocol): # ruff: ignore[unused-private-protocol] # parameter names are non-normative # returns: (args, retann) | None def __call__( @@ -50,7 +50,7 @@ if TYPE_CHECKING: /, ) -> tuple[str | None, str | None] | None: ... - class _AutodocProcessBasesListener(Protocol): # NoQA: PYI046 + class _AutodocProcessBasesListener(Protocol): # ruff: ignore[unused-private-protocol] # parameter names are non-normative def __call__( self, @@ -62,7 +62,7 @@ if TYPE_CHECKING: /, ) -> None: ... - class _AutodocSkipMemberListener(Protocol): # NoQA: PYI046 + class _AutodocSkipMemberListener(Protocol): # ruff: ignore[unused-private-protocol] # parameter names are non-normative # returns: skip_member def __call__( diff --git a/sphinx/ext/autodoc/_legacy_class_based/_directive_options.py b/sphinx/ext/autodoc/_legacy_class_based/_directive_options.py index bc8a206cc1..728240a176 100644 --- a/sphinx/ext/autodoc/_legacy_class_based/_directive_options.py +++ b/sphinx/ext/autodoc/_legacy_class_based/_directive_options.py @@ -87,7 +87,7 @@ def merge_members_option(options: dict[str, Any]) -> None: members.append(member) -class Options(dict[str, Any]): # NoQA: FURB189 +class Options(dict[str, Any]): # ruff: ignore[subclass-builtin] """A dict/attribute hybrid that returns None on nonexisting keys.""" def copy(self) -> Options: diff --git a/sphinx/ext/autodoc/_legacy_class_based/_documenters.py b/sphinx/ext/autodoc/_legacy_class_based/_documenters.py index c70acecf13..1c48e5643a 100644 --- a/sphinx/ext/autodoc/_legacy_class_based/_documenters.py +++ b/sphinx/ext/autodoc/_legacy_class_based/_documenters.py @@ -617,7 +617,7 @@ class Documenter: self.options.special_members and membername in self.options.special_members ): - if membername == '__doc__': # NoQA: SIM114 + if membername == '__doc__': # ruff: ignore[if-with-same-arms] keep = False elif is_filtered_inherited_member(membername, obj): keep = False @@ -636,7 +636,7 @@ class Documenter: keep = True elif want_all and isprivate: if has_doc or self.options.undoc_members: - if self.options.private_members is None: # NoQA: SIM114 + if self.options.private_members is None: # ruff: ignore[if-with-same-arms] keep = False elif is_filtered_inherited_member(membername, obj): keep = False @@ -1378,7 +1378,7 @@ class FunctionDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # typ if len(sig.parameters) == 0: return None - def dummy(): # type: ignore[no-untyped-def] # NoQA: ANN202 + def dummy(): # type: ignore[no-untyped-def] # ruff: ignore[missing-return-type-private-function] pass params = list(sig.parameters.values()) @@ -2202,7 +2202,7 @@ class MethodDocumenter(DocstringSignatureMixin, ClassLevelDocumenter): # type: kwargs.setdefault('short_literals', True) try: - if self.object == object.__init__ and self.parent != object: # NoQA: E721 + if self.object == object.__init__ and self.parent != object: # ruff: ignore[type-comparison] # Classes not having own __init__() method are shown as no arguments. # # Note: The signature of object.__init__() is (self, /, *args, **kwargs). @@ -2361,7 +2361,7 @@ class MethodDocumenter(DocstringSignatureMixin, ClassLevelDocumenter): # type: if len(sig.parameters) == 1: return None - def dummy(): # type: ignore[no-untyped-def] # NoQA: ANN202 + def dummy(): # type: ignore[no-untyped-def] # ruff: ignore[missing-return-type-private-function] pass params = list(sig.parameters.values()) diff --git a/sphinx/ext/autodoc/_sentinels.py b/sphinx/ext/autodoc/_sentinels.py index b7025163db..7d2ad013e5 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 # ty: ignore[invalid-type-form, invalid-return-type] + return Union[self, other] # ruff: ignore[non-pep604-annotation-union] # ty: ignore[invalid-type-form, invalid-return-type] def __ror__(self, other: object) -> _SpecialForm: from typing import Union - return Union[other, self] # NoQA: UP007 # ty: ignore[invalid-type-form, invalid-return-type] + return Union[other, self] # ruff: ignore[non-pep604-annotation-union] # ty: ignore[invalid-type-form, invalid-return-type] def __getstate__(self) -> NoReturn: msg = f'Cannot pickle {self._name}' diff --git a/sphinx/ext/autodoc/_shared.py b/sphinx/ext/autodoc/_shared.py index 203d85a231..211bbaf8f3 100644 --- a/sphinx/ext/autodoc/_shared.py +++ b/sphinx/ext/autodoc/_shared.py @@ -14,7 +14,7 @@ if TYPE_CHECKING: from sphinx.config import Config from sphinx.util.typing import _RestifyMode - class _AttrGetter(Protocol): # NoQA: PYI046 + class _AttrGetter(Protocol): # ruff: ignore[unused-private-protocol] def __call__(self, obj: Any, name: str, default: Any = ..., /) -> Any: ... diff --git a/sphinx/ext/autodoc/directive.py b/sphinx/ext/autodoc/directive.py index 5d5b7ab34f..9fd7634227 100644 --- a/sphinx/ext/autodoc/directive.py +++ b/sphinx/ext/autodoc/directive.py @@ -51,7 +51,7 @@ AUTODOC_EXTENDABLE_OPTIONS = frozenset({ # Retained: legacy class-based -class DummyOptionSpec(dict[str, Callable[[str], str]]): # NoQA: FURB189 +class DummyOptionSpec(dict[str, Callable[[str], str]]): # ruff: ignore[subclass-builtin] """An option_spec allows any options.""" def __bool__(self) -> bool: @@ -150,7 +150,7 @@ class AutodocDirective(SphinxDirective): ) except (KeyError, ValueError, TypeError) as exc: # an option is either unknown or has a wrong type - LOGGER.error( # NoQA: TRY400 + LOGGER.error( # ruff: ignore[error-instead-of-exception] 'An option to %s is either unknown or has an invalid value: %s', self.name, exc, diff --git a/sphinx/ext/autodoc/importer.py b/sphinx/ext/autodoc/importer.py index 02cf4d14f5..fe362c6e02 100644 --- a/sphinx/ext/autodoc/importer.py +++ b/sphinx/ext/autodoc/importer.py @@ -8,9 +8,9 @@ from typing import TYPE_CHECKING, NamedTuple from sphinx.errors import PycodeError from sphinx.ext.autodoc._dynamic._importer import ( - _find_type_stub_spec, # NoQA: F401 - _reload_module, # NoQA: F401 - _StubFileLoader, # NoQA: F401 + _find_type_stub_spec, # ruff: ignore[unused-import] + _reload_module, # ruff: ignore[unused-import] + _StubFileLoader, # ruff: ignore[unused-import] ) from sphinx.ext.autodoc._dynamic._importer import ( _import_module as import_module, @@ -18,7 +18,7 @@ from sphinx.ext.autodoc._dynamic._importer import ( from sphinx.ext.autodoc._dynamic._importer import _mangle_name as mangle from sphinx.ext.autodoc._dynamic._member_finder import ( _filter_enum_dict, - _is_native_enum_api, # NoQA: F401 + _is_native_enum_api, # ruff: ignore[unused-import] unmangle, ) from sphinx.ext.autodoc._dynamic._mock import ismock, undecorate diff --git a/sphinx/ext/autodoc/mock.py b/sphinx/ext/autodoc/mock.py index 1fb4330bdf..144f21b754 100644 --- a/sphinx/ext/autodoc/mock.py +++ b/sphinx/ext/autodoc/mock.py @@ -1,13 +1,13 @@ from __future__ import annotations from sphinx.ext.autodoc._dynamic._mock import ( - MockFinder, # NoQA: F401 - MockLoader, # NoQA: F401 - _make_subclass, # NoQA: F401 - _MockModule, # NoQA: F401 - _MockObject, # NoQA: F401 - ismock, # NoQA: F401 - ismockmodule, # NoQA: F401 - mock, # NoQA: F401 - undecorate, # NoQA: F401 + MockFinder, # ruff: ignore[unused-import] + MockLoader, # ruff: ignore[unused-import] + _make_subclass, # ruff: ignore[unused-import] + _MockModule, # ruff: ignore[unused-import] + _MockObject, # ruff: ignore[unused-import] + ismock, # ruff: ignore[unused-import] + ismockmodule, # ruff: ignore[unused-import] + mock, # ruff: ignore[unused-import] + undecorate, # ruff: ignore[unused-import] ) diff --git a/sphinx/ext/autodoc/preserve_defaults.py b/sphinx/ext/autodoc/preserve_defaults.py index fed033a7ec..a9afc2980a 100644 --- a/sphinx/ext/autodoc/preserve_defaults.py +++ b/sphinx/ext/autodoc/preserve_defaults.py @@ -9,11 +9,11 @@ from __future__ import annotations from typing import TYPE_CHECKING from sphinx.ext.autodoc._dynamic._preserve_defaults import ( - DefaultValue, # NoQA: F401 - _get_arguments, # NoQA: F401 - _get_arguments_inner, # NoQA: F401 - _is_lambda, # NoQA: F401 - get_default_value, # NoQA: F401 + DefaultValue, # ruff: ignore[unused-import] + _get_arguments, # ruff: ignore[unused-import] + _get_arguments_inner, # ruff: ignore[unused-import] + _is_lambda, # ruff: ignore[unused-import] + get_default_value, # ruff: ignore[unused-import] update_default_value, ) diff --git a/sphinx/ext/autodoc/type_comment.py b/sphinx/ext/autodoc/type_comment.py index e099ca7b49..ae2a876c10 100644 --- a/sphinx/ext/autodoc/type_comment.py +++ b/sphinx/ext/autodoc/type_comment.py @@ -6,8 +6,8 @@ from typing import TYPE_CHECKING from sphinx.ext.autodoc._dynamic._type_comments import ( _update_annotations_using_type_comments, - not_suppressed, # NoQA: F401 - signature_from_ast, # NoQA: F401 + not_suppressed, # ruff: ignore[unused-import] + signature_from_ast, # ruff: ignore[unused-import] ) if TYPE_CHECKING: diff --git a/sphinx/ext/autosummary/__init__.py b/sphinx/ext/autosummary/__init__.py index 6bba9bd0ff..4ebb8fc7f8 100644 --- a/sphinx/ext/autosummary/__init__.py +++ b/sphinx/ext/autosummary/__init__.py @@ -726,7 +726,7 @@ def _import_by_name(name: str, grouped_exception: bool = True) -> tuple[Any, Any except (ValueError, ImportError, AttributeError, KeyError) as exc: errors.append(exc) if grouped_exception: - raise ImportExceptionGroup('', errors) from None # NoQA: EM101 + raise ImportExceptionGroup('', errors) from None # ruff: ignore[raw-string-in-exception] else: raise ImportError(*exc.args) from exc diff --git a/sphinx/ext/autosummary/generate.py b/sphinx/ext/autosummary/generate.py index aec02012dd..dbdb8bd437 100644 --- a/sphinx/ext/autosummary/generate.py +++ b/sphinx/ext/autosummary/generate.py @@ -239,7 +239,7 @@ class ModuleScanner: try: if ('', name) in attr_docs: imported = False - elif inspect.ismodule(value): # NoQA: SIM114 + elif inspect.ismodule(value): # ruff: ignore[if-with-same-arms] imported = True elif safe_getattr(value, '__module__') != self.object.__name__: imported = True @@ -767,7 +767,7 @@ def find_autosummary_in_docstring( pass except ImportExceptionGroup as exc: errors = '\n'.join({f'* {type(e).__name__}: {e}' for e in exc.exceptions}) - logger.warning(f'Failed to import {name}.\nPossible hints:\n{errors}') # NoQA: G004 + logger.warning(f'Failed to import {name}.\nPossible hints:\n{errors}') # ruff: ignore[logging-f-string] except SystemExit: logger.warning( "Failed to import '%s'; the module executes module level " diff --git a/sphinx/ext/coverage.py b/sphinx/ext/coverage.py index cd83bcbaec..db5bfe758c 100644 --- a/sphinx/ext/coverage.py +++ b/sphinx/ext/coverage.py @@ -177,7 +177,7 @@ class CoverageBuilder(Builder): self.c_sourcefiles: list[str] = [] for pattern in self.config.coverage_c_path: pattern = self.srcdir / pattern - self.c_sourcefiles.extend(glob.glob(str(pattern))) # NoQA: PTH207 + self.c_sourcefiles.extend(glob.glob(str(pattern))) # ruff: ignore[glob] self.c_regexes: list[tuple[str, re.Pattern[str]]] = [] for name, exp in self.config.coverage_c_regexes.items(): @@ -264,7 +264,7 @@ class CoverageBuilder(Builder): ) else: logger.info( - red('undocumented ') # NoQA: G003 + red('undocumented ') # ruff: ignore[logging-string-concat] + f'c api {f"{name} [{typ:>9}]":<30}' + red(' - in file ') + filename @@ -456,7 +456,7 @@ class CoverageBuilder(Builder): else: for func in undoc['funcs']: logger.info( - red('undocumented ') # NoQA: G003 + red('undocumented ') # ruff: ignore[logging-string-concat] + f'py function {func:<30}' + red(' - in module ') + name @@ -476,7 +476,7 @@ class CoverageBuilder(Builder): ) else: logger.info( - red('undocumented ') # NoQA: G003 + red('undocumented ') # ruff: ignore[logging-string-concat] + f'py class {class_name:<30}' + red(' - in module ') + name @@ -499,7 +499,7 @@ class CoverageBuilder(Builder): else: for meth in methods: logger.info( - red('undocumented ') # NoQA: G003 + red('undocumented ') # ruff: ignore[logging-string-concat] + f'py method {f"{class_name}.{meth}":<30}' + red(' - in module ') + name diff --git a/sphinx/ext/doctest.py b/sphinx/ext/doctest.py index 308c186f31..96f49512c4 100644 --- a/sphinx/ext/doctest.py +++ b/sphinx/ext/doctest.py @@ -420,10 +420,10 @@ class DocTestBuilder(Builder): condition = node['skipif'] context: dict[str, Any] = {} if self.config.doctest_global_setup: - exec(self.config.doctest_global_setup, context) # NoQA: S102 - should_skip = eval(condition, context) # NoQA: S307 + exec(self.config.doctest_global_setup, context) # ruff: ignore[exec-builtin] + should_skip = eval(condition, context) # ruff: ignore[suspicious-eval-usage] if self.config.doctest_global_cleanup: - exec(self.config.doctest_global_cleanup, context) # NoQA: S102 + exec(self.config.doctest_global_cleanup, context) # ruff: ignore[exec-builtin] return should_skip def test_doc(self, docname: str, doctree: Node) -> bool: diff --git a/sphinx/ext/graphviz.py b/sphinx/ext/graphviz.py index 8ba99cc24a..bd43e7936e 100644 --- a/sphinx/ext/graphviz.py +++ b/sphinx/ext/graphviz.py @@ -239,7 +239,7 @@ def fix_svg_relative_paths( ) -> None: """Change relative links in generated svg files to be relative to imgpath.""" env = self.builder.env - tree = ET.parse(filepath) # NoQA: S314 + tree = ET.parse(filepath) # ruff: ignore[suspicious-xml-element-tree-usage] root = tree.getroot() ns = {'svg': 'http://www.w3.org/2000/svg', 'xlink': 'http://www.w3.org/1999/xlink'} href_name = '{http://www.w3.org/1999/xlink}href' diff --git a/sphinx/ext/ifconfig.py b/sphinx/ext/ifconfig.py index dd0990a814..e9768ed5a8 100644 --- a/sphinx/ext/ifconfig.py +++ b/sphinx/ext/ifconfig.py @@ -58,7 +58,7 @@ def process_ifconfig_nodes(app: Sphinx, doctree: nodes.document, docname: str) - ns['builder'] = app.builder.name for node in list(doctree.findall(ifconfig)): try: - res = eval(node['expr'], ns) # NoQA: S307 + res = eval(node['expr'], ns) # ruff: ignore[suspicious-eval-usage] except Exception as err: # handle exceptions in a clean fashion from traceback import format_exception_only diff --git a/sphinx/ext/imgmath.py b/sphinx/ext/imgmath.py index a8f88c62a1..af4678578f 100644 --- a/sphinx/ext/imgmath.py +++ b/sphinx/ext/imgmath.py @@ -69,7 +69,7 @@ depthsvgcomment_re = re.compile(r'') def read_svg_depth(filename: str | os.PathLike[str]) -> int | None: """Read the depth from comment at last line of SVG file""" with open(filename, encoding='utf-8') as f: - for line in f: # NoQA: B007 + for line in f: # ruff: ignore[unused-loop-control-variable] pass # Only last line is checked matched = depthsvgcomment_re.match(line) diff --git a/sphinx/ext/intersphinx/_load.py b/sphinx/ext/intersphinx/_load.py index ab6a373fea..4cb09d3ffd 100644 --- a/sphinx/ext/intersphinx/_load.py +++ b/sphinx/ext/intersphinx/_load.py @@ -83,7 +83,7 @@ def validate_intersphinx_mapping(app: Sphinx, config: Config) -> None: 'Invalid value `%r` in intersphinx_mapping[%r]. ' 'Values must be a (target URI, inventory locations) pair.' ) - LOGGER.error(msg, value, name) # NoQA: TRY400 + LOGGER.error(msg, value, name) # ruff: ignore[error-instead-of-exception] del config.intersphinx_mapping[name] continue diff --git a/sphinx/jinja2glue.py b/sphinx/jinja2glue.py index fd44a84bcb..b5b1de472f 100644 --- a/sphinx/jinja2glue.py +++ b/sphinx/jinja2glue.py @@ -73,7 +73,7 @@ def _slice_index( count = 0 start = offset if slices == slice_number + 1: # last column - offset = len(seq) # NoQA: SIM113 + offset = len(seq) else: for value in values[offset:]: count += 1 + len(value[1][1]) diff --git a/sphinx/pycode/parser.py b/sphinx/pycode/parser.py index a325dd7966..f84494f7df 100644 --- a/sphinx/pycode/parser.py +++ b/sphinx/pycode/parser.py @@ -210,7 +210,7 @@ class AfterCommentParser(TokenProcessor): tokens += self.fetch_until([OP, ']']) elif current == INDENT: tokens += self.fetch_until(DEDENT) - elif current == [OP, ';']: # NoQA: SIM114 + elif current == [OP, ';']: # ruff: ignore[if-with-same-arms] break elif current and current.kind not in {OP, NAME, NUMBER, STRING}: break diff --git a/sphinx/search/__init__.py b/sphinx/search/__init__.py index ab547b27f3..7911012fe5 100644 --- a/sphinx/search/__init__.py +++ b/sphinx/search/__init__.py @@ -118,7 +118,9 @@ var Stemmer = function () { # SearchEnglish imported after SearchLanguage is defined due to circular import -from sphinx.search.en import SearchEnglish # NoQA: E402 +from sphinx.search.en import ( # ruff: ignore[module-import-not-at-top-of-file] + SearchEnglish, +) def parse_stop_word(source: str) -> set[str]: diff --git a/sphinx/testing/fixtures.py b/sphinx/testing/fixtures.py index c6fdebe6e2..791e0cd1ea 100644 --- a/sphinx/testing/fixtures.py +++ b/sphinx/testing/fixtures.py @@ -121,7 +121,7 @@ def app_params( return _app_params(args, kwargs) -_app_params = namedtuple('_app_params', 'args,kwargs') # NoQA: PYI024 +_app_params = namedtuple('_app_params', 'args,kwargs') # ruff: ignore[collections-named-tuple] @pytest.fixture diff --git a/sphinx/theming.py b/sphinx/theming.py index d62af9646e..7f9212ede5 100644 --- a/sphinx/theming.py +++ b/sphinx/theming.py @@ -511,22 +511,22 @@ def _migrate_conf_to_toml(argv: list[str]) -> int: raise SystemExit(0) argv = argv[1:] if len(argv) != 1: - print('Usage: python -m sphinx.theming conf_to_toml ') # NoQA: T201 + print('Usage: python -m sphinx.theming conf_to_toml ') # ruff: ignore[print] raise SystemExit(1) theme_dir = Path(argv[0]).resolve() conf_path = theme_dir / _THEME_CONF if not theme_dir.is_dir() or not conf_path.is_file(): - print( # NoQA: T201 + print( # ruff: ignore[print] f'{theme_dir!r} must be a path to a theme directory containing a "theme.conf" file' ) return 1 _cfg_parser = _load_theme_conf(conf_path) if not _cfg_parser.has_section('theme'): - print('The "theme" table is missing.') # NoQA: T201 + print('The "theme" table is missing.') # ruff: ignore[print] return 1 inherit = _cfg_parser.get('theme', 'inherit', fallback=None) if not inherit: - print('The "theme.inherit" setting is missing.') # NoQA: T201 + print('The "theme.inherit" setting is missing.') # ruff: ignore[print] return 1 toml_lines = [ @@ -571,7 +571,7 @@ def _migrate_conf_to_toml(argv: list[str]) -> int: toml_path = theme_dir / _THEME_TOML toml_path.write_text('\n'.join(toml_lines) + '\n', encoding='utf-8') - print(f'Written converted settings to {toml_path!r}') # NoQA: T201 + print(f'Written converted settings to {toml_path!r}') # ruff: ignore[print] return 0 diff --git a/sphinx/util/_files.py b/sphinx/util/_files.py index 68ac888fea..62f6774ab5 100644 --- a/sphinx/util/_files.py +++ b/sphinx/util/_files.py @@ -11,7 +11,7 @@ if TYPE_CHECKING: from collections.abc import Set -class FilenameUniqDict(dict[str, tuple[set[str], str]]): # NoQA: FURB189 +class FilenameUniqDict(dict[str, tuple[set[str], str]]): # ruff: ignore[subclass-builtin] """A dictionary that automatically generates unique names for its keys, interpreted as filenames, and keeps track of a set of docnames they appear in. Used for images and downloadable files in the environment. @@ -61,7 +61,7 @@ class FilenameUniqDict(dict[str, tuple[set[str], str]]): # NoQA: FURB189 self._existing = state -class DownloadFiles(dict[Path, tuple[set[str], _StrPath]]): # NoQA: FURB189 +class DownloadFiles(dict[Path, tuple[set[str], _StrPath]]): # ruff: ignore[subclass-builtin] """A special dictionary for download files. .. important:: This class would be refactored in nearly future. diff --git a/sphinx/util/_lines.py b/sphinx/util/_lines.py index 019cfd2fa1..8bb11520c8 100644 --- a/sphinx/util/_lines.py +++ b/sphinx/util/_lines.py @@ -11,17 +11,17 @@ def parse_line_num_spec(spec: str, total: int) -> list[int]: try: begend = part.strip().split('-') if begend == ['', '']: - raise ValueError # NoQA: TRY301 + raise ValueError # ruff: ignore[raise-within-try] if len(begend) == 1: items.append(int(begend[0]) - 1) elif len(begend) == 2: start = int(begend[0] or 1) # left half open (cf. -10) end = int(begend[1] or max(start, total)) # right half open (cf. 10-) if start > end: # invalid range (cf. 10-1) - raise ValueError # NoQA: TRY301 + raise ValueError # ruff: ignore[raise-within-try] items.extend(range(start - 1, end)) else: - raise ValueError # NoQA: TRY301 + raise ValueError # ruff: ignore[raise-within-try] except ValueError as exc: msg = f'invalid line number spec: {spec!r}' raise ValueError(msg) from exc diff --git a/sphinx/util/_pathlib.py b/sphinx/util/_pathlib.py index 73b07ec94a..bacbee02aa 100644 --- a/sphinx/util/_pathlib.py +++ b/sphinx/util/_pathlib.py @@ -44,7 +44,7 @@ if sys.platform == 'win32': # replace exists in both Path and str; # in Path it makes filesystem changes, so we use the safer str version warnings.warn(_MSG, RemovedInSphinx10Warning, stacklevel=2) - return self.__str__().replace(old, new, count) # NoQA: PLC2801 + return self.__str__().replace(old, new, count) # ruff: ignore[unnecessary-dunder-call] def __getattr__(self, item: str) -> Any: if item in _STR_METHODS: @@ -99,7 +99,7 @@ else: # replace exists in both Path and str; # in Path it makes filesystem changes, so we use the safer str version warnings.warn(_MSG, RemovedInSphinx10Warning, stacklevel=2) - return self.__str__().replace(old, new, count) # NoQA: PLC2801 + return self.__str__().replace(old, new, count) # ruff: ignore[unnecessary-dunder-call] def __getattr__(self, item: str) -> Any: if item in _STR_METHODS: diff --git a/sphinx/util/cfamily.py b/sphinx/util/cfamily.py index 96a4436c03..41b56bd608 100644 --- a/sphinx/util/cfamily.py +++ b/sphinx/util/cfamily.py @@ -339,7 +339,7 @@ class BaseParser: def status(self, msg: str) -> None: # for debugging indicator = '-' * self.pos + '^' - logger.debug(f'{msg}\n{self.definition}\n{indicator}') # NoQA: G004 + logger.debug(f'{msg}\n{self.definition}\n{indicator}') # ruff: ignore[logging-f-string] def fail(self, msg: str) -> NoReturn: errors = [] diff --git a/sphinx/util/console.py b/sphinx/util/console.py index 90d69411c8..190e321c33 100644 --- a/sphinx/util/console.py +++ b/sphinx/util/console.py @@ -5,7 +5,7 @@ from __future__ import annotations import shutil import sphinx._cli.util.colour -from sphinx._cli.util.colour import ( # NoQA: F401 +from sphinx._cli.util.colour import ( # ruff: ignore[unused-import] _create_input_mode_colour_func, black, blink, diff --git a/sphinx/util/display.py b/sphinx/util/display.py index e134f8caf7..0ba5e1c70c 100644 --- a/sphinx/util/display.py +++ b/sphinx/util/display.py @@ -44,7 +44,7 @@ def status_iterator[T]( if single_line: # clear the entire line ('Erase in Line') logger.info('\x1b[2K', nonl=True) - logger.info(f'{bold_summary}[{i / length: >4.0%}] ', nonl=True) # NoQA: G004 + logger.info(f'{bold_summary}[{i / length: >4.0%}] ', nonl=True) # ruff: ignore[logging-f-string] # Emit the string representation of ``item`` logger.info(stringify_func(item), nonl=True, color=color) # If in single-line mode, emit a carriage return to move the cursor @@ -75,14 +75,14 @@ class progress_message: ) -> bool: prefix = '' if self.nonl else bold(self.message + ': ') if isinstance(val, SkipProgressMessage): - logger.info(prefix + __('skipped')) # NoQA: G003 + logger.info(prefix + __('skipped')) # ruff: ignore[logging-string-concat] if val.args: logger.info(*val.args) return True elif val: - logger.info(prefix + __('failed')) # NoQA: G003 + logger.info(prefix + __('failed')) # ruff: ignore[logging-string-concat] else: - logger.info(prefix + __('done')) # NoQA: G003 + logger.info(prefix + __('done')) # ruff: ignore[logging-string-concat] return False diff --git a/sphinx/util/docutils.py b/sphinx/util/docutils.py index 12eb015b27..cecefb7fb4 100644 --- a/sphinx/util/docutils.py +++ b/sphinx/util/docutils.py @@ -840,7 +840,7 @@ def new_document(source_path: str, settings: Any = None) -> nodes.document: caches the result of docutils' and use it on second call for instantiation. This makes an instantiation of document nodes much faster. """ - global __document_cache__ # NoQA: PLW0603 + global __document_cache__ # ruff: ignore[global-statement] try: cached_settings, reporter = __document_cache__ except NameError: @@ -960,5 +960,5 @@ if docutils.__version_info__[:2] < (0, 22): else: from docutils.parsers.rst.roles import ( - normalize_options as _normalize_options, # NoQA: F401 # ty: ignore[unresolved-import] + normalize_options as _normalize_options, # ruff: ignore[unused-import] # ty: ignore[unresolved-import] ) diff --git a/sphinx/util/inspect.py b/sphinx/util/inspect.py index 7e750c876c..dbc728f1d2 100644 --- a/sphinx/util/inspect.py +++ b/sphinx/util/inspect.py @@ -619,10 +619,10 @@ class TypeAliasForwardRef: def __or__(self, other: Any) -> Any: # When evaluating type hints, our forward ref can appear in type expressions, # i.e. `Alias | None`. This means it needs to support ``__or__`` and ``__ror__``. - return typing.Union[self, other] # NoQA: UP007 + return typing.Union[self, other] # ruff: ignore[non-pep604-annotation-union] def __ror__(self, other: Any) -> Any: - return typing.Union[other, self] # NoQA: UP007 + return typing.Union[other, self] # ruff: ignore[non-pep604-annotation-union] class TypeAliasModule: diff --git a/sphinx/util/nodes.py b/sphinx/util/nodes.py index 3a1805a2ea..b0acc320b6 100644 --- a/sphinx/util/nodes.py +++ b/sphinx/util/nodes.py @@ -514,7 +514,7 @@ def inline_all_toctrees( if includefile not in traversed: try: traversed.append(includefile) - logger.info(indent + colorfunc(includefile)) # NoQA: G003 + logger.info(indent + colorfunc(includefile)) # ruff: ignore[logging-string-concat] subtree = inline_all_toctrees( builder, docnameset, diff --git a/sphinx/util/texescape.py b/sphinx/util/texescape.py index c8d715ab4d..5fef6d7731 100644 --- a/sphinx/util/texescape.py +++ b/sphinx/util/texescape.py @@ -29,8 +29,8 @@ tex_replacements = [ # map some special Unicode characters to similar ASCII ones # (even for Unicode LaTeX as may not be supported by OpenType font) ('⎽', r'\_'), - ('ℯ', r'e'), # U+212F # NoQA: RUF001 - ('ⅈ', r'i'), # U+2148 # NoQA: RUF001 + ('ℯ', r'e'), # U+212F # ruff: ignore[ambiguous-unicode-character-string] + ('ⅈ', r'i'), # U+2148 # ruff: ignore[ambiguous-unicode-character-string] # Greek alphabet not escaped: pdflatex handles it via textalpha and inputenc # OHM SIGN U+2126 is handled by LaTeX textcomp package ] diff --git a/sphinx/util/typing.py b/sphinx/util/typing.py index dc19754cbf..8257ecb4e6 100644 --- a/sphinx/util/typing.py +++ b/sphinx/util/typing.py @@ -183,7 +183,7 @@ class ExtensionMetadata(typing.TypedDict, total=False): if TYPE_CHECKING: - type _ExtensionSetupFunc = Callable[[Sphinx], ExtensionMetadata] # NoQA: PYI047 (false positive) + type _ExtensionSetupFunc = Callable[[Sphinx], ExtensionMetadata] # ruff: ignore[unused-private-type-alias] (false positive) def get_type_hints( @@ -586,12 +586,12 @@ def stringify_annotation( elif dataclasses.is_dataclass(m): # use stringify_annotation for the repr of field values rather than repr d_fields = ', '.join([ - f'{f.name}={stringify_annotation(getattr(m, f.name), mode=mode, short_literals=short_literals)}' # NoQA: E501 + f'{f.name}={stringify_annotation(getattr(m, f.name), mode=mode, short_literals=short_literals)}' # ruff: ignore[line-too-long] for f in dataclasses.fields(m) if f.repr ]) meta_args.append( - f'{stringify_annotation(type(m), mode=mode, short_literals=short_literals)}({d_fields})' # NoQA: E501 + f'{stringify_annotation(type(m), mode=mode, short_literals=short_literals)}({d_fields})' # ruff: ignore[line-too-long] ) else: meta_args.append(repr(m)) diff --git a/sphinx/writers/html5.py b/sphinx/writers/html5.py index 3c6060eaf1..6271f1f92f 100644 --- a/sphinx/writers/html5.py +++ b/sphinx/writers/html5.py @@ -342,7 +342,7 @@ class HTML5Translator(SphinxTranslator, BaseTranslator): ) atts['href'] = '#' + node['refid'] if not isinstance(node.parent, nodes.TextElement): - assert len(node) == 1 and isinstance(node[0], nodes.image) # NoQA: PT018 + assert len(node) == 1 and isinstance(node[0], nodes.image) # ruff: ignore[pytest-composite-assertion] atts['class'] += ' image-reference' if 'reftitle' in node: atts['title'] = node['reftitle'] diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py index d5cac29020..a77b7f671f 100644 --- a/sphinx/writers/latex.py +++ b/sphinx/writers/latex.py @@ -2575,7 +2575,7 @@ class LaTeXTranslator(SphinxTranslator): # FIXME: Workaround to avoid circular import # See: https://github.com/sphinx-doc/sphinx/issues/5433 -from sphinx.builders.latex.nodes import ( # NoQA: E402 # isort:skip +from sphinx.builders.latex.nodes import ( # ruff: ignore[module-import-not-at-top-of-file] # isort:skip HYPERLINK_SUPPORT_NODES, captioned_literal_block, footnotetext, diff --git a/sphinx/writers/text.py b/sphinx/writers/text.py index f6b3b7ee8f..d0d7f1639f 100644 --- a/sphinx/writers/text.py +++ b/sphinx/writers/text.py @@ -242,7 +242,7 @@ class Table: for colno, cell in enumerate(line): if cell.col != colno: continue - if lineno != cell.row: # NoQA: SIM114 + if lineno != cell.row: # ruff: ignore[if-with-same-arms] physical_text = '' elif physical_line >= len(cell.wrapped): physical_text = '' diff --git a/tests/roots/test-add_enumerable_node/enumerable_node.py b/tests/roots/test-add_enumerable_node/enumerable_node.py index 2cf93e9104..ecb68222be 100644 --- a/tests/roots/test-add_enumerable_node/enumerable_node.py +++ b/tests/roots/test-add_enumerable_node/enumerable_node.py @@ -37,7 +37,7 @@ def visit_numbered_text(self, node): raise nodes.SkipNode -def get_title(node): # NoQA: FURB118 +def get_title(node): # ruff: ignore[reimplemented-operator] return node['title'] diff --git a/tests/roots/test-ext-autodoc/autodoc_dummy_module.py b/tests/roots/test-ext-autodoc/autodoc_dummy_module.py index 2138031066..688ede0d5b 100644 --- a/tests/roots/test-ext-autodoc/autodoc_dummy_module.py +++ b/tests/roots/test-ext-autodoc/autodoc_dummy_module.py @@ -1,6 +1,6 @@ -from dummy import * # NoQA: F403 +from dummy import * # ruff: ignore[undefined-local-with-import-star] def test(): """Dummy function using dummy.*""" - dummy_function() # NoQA: F405 + dummy_function() # ruff: ignore[undefined-local-with-import-star-usage] diff --git a/tests/roots/test-ext-autodoc/target/TYPE_CHECKING.py b/tests/roots/test-ext-autodoc/target/TYPE_CHECKING.py index 6aa83e0a5a..9470aef03d 100644 --- a/tests/roots/test-ext-autodoc/target/TYPE_CHECKING.py +++ b/tests/roots/test-ext-autodoc/target/TYPE_CHECKING.py @@ -1,7 +1,9 @@ -# NoQA: N999 +# ruff: ignore[invalid-module-name] from __future__ import annotations -from gettext import NullTranslations # NoQA: TC003 +from gettext import ( + NullTranslations, # ruff: ignore[typing-only-standard-library-import] +) from typing import TYPE_CHECKING if TYPE_CHECKING: diff --git a/tests/roots/test-ext-autodoc/target/__init__.py b/tests/roots/test-ext-autodoc/target/__init__.py index 2b0b822e89..e124e1b7b5 100644 --- a/tests/roots/test-ext-autodoc/target/__init__.py +++ b/tests/roots/test-ext-autodoc/target/__init__.py @@ -88,15 +88,15 @@ class Class: """a documented instance attribute""" self._private_inst_attr = None #: a private instance attribute - def __special1__(self): # NoQA: PLW3201 + def __special1__(self): # ruff: ignore[bad-dunder-method-name] """documented special method""" - def __special2__(self): # NoQA: PLW3201 + def __special2__(self): # ruff: ignore[bad-dunder-method-name] # undocumented special method pass -class CustomDict(dict): # NoQA: FURB189 +class CustomDict(dict): # ruff: ignore[subclass-builtin] """Docstring.""" @@ -166,7 +166,7 @@ class DocstringSig: return 456 -class StrRepr(str): # NoQA: FURB189,SLOT000 +class StrRepr(str): # ruff: ignore[subclass-builtin, no-slots-in-str-subclass] """docstring""" def __repr__(self): diff --git a/tests/roots/test-ext-autodoc/target/autodoc_type_aliases.py b/tests/roots/test-ext-autodoc/target/autodoc_type_aliases.py index 846c48a432..7e8b10d023 100644 --- a/tests/roots/test-ext-autodoc/target/autodoc_type_aliases.py +++ b/tests/roots/test-ext-autodoc/target/autodoc_type_aliases.py @@ -1,6 +1,6 @@ from __future__ import annotations -import io # NoQA: TC003 +import io # ruff: ignore[typing-only-standard-library-import] from typing import TYPE_CHECKING, overload if TYPE_CHECKING: @@ -15,7 +15,7 @@ variable: myint variable2 = None # type: myint #: docstring -variable3: Optional[myint] # NoQA: UP045 +variable3: Optional[myint] # ruff: ignore[non-pep604-annotation-optional] def read(r: io.BytesIO) -> io.StringIO: diff --git a/tests/roots/test-ext-autodoc/target/classes.py b/tests/roots/test-ext-autodoc/target/classes.py index fd36ded952..c348c77030 100644 --- a/tests/roots/test-ext-autodoc/target/classes.py +++ b/tests/roots/test-ext-autodoc/target/classes.py @@ -1,7 +1,7 @@ from __future__ import annotations from inspect import Parameter, Signature -from typing import List, Union # NoQA: UP035 +from typing import List, Union # ruff: ignore[deprecated-import] class Foo: @@ -30,7 +30,7 @@ class Qux: pass -class Quux(List[Union[int, float]]): # NoQA: UP006,UP007 +class Quux(List[Union[int, float]]): # ruff: ignore[non-pep585-annotation, non-pep604-annotation-union] """A subclass of List[Union[int, float]]""" pass diff --git a/tests/roots/test-ext-autodoc/target/coroutine.py b/tests/roots/test-ext-autodoc/target/coroutine.py index d1355ed4a8..b2d48304ff 100644 --- a/tests/roots/test-ext-autodoc/target/coroutine.py +++ b/tests/roots/test-ext-autodoc/target/coroutine.py @@ -22,7 +22,7 @@ class AsyncClass: yield -async def _other_coro_func(): # NoQA: RUF029 +async def _other_coro_func(): # ruff: ignore[unused-async] return 'run' diff --git a/tests/roots/test-ext-autodoc/target/docstring_signature.py b/tests/roots/test-ext-autodoc/target/docstring_signature.py index a6c5aa504c..7a6a9ecdd8 100644 --- a/tests/roots/test-ext-autodoc/target/docstring_signature.py +++ b/tests/roots/test-ext-autodoc/target/docstring_signature.py @@ -25,11 +25,11 @@ class E: def __init__(self): r"""E(foo: int, bar: int, baz: int) -> None \ E(foo: str, bar: str, baz: str) -> None \ - E(foo: float, bar: float, baz: float)""" # NoQA: D209 + E(foo: float, bar: float, baz: float)""" # ruff: ignore[new-line-after-last-paragraph] class F: def __init__(self): """F(foo: int, bar: int, baz: int) -> None F(foo: str, bar: str, baz: str) -> None - F(foo: float, bar: float, baz: float)""" # NoQA: D209 + F(foo: float, bar: float, baz: float)""" # ruff: ignore[new-line-after-last-paragraph] diff --git a/tests/roots/test-ext-autodoc/target/enums.py b/tests/roots/test-ext-autodoc/target/enums.py index bcfb86503b..f7f9aa769c 100644 --- a/tests/roots/test-ext-autodoc/target/enums.py +++ b/tests/roots/test-ext-autodoc/target/enums.py @@ -1,4 +1,4 @@ -# ruff: noqa: PIE796 +# ruff: file-ignore[non-unique-enums] import enum from typing import final diff --git a/tests/roots/test-ext-autodoc/target/final.py b/tests/roots/test-ext-autodoc/target/final.py index bd233abb58..63ac452477 100644 --- a/tests/roots/test-ext-autodoc/target/final.py +++ b/tests/roots/test-ext-autodoc/target/final.py @@ -4,7 +4,7 @@ import typing from typing import final import typing_extensions -from typing_extensions import final as final_ext # noqa: UP035 +from typing_extensions import final as final_ext # ruff: ignore[deprecated-import] @typing.final diff --git a/tests/roots/test-ext-autodoc/target/functions.py b/tests/roots/test-ext-autodoc/target/functions.py index 54c8803a74..3fc9f39fb0 100644 --- a/tests/roots/test-ext-autodoc/target/functions.py +++ b/tests/roots/test-ext-autodoc/target/functions.py @@ -9,7 +9,7 @@ async def coroutinefunc(): pass -async def asyncgenerator(): # NoQA: RUF029 +async def asyncgenerator(): # ruff: ignore[unused-async] yield @@ -20,5 +20,5 @@ builtin_func = print partial_builtin_func = partial(print) -def slice_arg_func(arg: 'float64[:, :]'): # NoQA: F821 +def slice_arg_func(arg: 'float64[:, :]'): # ruff: ignore[undefined-name] pass diff --git a/tests/roots/test-ext-autodoc/target/generic_class.py b/tests/roots/test-ext-autodoc/target/generic_class.py index 3ab7415c1e..f0e90d3f05 100644 --- a/tests/roots/test-ext-autodoc/target/generic_class.py +++ b/tests/roots/test-ext-autodoc/target/generic_class.py @@ -7,7 +7,7 @@ T = TypeVar('T') # Test that typing.Generic's __new__ method does not mask our class' # __init__ signature. -class A(Generic[T]): # NoQA: UP046 +class A(Generic[T]): # ruff: ignore[non-pep695-generic-class] """docstring for A""" def __init__(self, a, b=None): diff --git a/tests/roots/test-ext-autodoc/target/inheritance.py b/tests/roots/test-ext-autodoc/target/inheritance.py index a8ddc5b921..564ce57f56 100644 --- a/tests/roots/test-ext-autodoc/target/inheritance.py +++ b/tests/roots/test-ext-autodoc/target/inheritance.py @@ -10,7 +10,7 @@ class Base: """Inherited class method.""" @staticmethod - def inheritedstaticmeth(cls): # NoQA: PLW0211 + def inheritedstaticmeth(cls): # ruff: ignore[bad-staticmethod-argument] """Inherited static method.""" @@ -26,6 +26,6 @@ class Derived(Base, AnotherBase): pass -class MyList(list): # NoQA: FURB189 +class MyList(list): # ruff: ignore[subclass-builtin] def meth(self): """docstring""" diff --git a/tests/roots/test-ext-autodoc/target/need_mocks.py b/tests/roots/test-ext-autodoc/target/need_mocks.py index 73782a2fde..1e5f81d21e 100644 --- a/tests/roots/test-ext-autodoc/target/need_mocks.py +++ b/tests/roots/test-ext-autodoc/target/need_mocks.py @@ -3,14 +3,16 @@ import missing_package1.missing_module1 import sphinx.missing_module4 from missing_module import missing_name from missing_package2 import missing_module2 -from missing_package3.missing_module3 import missing_name # NoQA: F811 +from missing_package3.missing_module3 import ( + missing_name, # ruff: ignore[redefined-while-unused] +) from sphinx.missing_module4 import missing_name2 @missing_name(int) def decorated_function(): """decorated_function docstring""" - return None # NoQA: RET501 + return None # ruff: ignore[unnecessary-return-none] def func(arg: missing_module.Class): @@ -27,7 +29,7 @@ class TestAutodoc: @missing_name def decorated_method(self): """TestAutodoc::decorated_method docstring""" - return None # NoQA: RET501 + return None # ruff: ignore[unnecessary-return-none] class Inherited(missing_module.Class): diff --git a/tests/roots/test-ext-autodoc/target/overload3.py b/tests/roots/test-ext-autodoc/target/overload3.py index a3cc34a9f8..d2f451b873 100644 --- a/tests/roots/test-ext-autodoc/target/overload3.py +++ b/tests/roots/test-ext-autodoc/target/overload3.py @@ -2,7 +2,7 @@ import typing from typing import TYPE_CHECKING, overload import typing_extensions -from typing_extensions import overload as over_ext # noqa: UP035 +from typing_extensions import overload as over_ext # ruff: ignore[deprecated-import] @overload diff --git a/tests/roots/test-ext-autodoc/target/pep695.py b/tests/roots/test-ext-autodoc/target/pep695.py index 3e57ed4baf..1985c21874 100644 --- a/tests/roots/test-ext-autodoc/target/pep695.py +++ b/tests/roots/test-ext-autodoc/target/pep695.py @@ -24,13 +24,13 @@ type Pep695Alias = Foo type Pep695AliasUndocumented = Foo -TypeAliasTypeExplicit = TypeAliasType('TypeAliasTypeExplicit', Foo) # NoQA: UP040 +TypeAliasTypeExplicit = TypeAliasType('TypeAliasTypeExplicit', Foo) # ruff: ignore[non-pep695-type-alias] """This is an explicitly constructed typing.TypeAlias.""" -HandlerTypeAliasType = TypeAliasType('HandlerTypeAliasType', type[Exception]) # NoQA: UP040 +HandlerTypeAliasType = TypeAliasType('HandlerTypeAliasType', type[Exception]) # ruff: ignore[non-pep695-type-alias] """This is an explicitly constructed generic alias typing.TypeAlias.""" -TypeAliasTypeExtension = typing_extensions.TypeAliasType('TypeAliasTypeExtension', Foo) # NoQA: UP040 +TypeAliasTypeExtension = typing_extensions.TypeAliasType('TypeAliasTypeExtension', Foo) # ruff: ignore[non-pep695-type-alias] """This is an explicitly constructed typing_extensions.TypeAlias.""" #: This is PEP695 complex type alias with doc comment. diff --git a/tests/roots/test-ext-autodoc/target/preserve_defaults.py b/tests/roots/test-ext-autodoc/target/preserve_defaults.py index 42a148a87b..a50c17e9b7 100644 --- a/tests/roots/test-ext-autodoc/target/preserve_defaults.py +++ b/tests/roots/test-ext-autodoc/target/preserve_defaults.py @@ -1,7 +1,7 @@ from __future__ import annotations from datetime import datetime -from typing import Any # NoQA: TC003 +from typing import Any # ruff: ignore[typing-only-standard-library-import] CONSTANT = 'foo' SENTINEL = object() @@ -10,7 +10,7 @@ SENTINEL = object() def foo( name: str = CONSTANT, sentinel: Any = SENTINEL, - now: datetime = datetime.now(), # NoQA: B008,DTZ005 + now: datetime = datetime.now(), # ruff: ignore[function-call-in-default-argument, call-datetime-now-without-tzinfo] color: int = 0xFFFFFF, *, kwarg1, @@ -26,7 +26,7 @@ class Class: self, name: str = CONSTANT, sentinel: Any = SENTINEL, - now: datetime = datetime.now(), # NoQA: B008,DTZ005 + now: datetime = datetime.now(), # ruff: ignore[function-call-in-default-argument, call-datetime-now-without-tzinfo] color: int = 0xFFFFFF, *, kwarg1, @@ -39,7 +39,7 @@ class Class: cls, name: str = CONSTANT, sentinel: Any = SENTINEL, - now: datetime = datetime.now(), # NoQA: B008,DTZ005 + now: datetime = datetime.now(), # ruff: ignore[function-call-in-default-argument, call-datetime-now-without-tzinfo] color: int = 0xFFFFFF, *, kwarg1, @@ -48,7 +48,7 @@ class Class: """docstring""" -get_sentinel = lambda custom=SENTINEL: custom # NoQA: E731 +get_sentinel = lambda custom=SENTINEL: custom # ruff: ignore[lambda-assignment] """docstring""" @@ -74,5 +74,5 @@ class MultiLine: (lambda self: 4, doc='docstring')) prop5 = property\ - (lambda self: 5, doc='docstring') # NoQA: E211 + (lambda self: 5, doc='docstring') # ruff: ignore[whitespace-before-parameters] # fmt: on diff --git a/tests/roots/test-ext-autodoc/target/preserve_defaults_special_constructs.py b/tests/roots/test-ext-autodoc/target/preserve_defaults_special_constructs.py index ba397f8671..dc3a99abd0 100644 --- a/tests/roots/test-ext-autodoc/target/preserve_defaults_special_constructs.py +++ b/tests/roots/test-ext-autodoc/target/preserve_defaults_special_constructs.py @@ -9,7 +9,7 @@ SENTINEL = object() #: docstring -ze_lambda = lambda z=SENTINEL: None # NoQA: E731 +ze_lambda = lambda z=SENTINEL: None # ruff: ignore[lambda-assignment] def foo(x, y, z=SENTINEL): @@ -50,5 +50,5 @@ class MyNamedTuple1(NamedTuple): c: list[int] = [1, 2, 3] -class MyNamedTuple2(namedtuple('Base', ('a', 'b'), defaults=(0, SENTINEL))): # NoQA: PYI024,SLOT002 +class MyNamedTuple2(namedtuple('Base', ('a', 'b'), defaults=(0, SENTINEL))): # ruff: ignore[collections-named-tuple, no-slots-in-namedtuple-subclass] """docstring""" diff --git a/tests/roots/test-ext-autodoc/target/slots.py b/tests/roots/test-ext-autodoc/target/slots.py index 3fa3f0798c..78a1f4752b 100644 --- a/tests/roots/test-ext-autodoc/target/slots.py +++ b/tests/roots/test-ext-autodoc/target/slots.py @@ -21,4 +21,4 @@ class Bar: class Baz: """docstring""" - __slots__ = 'attr' # NoQA: PLC0205 + __slots__ = 'attr' # ruff: ignore[single-string-slots] diff --git a/tests/roots/test-ext-autodoc/target/typed_vars.py b/tests/roots/test-ext-autodoc/target/typed_vars.py index a87bd6accd..b12d298af5 100644 --- a/tests/roots/test-ext-autodoc/target/typed_vars.py +++ b/tests/roots/test-ext-autodoc/target/typed_vars.py @@ -10,7 +10,7 @@ class _Descriptor: def __init__(self, name): self.__doc__ = f'This is {name}' - def __get__(self): # NoQA: PLE0302 + def __get__(self): # ruff: ignore[unexpected-special-method-signature] pass diff --git a/tests/roots/test-ext-autodoc/target/typehints.py b/tests/roots/test-ext-autodoc/target/typehints.py index b2448bf4b2..cfa428d020 100644 --- a/tests/roots/test-ext-autodoc/target/typehints.py +++ b/tests/roots/test-ext-autodoc/target/typehints.py @@ -1,7 +1,12 @@ from __future__ import annotations import pathlib -from typing import TYPE_CHECKING, Tuple, TypeVar, Union # NoQA: UP035 +from typing import ( # ruff: ignore[deprecated-import] + TYPE_CHECKING, + Tuple, + TypeVar, + Union, +) if TYPE_CHECKING: from typing import Any @@ -65,7 +70,7 @@ def tuple_args(x: tuple[int, int | str]) -> tuple[int, int]: class NewAnnotation: - def __new__(cls, i: int) -> NewAnnotation: # NoQA: PYI034 + def __new__(cls, i: int) -> NewAnnotation: # ruff: ignore[non-self-return-type] pass diff --git a/tests/roots/test-ext-autodoc/target/typevar.py b/tests/roots/test-ext-autodoc/target/typevar.py index 6cc088a821..7cd97e295f 100644 --- a/tests/roots/test-ext-autodoc/target/typevar.py +++ b/tests/roots/test-ext-autodoc/target/typevar.py @@ -12,10 +12,10 @@ T2 = TypeVar('T2') # A TypeVar not having doc comment T3 = TypeVar('T3', int, str) #: T4 -T4 = TypeVar('T4', covariant=True) # NoQA: PLC0105 +T4 = TypeVar('T4', covariant=True) # ruff: ignore[type-name-incorrect-variance] #: T5 -T5 = TypeVar('T5', contravariant=True) # NoQA: PLC0105 +T5 = TypeVar('T5', contravariant=True) # ruff: ignore[type-name-incorrect-variance] #: T6 T6 = NewType('T6', date) diff --git a/tests/roots/test-ext-autodoc/target/wrappedfunction.py b/tests/roots/test-ext-autodoc/target/wrappedfunction.py index d868c5756c..b8f58795a4 100644 --- a/tests/roots/test-ext-autodoc/target/wrappedfunction.py +++ b/tests/roots/test-ext-autodoc/target/wrappedfunction.py @@ -2,10 +2,12 @@ from __future__ import annotations from contextlib import contextmanager from functools import lru_cache -from typing import Generator # NoQA: TC003,UP035 +from typing import ( # ruff: ignore[typing-only-standard-library-import, deprecated-import] + Generator, +) -@lru_cache(maxsize=None) # NoQA: UP033 +@lru_cache(maxsize=None) # ruff: ignore[lru-cache-with-maxsize-none] def slow_function(message, timeout): """This function is slow.""" print(message) diff --git a/tests/roots/test-ext-autosummary-ext/dummy_module.py b/tests/roots/test-ext-autosummary-ext/dummy_module.py index a54b8362ac..cf8bf089f5 100644 --- a/tests/roots/test-ext-autosummary-ext/dummy_module.py +++ b/tests/roots/test-ext-autosummary-ext/dummy_module.py @@ -7,7 +7,7 @@ C.prop_attr1 C.prop_attr2 C.C2 -""" # NoQA: D212 +""" # ruff: ignore[multi-line-summary-first-line] def with_sentence(): diff --git a/tests/roots/test-ext-autosummary-ext/underscore_module_.py b/tests/roots/test-ext-autosummary-ext/underscore_module_.py index 908015ac8d..c6898f8949 100644 --- a/tests/roots/test-ext-autosummary-ext/underscore_module_.py +++ b/tests/roots/test-ext-autosummary-ext/underscore_module_.py @@ -4,7 +4,7 @@ class class_: """Class""" - def method_(_arg): # NoQA: N805 + def method_(_arg): # ruff: ignore[invalid-first-argument-name-for-method] """Method""" pass diff --git a/tests/roots/test-ext-autosummary-filename-map/autosummary_dummy_module.py b/tests/roots/test-ext-autosummary-filename-map/autosummary_dummy_module.py index 9ed0ce6687..b0bd3f779e 100644 --- a/tests/roots/test-ext-autosummary-filename-map/autosummary_dummy_module.py +++ b/tests/roots/test-ext-autosummary-filename-map/autosummary_dummy_module.py @@ -5,7 +5,7 @@ from typing import Union class Foo: - class Bar: # NoQA: D106 + class Bar: # ruff: ignore[undocumented-public-nested-class] pass def __init__(self): diff --git a/tests/roots/test-ext-autosummary-module_all/autosummary_dummy_package_all/__init__.py b/tests/roots/test-ext-autosummary-module_all/autosummary_dummy_package_all/__init__.py index e1ba34e63c..e66d154dff 100644 --- a/tests/roots/test-ext-autosummary-module_all/autosummary_dummy_package_all/__init__.py +++ b/tests/roots/test-ext-autosummary-module_all/autosummary_dummy_package_all/__init__.py @@ -10,4 +10,4 @@ def public_baz(): """Public Baz function""" -__all__ = ['PublicBar', 'public_foo', 'public_baz', 'extra_dummy_module'] # NoQA: F822 +__all__ = ['PublicBar', 'public_foo', 'public_baz', 'extra_dummy_module'] # ruff: ignore[undefined-export] diff --git a/tests/roots/test-ext-autosummary-recursive/package/module.py b/tests/roots/test-ext-autosummary-recursive/package/module.py index 30e6cb819e..c9b59decfc 100644 --- a/tests/roots/test-ext-autosummary-recursive/package/module.py +++ b/tests/roots/test-ext-autosummary-recursive/package/module.py @@ -1,4 +1,4 @@ -from os import * # NoQA: F403 +from os import * # ruff: ignore[undefined-local-with-import-star] class Foo: diff --git a/tests/roots/test-ext-autosummary-recursive/package/package/module.py b/tests/roots/test-ext-autosummary-recursive/package/package/module.py index 30e6cb819e..c9b59decfc 100644 --- a/tests/roots/test-ext-autosummary-recursive/package/package/module.py +++ b/tests/roots/test-ext-autosummary-recursive/package/package/module.py @@ -1,4 +1,4 @@ -from os import * # NoQA: F403 +from os import * # ruff: ignore[undefined-local-with-import-star] class Foo: diff --git a/tests/roots/test-ext-autosummary-recursive/package2/module.py b/tests/roots/test-ext-autosummary-recursive/package2/module.py index 30e6cb819e..c9b59decfc 100644 --- a/tests/roots/test-ext-autosummary-recursive/package2/module.py +++ b/tests/roots/test-ext-autosummary-recursive/package2/module.py @@ -1,4 +1,4 @@ -from os import * # NoQA: F403 +from os import * # ruff: ignore[undefined-local-with-import-star] class Foo: diff --git a/tests/roots/test-ext-autosummary/autosummary_dummy_module.py b/tests/roots/test-ext-autosummary/autosummary_dummy_module.py index c8575d3a12..ef395cbaad 100644 --- a/tests/roots/test-ext-autosummary/autosummary_dummy_module.py +++ b/tests/roots/test-ext-autosummary/autosummary_dummy_module.py @@ -23,7 +23,7 @@ class Foo: CONSTANT3 = None CONSTANT4 = None - class Bar: # NoQA: D106 + class Bar: # ruff: ignore[undocumented-public-nested-class] pass def __init__(self): @@ -42,7 +42,7 @@ class _Baz: pass -def bar(x: Union[int, str], y: int = 1) -> None: # NoQA: UP007 +def bar(x: Union[int, str], y: int = 1) -> None: # ruff: ignore[non-pep604-annotation-union] pass diff --git a/tests/roots/test-ext-inheritance_diagram/test.py b/tests/roots/test-ext-inheritance_diagram/test.py index 0146c5d0f3..bdf20e9bbb 100644 --- a/tests/roots/test-ext-inheritance_diagram/test.py +++ b/tests/roots/test-ext-inheritance_diagram/test.py @@ -18,5 +18,5 @@ class DocMainLevel(Foo): pass -class Alice(object): # NoQA: UP004 +class Alice(object): # ruff: ignore[useless-object-inheritance] pass diff --git a/tests/roots/test-ext-math-compat/conf.py b/tests/roots/test-ext-math-compat/conf.py index 82cc265bc9..8e0ee79bc9 100644 --- a/tests/roots/test-ext-math-compat/conf.py +++ b/tests/roots/test-ext-math-compat/conf.py @@ -4,7 +4,7 @@ from docutils.parsers.rst import Directive extensions = ['sphinx.ext.mathjax'] -def my_math_role(role, rawtext, text, lineno, inliner, options={}, content=[]): # NoQA: B006 +def my_math_role(role, rawtext, text, lineno, inliner, options={}, content=[]): # ruff: ignore[mutable-argument-default] text = 'E = mc^2' return [nodes.math(text, text)], [] diff --git a/tests/roots/test-ext-viewcode-find-package/conf.py b/tests/roots/test-ext-viewcode-find-package/conf.py index be67c6296e..4fd5addee9 100644 --- a/tests/roots/test-ext-viewcode-find-package/conf.py +++ b/tests/roots/test-ext-viewcode-find-package/conf.py @@ -8,7 +8,7 @@ extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] exclude_patterns = ['_build'] -if 'test_linkcode' in tags: # NoQA: F821 (tags is injected into conf.py) +if 'test_linkcode' in tags: # ruff: ignore[undefined-name] (tags is injected into conf.py) extensions.remove('sphinx.ext.viewcode') extensions.append('sphinx.ext.linkcode') diff --git a/tests/roots/test-ext-viewcode-find/not_a_package/submodule.py b/tests/roots/test-ext-viewcode-find/not_a_package/submodule.py index 48171d76ac..5133af3f4e 100644 --- a/tests/roots/test-ext-viewcode-find/not_a_package/submodule.py +++ b/tests/roots/test-ext-viewcode-find/not_a_package/submodule.py @@ -1,8 +1,8 @@ """ submodule -""" # NoQA: D212 +""" # ruff: ignore[multi-line-summary-first-line] -raise RuntimeError('This module should not get imported') # NoQA: EM101,TRY003 +raise RuntimeError('This module should not get imported') # ruff: ignore[raw-string-in-exception, raise-vanilla-args] def decorator(f): @@ -13,7 +13,7 @@ def decorator(f): def func1(a, b): """ this is func1 - """ # NoQA: D212 + """ # ruff: ignore[multi-line-summary-first-line] return a, b diff --git a/tests/roots/test-ext-viewcode/conf.py b/tests/roots/test-ext-viewcode/conf.py index a15e2eab58..3192562b48 100644 --- a/tests/roots/test-ext-viewcode/conf.py +++ b/tests/roots/test-ext-viewcode/conf.py @@ -9,7 +9,7 @@ extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] exclude_patterns = ['_build'] -if 'test_linkcode' in tags: # NoQA: F821 (tags is injected into conf.py) +if 'test_linkcode' in tags: # ruff: ignore[undefined-name] (tags is injected into conf.py) extensions.remove('sphinx.ext.viewcode') extensions.append('sphinx.ext.linkcode') diff --git a/tests/roots/test-inheritance/dummy/test.py b/tests/roots/test-inheritance/dummy/test.py index e3838e7f07..982c6af626 100644 --- a/tests/roots/test-inheritance/dummy/test.py +++ b/tests/roots/test-inheritance/dummy/test.py @@ -6,7 +6,7 @@ r"""Test with a class diagram like this:: / \ / \ E D F -""" # NoQA: D208 +""" # ruff: ignore[over-indentation] class A: diff --git a/tests/roots/test-inheritance/dummy/test_nested.py b/tests/roots/test-inheritance/dummy/test_nested.py index ccbde523d1..7b1a626abf 100644 --- a/tests/roots/test-inheritance/dummy/test_nested.py +++ b/tests/roots/test-inheritance/dummy/test_nested.py @@ -2,7 +2,7 @@ class A: - class B: # NoQA: D106 + class B: # ruff: ignore[undocumented-public-nested-class] pass diff --git a/tests/roots/test-root/autodoc_target.py b/tests/roots/test-root/autodoc_target.py index df9e6b853c..a0b6ef4f82 100644 --- a/tests/roots/test-root/autodoc_target.py +++ b/tests/roots/test-root/autodoc_target.py @@ -121,15 +121,15 @@ class Class(Base): """a documented instance attribute""" self._private_inst_attr = None #: a private instance attribute - def __special1__(self): # NoQA: PLW3201 + def __special1__(self): # ruff: ignore[bad-dunder-method-name] """documented special method""" - def __special2__(self): # NoQA: PLW3201 + def __special2__(self): # ruff: ignore[bad-dunder-method-name] # undocumented special method pass -class CustomDict(dict): # NoQA: FURB189 +class CustomDict(dict): # ruff: ignore[subclass-builtin] """Docstring.""" @@ -181,7 +181,7 @@ class DocstringSig: return 456 -class StrRepr(str): # NoQA: FURB189,SLOT000 +class StrRepr(str): # ruff: ignore[subclass-builtin, no-slots-in-str-subclass] def __repr__(self): return self diff --git a/tests/roots/test-root/conf.py b/tests/roots/test-root/conf.py index ae63715346..d7685ada6e 100644 --- a/tests/roots/test-root/conf.py +++ b/tests/roots/test-root/conf.py @@ -138,7 +138,7 @@ extlinks = { } # modify tags from conf.py -tags.add('confpytag') # NoQA: F821 (tags is injected into conf.py) +tags.add('confpytag') # ruff: ignore[undefined-name] (tags is injected into conf.py) # -- extension API diff --git a/tests/test_builders/test_build_epub.py b/tests/test_builders/test_build_epub.py index 728c0e2066..8c796ed4ad 100644 --- a/tests/test_builders/test_build_epub.py +++ b/tests/test_builders/test_build_epub.py @@ -48,7 +48,7 @@ class EPUBElementTree: @classmethod def fromstring(cls, string: str | bytes) -> Self: - tree = ET.fromstring(string) # NoQA: S314 # using known data in tests + tree = ET.fromstring(string) # ruff: ignore[suspicious-xml-element-tree-usage] # using known data in tests return cls(tree) def find(self, match: str) -> Self: @@ -511,7 +511,7 @@ def test_run_epubcheck(app: SphinxTestApp) -> None: try: subprocess.run( - ['java', '-jar', epubcheck, app.outdir / 'SphinxTests.epub'], # NoQA: S607 + ['java', '-jar', epubcheck, app.outdir / 'SphinxTests.epub'], # ruff: ignore[start-process-with-partial-path] capture_output=True, check=True, ) @@ -560,7 +560,7 @@ def test_epub_manifest_path_separator_normalization(app: SphinxTestApp) -> None: # Parse manifest and spine elements # Verify that all idrefs in spine match ids in manifest - tree = ET.parse(str(opf_path)) # noqa: S314 + tree = ET.parse(str(opf_path)) # ruff: ignore[suspicious-xml-element-tree-usage] root = tree.getroot() # Define namespace @@ -621,7 +621,7 @@ def test_epub_manifest_subdirectory_paths(app: SphinxTestApp) -> None: opf_path = app.outdir / 'content.opf' assert opf_path.exists() - tree = ET.parse(str(opf_path)) # noqa: S314 + tree = ET.parse(str(opf_path)) # ruff: ignore[suspicious-xml-element-tree-usage] root = tree.getroot() ns: dict[str, str] = {'opf': 'http://www.idpf.org/2007/opf'} @@ -652,7 +652,7 @@ def test_epub_spine_idref_consistency(app: SphinxTestApp) -> None: opf_path = app.outdir / 'content.opf' - tree = ET.parse(str(opf_path)) # noqa: S314 + tree = ET.parse(str(opf_path)) # ruff: ignore[suspicious-xml-element-tree-usage] root = tree.getroot() ns: dict[str, str] = {'opf': 'http://www.idpf.org/2007/opf'} diff --git a/tests/test_builders/test_build_latex.py b/tests/test_builders/test_build_latex.py index 71ee6d16d9..34c73f1668 100644 --- a/tests/test_builders/test_build_latex.py +++ b/tests/test_builders/test_build_latex.py @@ -49,7 +49,7 @@ STYLEFILES = [ # only run latex if all needed packages are there def kpsetest(*filenames: str) -> bool: try: - subprocess.run(['kpsewhich', *list(filenames)], capture_output=True, check=True) # NoQA: S607 + subprocess.run(['kpsewhich', *list(filenames)], capture_output=True, check=True) # ruff: ignore[start-process-with-partial-path] return True except (OSError, CalledProcessError): return False # command not found or exit with non-zero diff --git a/tests/test_domains/test_domain_c.py b/tests/test_domains/test_domain_c.py index 07421eb6c2..8b293a06b1 100644 --- a/tests/test_domains/test_domain_c.py +++ b/tests/test_domains/test_domain_c.py @@ -729,7 +729,7 @@ def extract_role_links(app, filename): lis = [l for l in t.split('\n') if l.startswith(' None: def test_mock_does_not_follow_upper_modules() -> None: - with mock(['sphinx.unknown.module']): # NoQA: SIM117 + with mock(['sphinx.unknown.module']): # ruff: ignore[multiple-with-statements] with pytest.raises(ImportError): import_module('sphinx.unknown') diff --git a/tests/test_ext_autodoc/test_ext_autodoc_signatures.py b/tests/test_ext_autodoc/test_ext_autodoc_signatures.py index f3f87e4d38..e260257e5f 100644 --- a/tests/test_ext_autodoc/test_ext_autodoc_signatures.py +++ b/tests/test_ext_autodoc/test_ext_autodoc_signatures.py @@ -129,7 +129,7 @@ def test_format_function_signatures() -> None: ) def test_format_function_signatures_pep695(params: str, expect: str) -> None: ns: dict[str, Any] = {} - exec(f'def f[T]{params}: pass', ns) # NoQA: S102 + exec(f'def f[T]{params}: pass', ns) # ruff: ignore[exec-builtin] f = ns['f'] assert format_sig('function', 'f', f) == (expect, '') assert format_sig('function', 'f', f, args='(...)') == ('(...)', '') @@ -138,7 +138,7 @@ def test_format_function_signatures_pep695(params: str, expect: str) -> None: '...', ) - exec(f'def f[T]{params} -> list[T]: return []', ns) # NoQA: S102 + exec(f'def f[T]{params} -> list[T]: return []', ns) # ruff: ignore[exec-builtin] f = ns['f'] assert format_sig('function', 'f', f) == (expect, 'list[T]') assert format_sig('function', 'f', f, args='(...)') == ('(...)', '') @@ -174,7 +174,7 @@ def test_format_class_signatures() -> None: pass class FNew: - def __new__(cls, a, b=None): # type: ignore[no-untyped-def] # NoQA: ARG004 + def __new__(cls, a, b=None): # type: ignore[no-untyped-def] # ruff: ignore[unused-static-method-argument] return super().__new__(cls) class FMeta(metaclass=SomeMeta): @@ -201,7 +201,7 @@ def test_format_class_signatures() -> None: def test_format_class_signatures_text_signature() -> None: - class ListSubclass(list): # type: ignore[type-arg] # NoQA: FURB189 + class ListSubclass(list): # type: ignore[type-arg] # ruff: ignore[subclass-builtin] pass # only supported if the python implementation decides to document it @@ -233,7 +233,7 @@ def test_format_class_signatures_init_both() -> None: __init__(a1, a2, kw1=True, kw2=False) some docstring for __init__. - """ # NoQA: D212 + """ # ruff: ignore[multi-line-summary-first-line] class G2(F2): pass @@ -254,7 +254,7 @@ def test_format_method_signatures() -> None: def foo1(self, b, *c): # type: ignore[no-untyped-def] pass - def foo2(b, *c): # type: ignore[no-untyped-def] # NoQA: N805 + def foo2(b, *c): # type: ignore[no-untyped-def] # ruff: ignore[invalid-first-argument-name-for-method] pass def foo3(self, d='\n'): # type: ignore[no-untyped-def] diff --git a/tests/test_ext_autodoc/test_ext_autodoc_typehints.py b/tests/test_ext_autodoc/test_ext_autodoc_typehints.py index 1a0a7d9fdd..3f32a29e0e 100644 --- a/tests/test_ext_autodoc/test_ext_autodoc_typehints.py +++ b/tests/test_ext_autodoc/test_ext_autodoc_typehints.py @@ -329,7 +329,7 @@ def test_autodoc_typehints_description(app: SphinxTestApp) -> None: app.build() context = (app.outdir / 'index.txt').read_text(encoding='utf8') - expect = '\n'.join(( # NoQA: FLY002 + expect = '\n'.join(( # ruff: ignore[static-join-to-f-string] 'target.typehints.incr(a, b=1)', '', ' Parameters:', @@ -342,7 +342,7 @@ def test_autodoc_typehints_description(app: SphinxTestApp) -> None: '', )) assert expect in context - expect = '\n'.join(( # NoQA: FLY002 + expect = '\n'.join(( # ruff: ignore[static-join-to-f-string] 'target.typehints.tuple_args(x)', '', ' Parameters:', @@ -355,7 +355,7 @@ def test_autodoc_typehints_description(app: SphinxTestApp) -> None: assert expect in context # Overloads still get displayed in the signature - expect = '\n'.join(( # NoQA: FLY002 + expect = '\n'.join(( # ruff: ignore[static-join-to-f-string] 'target.overload.sum(x: int, y: int = 0) -> int', 'target.overload.sum(x: float, y: float = 0.0) -> float', 'target.overload.sum(x: str, y: str = None) -> str', @@ -390,7 +390,7 @@ def test_autodoc_typehints_description_no_undoc(app: SphinxTestApp) -> None: app.build() # Restore the original content of the file context = (app.outdir / 'index.txt').read_text(encoding='utf8') - expect = '\n'.join(( # NoQA: FLY002 + expect = '\n'.join(( # ruff: ignore[static-join-to-f-string] 'target.typehints.incr(a, b=1)', '', 'target.typehints.decr(a, b=1)', @@ -612,7 +612,7 @@ def test_autodoc_typehints_both(app: SphinxTestApp) -> None: ): app.build() context = (app.outdir / 'index.txt').read_text(encoding='utf8') - expect = '\n'.join(( # NoQA: FLY002 + expect = '\n'.join(( # ruff: ignore[static-join-to-f-string] 'target.typehints.incr(a: int, b: int = 1) -> int', '', ' Parameters:', @@ -625,7 +625,7 @@ def test_autodoc_typehints_both(app: SphinxTestApp) -> None: '', )) assert expect in context - expect = '\n'.join(( # NoQA: FLY002 + expect = '\n'.join(( # ruff: ignore[static-join-to-f-string] 'target.typehints.tuple_args(x: tuple[int, int | str]) -> tuple[int, int]', '', ' Parameters:', @@ -638,7 +638,7 @@ def test_autodoc_typehints_both(app: SphinxTestApp) -> None: assert expect in context # Overloads still get displayed in the signature - expect = '\n'.join(( # NoQA: FLY002 + expect = '\n'.join(( # ruff: ignore[static-join-to-f-string] 'target.overload.sum(x: int, y: int = 0) -> int', 'target.overload.sum(x: float, y: float = 0.0) -> float', 'target.overload.sum(x: str, y: str = None) -> str', diff --git a/tests/test_ext_autosummary/test_ext_autosummary.py b/tests/test_ext_autosummary/test_ext_autosummary.py index 337e3a2787..1f48193045 100644 --- a/tests/test_ext_autosummary/test_ext_autosummary.py +++ b/tests/test_ext_autosummary/test_ext_autosummary.py @@ -173,7 +173,7 @@ def test_get_items_summary(make_app, app_params): def new_get_items(self, names, *args, **kwargs): results = orig_get_items(self, names, *args, **kwargs) for name, result in zip(names, results, strict=True): - autosummary_items[name] = result # NoQA: PERF403 + autosummary_items[name] = result # ruff: ignore[manual-dict-comprehension] return results def handler(app, what, name, obj, options, lines): diff --git a/tests/test_ext_intersphinx/test_ext_intersphinx.py b/tests/test_ext_intersphinx/test_ext_intersphinx.py index 5fcfe4d926..35f897045e 100644 --- a/tests/test_ext_intersphinx/test_ext_intersphinx.py +++ b/tests/test_ext_intersphinx/test_ext_intersphinx.py @@ -48,7 +48,7 @@ if TYPE_CHECKING: from sphinx.util.typing import Inventory -class FakeList(list[str]): # NoQA: FURB189 +class FakeList(list[str]): # ruff: ignore[subclass-builtin] def __iter__(self) -> NoReturn: raise NotImplementedError diff --git a/tests/test_ext_napoleon/test_ext_napoleon.py b/tests/test_ext_napoleon/test_ext_napoleon.py index 8e609137b5..30bb629372 100644 --- a/tests/test_ext_napoleon/test_ext_napoleon.py +++ b/tests/test_ext_napoleon/test_ext_napoleon.py @@ -37,12 +37,12 @@ def _private_undoc() -> None: pass -def __special_doc__() -> None: # NoQA: N807 +def __special_doc__() -> None: # ruff: ignore[dunder-function-name] """module.__special_doc__.DOCSTRING""" pass -def __special_undoc__() -> None: # NoQA: N807 +def __special_undoc__() -> None: # ruff: ignore[dunder-function-name] pass @@ -54,15 +54,15 @@ class SampleClass: def _private_undoc(self) -> None: pass - def __special_doc__(self) -> None: # NoQA: PLW3201 + def __special_doc__(self) -> None: # ruff: ignore[bad-dunder-method-name] """SampleClass.__special_doc__.DOCSTRING""" pass - def __special_undoc__(self) -> None: # NoQA: PLW3201 + def __special_undoc__(self) -> None: # ruff: ignore[bad-dunder-method-name] pass @simple_decorator - def __decorated_func__(self) -> None: # NoQA: PLW3201 + def __decorated_func__(self) -> None: # ruff: ignore[bad-dunder-method-name] """Doc""" pass @@ -75,15 +75,15 @@ class SampleError(Exception): def _private_undoc(self) -> None: pass - def __special_doc__(self) -> None: # NoQA: PLW3201 + def __special_doc__(self) -> None: # ruff: ignore[bad-dunder-method-name] """SampleError.__special_doc__.DOCSTRING""" pass - def __special_undoc__(self) -> None: # NoQA: PLW3201 + def __special_undoc__(self) -> None: # ruff: ignore[bad-dunder-method-name] pass -SampleNamedTuple = namedtuple('SampleNamedTuple', 'user_id block_type def_id') # NoQA: PYI024 +SampleNamedTuple = namedtuple('SampleNamedTuple', 'user_id block_type def_id') # ruff: ignore[collections-named-tuple] class TestProcessDocstring: diff --git a/tests/test_ext_napoleon/test_ext_napoleon_docstring.py b/tests/test_ext_napoleon/test_ext_napoleon_docstring.py index f894be526d..c7a79ad103 100644 --- a/tests/test_ext_napoleon/test_ext_napoleon_docstring.py +++ b/tests/test_ext_napoleon/test_ext_napoleon_docstring.py @@ -33,7 +33,7 @@ if TYPE_CHECKING: from sphinx.testing.util import SphinxTestApp -class NamedtupleSubclass(namedtuple('NamedtupleSubclass', ('attr1', 'attr2'))): # NoQA: PYI024 +class NamedtupleSubclass(namedtuple('NamedtupleSubclass', ('attr1', 'attr2'))): # ruff: ignore[collections-named-tuple] """Sample namedtuple subclass Attributes @@ -1261,7 +1261,7 @@ Methods: description -""" # NoQA: W293 +""" # ruff: ignore[blank-line-with-whitespace] config = Config() actual = GoogleDocstring( docstring, diff --git a/tests/test_extensions/test_ext_apidoc.py b/tests/test_extensions/test_ext_apidoc.py index 0052a4740b..87a6322b8a 100644 --- a/tests/test_extensions/test_ext_apidoc.py +++ b/tests/test_extensions/test_ext_apidoc.py @@ -15,7 +15,7 @@ if TYPE_CHECKING: from sphinx.testing.util import SphinxTestApp -_apidoc = namedtuple('_apidoc', 'coderoot,outdir') # NoQA: PYI024 +_apidoc = namedtuple('_apidoc', 'coderoot,outdir') # ruff: ignore[collections-named-tuple] @pytest.fixture diff --git a/tests/test_extensions/test_ext_doctest.py b/tests/test_extensions/test_ext_doctest.py index c8a12c24de..2d500f4650 100644 --- a/tests/test_extensions/test_ext_doctest.py +++ b/tests/test_extensions/test_ext_doctest.py @@ -21,7 +21,7 @@ cleanup_called = 0 @pytest.mark.sphinx('doctest', testroot='ext-doctest') def test_build(app: SphinxTestApp) -> None: - global cleanup_called # NoQA: PLW0603 + global cleanup_called # ruff: ignore[global-statement] cleanup_called = 0 app.build(force_all=True) assert app.statuscode == 0, f'failures in doctests:\n{app.status.getvalue()}' @@ -75,7 +75,7 @@ def test_is_allowed_version() -> None: def cleanup_call() -> None: - global cleanup_called # NoQA: PLW0603 + global cleanup_called # ruff: ignore[global-statement] cleanup_called += 1 @@ -93,7 +93,7 @@ def test_skipif(app: SphinxTestApp) -> None: in ``test_build`` above, and the assertion below would fail. """ - global recorded_calls # NoQA: PLW0603 + global recorded_calls # ruff: ignore[global-statement] recorded_calls = Counter() app.build(force_all=True) if app.statuscode != 0: diff --git a/tests/test_quickstart.py b/tests/test_quickstart.py index 3688984d9c..304b5421cb 100644 --- a/tests/test_quickstart.py +++ b/tests/test_quickstart.py @@ -111,7 +111,7 @@ def test_quickstart_defaults(tmp_path: Path) -> None: conffile = tmp_path / 'conf.py' assert conffile.is_file() ns: dict[str, Any] = {} - exec(conffile.read_text(encoding='utf8'), ns) # NoQA: S102 + exec(conffile.read_text(encoding='utf8'), ns) # ruff: ignore[exec-builtin] assert ns['extensions'] == [] assert ns['templates_path'] == ['_templates'] assert ns['project'] == 'Sphinx Test' @@ -161,7 +161,7 @@ def test_quickstart_all_answers(tmp_path: Path) -> None: conffile = tmp_path / 'source' / 'conf.py' assert conffile.is_file() ns: dict[str, Any] = {} - exec(conffile.read_text(encoding='utf8'), ns) # NoQA: S102 + exec(conffile.read_text(encoding='utf8'), ns) # ruff: ignore[exec-builtin] assert ns['extensions'] == [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', @@ -239,7 +239,7 @@ def test_default_filename(tmp_path: Path) -> None: conffile = tmp_path / 'conf.py' assert conffile.is_file() ns: dict[str, Any] = {} - exec(conffile.read_text(encoding='utf8'), ns) # NoQA: S102 + exec(conffile.read_text(encoding='utf8'), ns) # ruff: ignore[exec-builtin] def test_extensions(tmp_path: Path) -> None: @@ -257,7 +257,7 @@ def test_extensions(tmp_path: Path) -> None: conffile = tmp_path / 'conf.py' assert conffile.is_file() ns: dict[str, Any] = {} - exec(conffile.read_text(encoding='utf8'), ns) # NoQA: S102 + exec(conffile.read_text(encoding='utf8'), ns) # ruff: ignore[exec-builtin] assert ns['extensions'] == ['foo', 'bar', 'baz'] diff --git a/tests/test_util/test_util_display.py b/tests/test_util/test_util_display.py index f4fa9c997c..fce4ac1fbd 100644 --- a/tests/test_util/test_util_display.py +++ b/tests/test_util/test_util_display.py @@ -94,7 +94,7 @@ def test_progress_message(app: SphinxTestApp) -> None: # skipping case with progress_message('testing'): - raise SkipProgressMessage('Reason: %s', 'error') # NoQA: EM101,TRY003 + raise SkipProgressMessage('Reason: %s', 'error') # ruff: ignore[raw-string-in-exception, raise-vanilla-args] output = strip_escape_sequences(app.status.getvalue()) assert 'testing... skipped\nReason: error\n' in output @@ -102,7 +102,7 @@ def test_progress_message(app: SphinxTestApp) -> None: # error case try: with progress_message('testing'): - raise RuntimeError # NoQA: TRY301 + raise RuntimeError # ruff: ignore[raise-within-try] except Exception: pass diff --git a/tests/test_util/test_util_i18n.py b/tests/test_util/test_util_i18n.py index 14db179b19..d4aa8ec883 100644 --- a/tests/test_util/test_util_i18n.py +++ b/tests/test_util/test_util_i18n.py @@ -59,7 +59,7 @@ def test_catalog_write_mo(tmp_path: Path) -> None: def test_format_date() -> None: - date = datetime.datetime(2016, 2, 7, 5, 11, 17, 0) # NoQA: DTZ001 + date = datetime.datetime(2016, 2, 7, 5, 11, 17, 0) # ruff: ignore[call-datetime-without-tzinfo] # strftime format format = '%B %d, %Y' @@ -99,7 +99,7 @@ def test_format_date() -> None: def test_format_date_timezone() -> None: dt = datetime.datetime(2016, 8, 7, 5, 11, 17, 0, tzinfo=datetime.UTC) if time.localtime(dt.timestamp()).tm_gmtoff == 0: - raise pytest.skip('Local time zone is GMT') # NoQA: EM101,TRY003 + raise pytest.skip('Local time zone is GMT') # ruff: ignore[raw-string-in-exception, raise-vanilla-args] fmt = '%Y-%m-%d %H:%M:%S' diff --git a/tests/test_util/test_util_inspect.py b/tests/test_util/test_util_inspect.py index f17750eda5..2deed7d5c2 100644 --- a/tests/test_util/test_util_inspect.py +++ b/tests/test_util/test_util_inspect.py @@ -8,7 +8,7 @@ import enum import functools import types from inspect import Parameter -from typing import Callable, List, Optional, Union # NoQA: UP035 +from typing import Callable, List, Optional, Union # ruff: ignore[deprecated-import] import pytest @@ -77,7 +77,7 @@ async def coroutinefunc(): pass -async def asyncgenerator(): # NoQA: RUF029 +async def asyncgenerator(): # ruff: ignore[unused-async] yield @@ -106,11 +106,11 @@ def _decorator(f): return wrapper -def forward_reference_in_args(x: Foo) -> None: # type: ignore[name-defined] # noqa: F821 +def forward_reference_in_args(x: Foo) -> None: # type: ignore[name-defined] # ruff: ignore[undefined-name] pass -def forward_reference_in_return() -> Foo: # type: ignore[name-defined] # noqa: F821 +def forward_reference_in_return() -> Foo: # type: ignore[name-defined] # 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] # NoQA: UP045 + alias = Optional[alias] # ruff: ignore[non-pep604-annotation-optional] sig_str = stringify_annotation(alias, 'fully-qualified-except-typing') assert sig_str == "TypeAliasForwardRef('example') | None" @@ -723,7 +723,7 @@ def test_getslots() -> None: __slots__ = {'attr': 'docstring'} class Qux: - __slots__ = 'attr' # NoQA: PLC0205 + __slots__ = 'attr' # ruff: ignore[single-string-slots] assert inspect.getslots(Foo) is None assert inspect.getslots(Bar) == {'attr': None} @@ -934,15 +934,15 @@ def test_isproperty() -> None: def test_isgenericalias() -> None: #: A list of int - T = List[int] # NoQA: UP006 - S = list[Union[str, None]] # NoQA: UP007 + T = List[int] # ruff: ignore[non-pep585-annotation] + S = list[Union[str, None]] # ruff: ignore[non-pep604-annotation-union] C = Callable[[int], None] # a generic alias not having a doccomment assert inspect.isgenericalias(C) assert inspect.isgenericalias(Callable) assert inspect.isgenericalias(T) - assert inspect.isgenericalias(List) # NoQA: UP006 + assert inspect.isgenericalias(List) # ruff: ignore[non-pep585-annotation] assert inspect.isgenericalias(S) assert not inspect.isgenericalias(list) assert not inspect.isgenericalias([]) @@ -988,7 +988,7 @@ def test_getdoc_inherited_decorated_method(): """ class Bar(Foo): - @functools.lru_cache # NoQA: B019 + @functools.lru_cache # ruff: ignore[cached-instance-method] def meth(self): # inherited and decorated method pass diff --git a/tests/test_util/test_util_inspect_py314.py b/tests/test_util/test_util_inspect_py314.py index dbda82a53b..154193e73a 100644 --- a/tests/test_util/test_util_inspect_py314.py +++ b/tests/test_util/test_util_inspect_py314.py @@ -1,4 +1,4 @@ -# noqa: I002 as 'from __future__ import annotations' prevents Python 3.14 +# ruff: ignore[missing-required-import] as 'from __future__ import annotations' prevents Python 3.14 # forward references from causing issues, so we must skip it here. import pytest @@ -12,11 +12,11 @@ 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] # noqa: F821 +def forward_reference_in_args(x: Foo) -> None: # type: ignore[name-defined] # ruff: ignore[undefined-name] pass -def forward_reference_in_return() -> Foo: # type: ignore[name-defined] # noqa: F821 +def forward_reference_in_return() -> Foo: # type: ignore[name-defined] # ruff: ignore[undefined-name] pass diff --git a/tests/test_util/typing_test_data.py b/tests/test_util/typing_test_data.py index 696132f921..ae72687a90 100644 --- a/tests/test_util/typing_test_data.py +++ b/tests/test_util/typing_test_data.py @@ -16,7 +16,7 @@ T_co = TypeVar('T_co', covariant=True) T_contra = TypeVar('T_contra', contravariant=True) -def f2(x: List[T], y: List[T_co], z: T) -> List[T_contra]: # pyright: ignore[reportInvalidTypeVarUse] # NoQA: UP047 +def f2(x: List[T], y: List[T_co], z: T) -> List[T_contra]: # pyright: ignore[reportInvalidTypeVarUse] # ruff: ignore[non-pep695-generic-function] pass @@ -39,7 +39,7 @@ def f6(x: int, *args, y: str, z: str) -> None: pass -def f7(x: int = None, y: dict = {}) -> None: # NoQA: B006,RUF013 # ty: ignore[invalid-parameter-default] +def f7(x: int = None, y: dict = {}) -> None: # ruff: ignore[mutable-argument-default, implicit-optional] # ty: ignore[invalid-parameter-default] pass @@ -77,7 +77,7 @@ def f14() -> Any: pass -def f15(x: 'Unknown', y: 'int') -> Any: # NoQA: F821 # type: ignore[attr-defined] +def f15(x: 'Unknown', y: 'int') -> Any: # ruff: ignore[undefined-name] # type: ignore[attr-defined] pass diff --git a/tests/test_versioning.py b/tests/test_versioning.py index 03d5e00750..be88c02036 100644 --- a/tests/test_versioning.py +++ b/tests/test_versioning.py @@ -26,7 +26,7 @@ original_uids: list[str] @pytest.fixture(scope='module', autouse=True) def _setup_module(rootdir: Path, sphinx_test_tempdir: Path) -> Iterator[None]: - global original, original_uids # NoQA: PLW0603 + global original, original_uids # ruff: ignore[global-statement] srcdir = sphinx_test_tempdir / 'test-versioning' if not srcdir.exists(): shutil.copytree(rootdir / 'test-versioning', srcdir) diff --git a/utils/bump_docker.py b/utils/bump_docker.py index 627bea5a05..7062844bb9 100755 --- a/utils/bump_docker.py +++ b/utils/bump_docker.py @@ -42,7 +42,7 @@ for file in DOCKERFILE_BASE, DOCKERFILE_LATEXPDF: def git(*args: str) -> None: subprocess.run( - ('git', *args), # NoQA: S607 + ('git', *args), # ruff: ignore[start-process-with-partial-path] cwd=DOCKER_ROOT, check=True, text=True,