diff --git a/Cargo.lock b/Cargo.lock index 8c85da0d78daa..2ed8aa76e3632 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3214,7 +3214,6 @@ dependencies = [ "schemars", "serde", "serde_json", - "similar 3.1.1", "supports-hyperlinks", "tempfile", "thiserror 2.0.19", diff --git a/crates/ruff/tests/cli/format.rs b/crates/ruff/tests/cli/format.rs index 08549a9fa1e9e..8768fb24ca66d 100644 --- a/crates/ruff/tests/cli/format.rs +++ b/crates/ruff/tests/cli/format.rs @@ -56,18 +56,16 @@ fn default_files() -> Result<()> { exit_code: 1 ----- stdout ----- unformatted: File would be reformatted - --> bar.py:1:7 - | - - bar = "needs formatting" - 1 + bar = "needs formatting" - | + --> bar.py:1:7 + | + 1 | bar = "needs formatting" + | ~~~~~~~~~~~~~~~~~~ unformatted: File would be reformatted - --> foo.py:1:7 - | - - foo = "needs formatting" - 1 + foo = "needs formatting" - | + --> foo.py:1:7 + | + 1 | foo = "needs formatting" + | ~~~~~~~~~~~~~~~~~~ 2 files would be reformatted @@ -466,20 +464,20 @@ OTHER = "OTHER" exit_code: 1 ----- stdout ----- unformatted: File would be reformatted - --> main.py:1:1 - | - - - 1 | from test import say_hy - | + --> main.py:1:1 + | + 1 | from test import say_hy + 2 | + 3 | if __name__ == "__main__": + 4 | say_hy("dear Ruff contributor") + | unformatted: File would be reformatted - --> test.py:1:1 - | - - - 1 | def say_hy(name: str): - - print(f"Hy {name}") - 2 + print(f"Hy {name}") - | + --> test.py:1:1 + | + 1 + def say_hy(name: str): + 2 + print(f"Hy {name}") + | 2 files would be reformatted @@ -520,11 +518,10 @@ exclude = ["format_excluded.py"] exit_code: 1 ----- stdout ----- unformatted: File would be reformatted - --> main.py:1:3 - | - - x = 1 - 1 + x = 1 - | + --> main.py:1:3 + | + 1 | x = 1 + | ~~~ 1 file would be reformatted @@ -548,11 +545,10 @@ fn deduplicate_directory_and_explicit_file() -> Result<()> { exit_code: 1 ----- stdout ----- unformatted: File would be reformatted - --> main.py:1:3 - | - - x = 1 - 1 + x = 1 - | + --> main.py:1:3 + | + 1 | x = 1 + | 1 file would be reformatted @@ -607,21 +603,23 @@ if __name__ == "__main__": assert_cmd_snapshot!(test.format_command() .arg("--isolated") .arg("--check") - .arg("main.py"), @" + .arg("main.py"), @r#" success: false exit_code: 1 ----- stdout ----- unformatted: File would be reformatted - --> main.py:1:1 - | - - - 1 | from test import say_hy - | + --> main.py:1:1 + | + 1 | from test import say_hy + 2 | + 3 | if __name__ == "__main__": + 4 | say_hy("dear Ruff contributor") + | 1 file would be reformatted ----- stderr ----- - "); + "#); assert_cmd_snapshot!(test.format_command() .arg("--isolated") @@ -699,35 +697,36 @@ fn output_format_notebook() -> Result<()> { exit_code: 1 ----- stdout ----- unformatted: File would be reformatted - --> CRATE_ROOT/resources/test/fixtures/unformatted.ipynb:cell 1:2:1 - ::: cell 1 - | - 1 | import numpy - - maths = (numpy.arange(100)**2).sum() - - stats= numpy.asarray([1,2,3,4]).median() - 2 + - 3 + maths = (numpy.arange(100) ** 2).sum() - 4 + stats = numpy.asarray([1, 2, 3, 4]).median() - | - ::: cell 3 - | - 3 | pass - 4 + - 5 + - 6 | %matplotlib inline - | - ::: cell 4 - | - 1 | foo = %pwd - - def some_function(foo,bar,): - 2 + - 3 + - 4 + def some_function( - 5 + foo, - 6 + bar, - 7 + ): - 8 | # Another cell with IPython escape command - | + --> CRATE_ROOT/resources/test/fixtures/unformatted.ipynb:cell 1:2:1 + ::: cell 1:0:1 + | + 0 + import numpy + 1 + + 2 + maths = (numpy.arange(100) ** 2).sum() + 3 + stats = numpy.asarray([1, 2, 3, 4]).median() + | + ::: cell 3:3:1 + | + 0 | # A cell with IPython escape command + 1 | def some_function(foo, bar): + 2 | pass + 3 + + 4 + + 5 | %matplotlib inline + | + ::: cell 4:0:1 + | + 0 + foo = %pwd + 1 + + 2 + + 3 + def some_function( + 4 + foo, + 5 + bar, + 6 + ): + 7 + # Another cell with IPython escape command + 8 + foo = %pwd + 9 + print(foo) + | 1 file would be reformatted @@ -834,13 +833,11 @@ fn check_quiet_mode_shows_diagnostics_only() -> Result<()> { exit_code: 1 ----- stdout ----- unformatted: File would be reformatted - --> main.py:1:5 - | - - def foo(): - - pass - 1 + def foo(): - 2 + pass - | + --> main.py:1:5 + | + 1 ~ def foo(): + 2 | pass + | ----- stderr ----- @@ -858,13 +855,11 @@ fn check_default_mode_shows_diagnostics_and_summary() -> Result<()> { exit_code: 1 ----- stdout ----- unformatted: File would be reformatted - --> main.py:1:5 - | - - def foo(): - - pass - 1 + def foo(): - 2 + pass - | + --> main.py:1:5 + | + 1 ~ def foo(): + 2 | pass + | 1 file would be reformatted @@ -918,21 +913,23 @@ OTHER = "OTHER" // Explicitly pass test.py, should not be formatted because of --force-exclude .arg("test.py") // Format all other files in the directory, should respect the `exclude` and `format.exclude` options - .arg("."), @" + .arg("."), @r#" success: false exit_code: 1 ----- stdout ----- unformatted: File would be reformatted - --> main.py:1:1 - | - - - 1 | from test import say_hy - | + --> main.py:1:1 + | + 1 | from test import say_hy + 2 | + 3 | if __name__ == "__main__": + 4 | say_hy("dear Ruff contributor") + | 1 file would be reformatted ----- stderr ----- - "); + "#); Ok(()) } @@ -2555,27 +2552,25 @@ fn markdown_formatting() -> Result<()> { exit_code: 1 ----- stdout ----- unformatted: File would be reformatted - --> CRATE_ROOT/resources/test/fixtures/unformatted.md:4:7 - | - 3 | ```py - - print( "hello" ) - - def foo(): pass - 4 + print("hello") - 5 + - 6 + - 7 + def foo(): - 8 + pass - 9 | ``` - 10 | - 11 | ```pyi - - print( "hello" ) - - def foo(): pass - 12 + print("hello") - 13 + - 14 + def foo(): - 15 + pass - 16 | ``` - | + --> CRATE_ROOT/resources/test/fixtures/unformatted.md:4:7 + | + 1 | This is a markdown document with two fenced code blocks: + 2 | + 3 | ```py + 4 ~ print("hello") + 5 + + 6 + + 7 + def foo(): + 8 + pass + 9 + ``` + 10 + + 11 + ```pyi + 12 + print("hello") + 13 + + 14 + def foo(): + 15 ~ pass + 16 | ``` + | 1 file would be reformatted @@ -2692,21 +2687,22 @@ print( 'hello' ) exit_code: 1 ----- stdout ----- unformatted: File would be reformatted - --> test.bar:5:7 - | - 4 | ```py - - print( 'hello' ) - 5 + print("hello") - 6 | ``` - | + --> test.bar:5:7 + | + 2 | Text string + 3 | + 4 | ```py + 5 ~ print("hello") + 6 | ``` + | unformatted: File would be reformatted - --> test.foo:1:1 - | - - - - print( 'hello' ) - 1 + print("hello") - | + --> test.foo:1:1 + | + 1 - + 2 - print( 'hello' ) + 1 + print("hello") + | 2 files would be reformatted diff --git a/crates/ruff/tests/cli/lint.rs b/crates/ruff/tests/cli/lint.rs index d8e394cfb2bba..f03945251bb32 100644 --- a/crates/ruff/tests/cli/lint.rs +++ b/crates/ruff/tests/cli/lint.rs @@ -4502,7 +4502,7 @@ fn show_fixes_in_full_output_with_preview_enabled() { | ^^^^ help: Remove unused import: `math` | - - import math + 1 - import math | Found 1 error. @@ -4566,7 +4566,7 @@ fn rule_panic_mixed_results_full() -> Result<()> { --> normal.py:1:1 stable-test-rule-safe-fix: [*] Hey this is a stable test rule with a safe fix. - --> normal.py:1:1 + --> normal.py:1:1 | 1 + # fix from stable-test-rule-safe-fix 2 | import os @@ -5221,7 +5221,7 @@ fn ruff_toml_is_linted() -> Result<()> { | ^^^^ help: Replace rule code with `unused-import` | - - lint.select = ["F401"] + 1 - lint.select = ["F401"] 1 + lint.select = ["unused-import"] | diff --git a/crates/ruff/tests/cli/snapshots/cli__format__output_format_full.snap b/crates/ruff/tests/cli/snapshots/cli__format__output_format_full.snap index 199e170d04931..692c331c87ab8 100644 --- a/crates/ruff/tests/cli/snapshots/cli__format__output_format_full.snap +++ b/crates/ruff/tests/cli/snapshots/cli__format__output_format_full.snap @@ -7,7 +7,6 @@ info: - "--no-cache" - "--output-format" - full - - "--preview" - "--check" - input.py --- @@ -15,11 +14,13 @@ success: false exit_code: 1 ----- stdout ----- unformatted: File would be reformatted - --> input.py:1:1 - | - - -1 | from test import say_hy - | + --> input.py:1:1 + | + 1 | from test import say_hy + 2 | + 3 | if __name__ == "__main__": + 4 | say_hy("dear Ruff contributor") + | 1 file would be reformatted diff --git a/crates/ruff/tests/cli/snapshots/cli__lint__output_format_full.snap b/crates/ruff/tests/cli/snapshots/cli__lint__output_format_full.snap index 59e2fcbe6d306..a15e337d2f2d4 100644 --- a/crates/ruff/tests/cli/snapshots/cli__lint__output_format_full.snap +++ b/crates/ruff/tests/cli/snapshots/cli__lint__output_format_full.snap @@ -26,8 +26,7 @@ F401 [*] `os` imported but unused | help: Remove unused import: `os` | - - import os # F401 -1 | x = y # F821 +1 - import os # F401 | F821 Undefined name `y` diff --git a/crates/ruff/tests/cli/snapshots/cli__lint__output_format_preview_full.snap b/crates/ruff/tests/cli/snapshots/cli__lint__output_format_preview_full.snap index f5cd1fcd058ec..c59e54251be4a 100644 --- a/crates/ruff/tests/cli/snapshots/cli__lint__output_format_preview_full.snap +++ b/crates/ruff/tests/cli/snapshots/cli__lint__output_format_preview_full.snap @@ -27,8 +27,7 @@ unused-import: [*] `os` imported but unused | help: Remove unused import: `os` | - - import os # F401 -1 | x = y # F821 +1 - import os # F401 | undefined-name: Undefined name `y` diff --git a/crates/ruff/tests/integration_test.rs b/crates/ruff/tests/integration_test.rs index 08d53501db43a..149d115568ea3 100644 --- a/crates/ruff/tests/integration_test.rs +++ b/crates/ruff/tests/integration_test.rs @@ -122,7 +122,7 @@ fn stdin_error() { | ^^ help: Remove unused import: `os` | - - import os + 1 - import os | Found 1 error. @@ -149,7 +149,7 @@ fn stdin_filename() { | ^^ help: Remove unused import: `os` | - - import os + 1 - import os | Found 1 error. @@ -187,8 +187,7 @@ import bar # unused import | ^^^ help: Remove unused import: `bar` | - 1 | - - import bar # unused import + 2 - import bar # unused import | F401 [*] `foo` imported but unused @@ -198,8 +197,7 @@ import bar # unused import | ^^^ help: Remove unused import: `foo` | - 1 | - - import foo # unused import + 2 - import foo # unused import | Found 2 errors. @@ -229,7 +227,7 @@ fn check_warn_stdin_filename_with_files() { | ^^ help: Remove unused import: `os` | - - import os + 1 - import os | Found 1 error. @@ -258,7 +256,7 @@ fn stdin_source_type_py() { | ^^ help: Remove unused import: `os` | - - import os + 1 - import os | Found 1 error. @@ -595,9 +593,9 @@ fn stdin_override_parser_ipynb() { 1 | import os | ^^ help: Remove unused import: `os` - ::: cell 1 + ::: cell 1:0:1 | - - import os + 0 - import os | F401 [*] `sys` imported but unused @@ -606,9 +604,9 @@ fn stdin_override_parser_ipynb() { 1 | import sys | ^^^ help: Remove unused import: `sys` - ::: cell 3 + ::: cell 3:0:1 | - - import sys + 0 - import sys | Found 2 errors. @@ -640,7 +638,7 @@ fn stdin_override_parser_py() { | ^^ help: Remove unused import: `os` | - - import os + 1 - import os | Found 1 error. @@ -677,7 +675,7 @@ extension = {ipynb="python"} | ^^ help: Remove unused import: `os` | - - import os + 1 - import os | Found 1 error. @@ -1855,7 +1853,7 @@ fn check_input_from_argfile() -> Result<()> { | ^^ help: Remove unused import: `os` | - - import os + 1 - import os | Found 1 error. @@ -1899,7 +1897,7 @@ fn check_hints_hidden_unsafe_fixes() { exit_code: 1 ----- stdout ----- RUF901 [*] Hey this is a stable test rule with a safe fix. - --> -:1:1 + --> -:1:1 | 1 + # fix from stable-test-rule-safe-fix | @@ -1944,7 +1942,7 @@ fn check_no_hint_for_hidden_unsafe_fixes_when_disabled() { exit_code: 1 ----- stdout ----- RUF901 [*] Hey this is a stable test rule with a safe fix. - --> -:1:1 + --> -:1:1 | 1 + # fix from stable-test-rule-safe-fix | @@ -1990,13 +1988,13 @@ fn check_shows_unsafe_fixes_with_opt_in() { exit_code: 1 ----- stdout ----- RUF901 [*] Hey this is a stable test rule with a safe fix. - --> -:1:1 + --> -:1:1 | 1 + # fix from stable-test-rule-safe-fix | RUF902 [*] Hey this is a stable test rule with an unsafe fix. - --> -:1:1 + --> -:1:1 | 1 + # fix from stable-test-rule-unsafe-fix | @@ -2275,13 +2273,13 @@ extend-safe-fixes = ["RUF902"] exit_code: 1 ----- stdout ----- RUF901 [*] Hey this is a stable test rule with a safe fix. - --> -:1:1 + --> -:1:1 | 1 + # fix from stable-test-rule-safe-fix | RUF902 [*] Hey this is a stable test rule with an unsafe fix. - --> -:1:1 + --> -:1:1 | 1 + # fix from stable-test-rule-unsafe-fix | @@ -2319,7 +2317,7 @@ extend-safe-fixes = ["RUF902"] exit_code: 1 ----- stdout ----- RUF901 [*] Hey this is a stable test rule with a safe fix. - --> -:1:1 + --> -:1:1 | 1 + # fix from stable-test-rule-safe-fix | @@ -2368,10 +2366,13 @@ extend-safe-fixes = ["RUF9"] --> -:1:1 RUF902 [*] Hey this is a stable test rule with an unsafe fix. - --> -:1:1 + --> -:1:1 | 1 + # fix from stable-test-rule-unsafe-fix 2 | x = {'a': 1, 'a': 1} + 3 | print(('foo')) + 4 | print(str('foo')) + 5 | isinstance(x, (int, str)) | RUF903 Hey this is a stable test rule with a display only fix. diff --git a/crates/ruff_db/Cargo.toml b/crates/ruff_db/Cargo.toml index 52d668e9afc61..f179530bbaa0c 100644 --- a/crates/ruff_db/Cargo.toml +++ b/crates/ruff_db/Cargo.toml @@ -42,7 +42,6 @@ same-file = { workspace = true, optional = true } schemars = { workspace = true, optional = true } serde = { workspace = true, optional = true } serde_json = { workspace = true, optional = true } -similar = { workspace = true } supports-hyperlinks = { workspace = true } thiserror = { workspace = true } tracing = { workspace = true } diff --git a/crates/ruff_db/src/diagnostic/render/full.rs b/crates/ruff_db/src/diagnostic/render/full.rs index b06b07c08a536..e8305aa53bbe9 100644 --- a/crates/ruff_db/src/diagnostic/render/full.rs +++ b/crates/ruff_db/src/diagnostic/render/full.rs @@ -1,10 +1,6 @@ -use std::borrow::Cow; -use std::num::NonZeroUsize; - -use similar::{ChangeTag, DiffOp, TextDiff}; - use annotate_snippets::{ - Group as AnnotateGroup, Level as AnnotateLevel, Renderer as AnnotateRenderer, + Group as AnnotateGroup, Level as AnnotateLevel, Patch as AnnotatePatch, + Renderer as AnnotateRenderer, Snippet as AnnotateSnippet, }; use ruff_diagnostics::{Applicability, Fix}; use ruff_notebook::NotebookIndex; @@ -12,7 +8,7 @@ use ruff_source_file::OneIndexed; use ruff_text_size::{Ranged, TextLen, TextRange, TextSize}; use crate::diagnostic::render::{FileResolver, Resolved}; -use crate::diagnostic::stylesheet::{DiagnosticStylesheet, fmt_styled}; +use crate::diagnostic::stylesheet::DiagnosticStylesheet; use crate::diagnostic::{Diagnostic, DiagnosticSource, DisplayDiagnosticConfig}; pub(super) struct FullRenderer<'a> { @@ -52,6 +48,8 @@ impl<'a> FullRenderer<'a> { .help(stylesheet.help) .line_num(stylesheet.line_no) .emphasis(stylesheet.emphasis) + .addition(stylesheet.insertion) + .removal(stylesheet.deletion) .none(stylesheet.none) .hyperlink(stylesheet.hyperlink); @@ -62,15 +60,24 @@ impl<'a> FullRenderer<'a> { let resolved = Resolved::new(self.resolver, diag, self.config); let renderable = resolved.to_renderable(self.config); - for diag in renderable.diagnostics.iter() { - writeln!(f, "{}", renderer.render(&[diag.to_annotate()]))?; + let diff = diag + .has_applicable_fix(self.config.fix_applicability()) + .then(|| Diff::from_diagnostic(diag, self.resolver)) + .flatten(); + + for (index, diagnostic) in renderable.diagnostics.iter().enumerate() { + let mut group = diagnostic.to_annotate(); + if index + 1 == renderable.diagnostics.len() + && let Some(diff) = diff.as_ref() + { + group = diff.append_to(group); + } + + let rendered = renderer.render(&[group]); + writeln!(f, "{rendered}")?; } - if diag.has_applicable_fix(self.config.fix_applicability()) - && let Some(diff) = - Diff::from_diagnostic(diag, &stylesheet, self.resolver, self.config) - { - write!(f, "{diff}")?; + if let Some(diff) = diff { if let Some(applicability) = to_applicability_annotate(diff.fix) { writeln!(f, "{}", renderer.render(&[applicability]))?; } @@ -83,42 +90,30 @@ impl<'a> FullRenderer<'a> { } } -const FIX_CONTEXT: usize = 1; - -/// Renders a diff that shows the code fixes. -/// -/// The implementation isn't fully fledged out and only used by tests. Before using in production, try -/// * Improve layout -/// * Replace tabs with spaces for a consistent experience across terminals -/// * Replace zero-width whitespaces -/// * Print a simpler diff if only a single line has changed -/// * Compute the diff from the `Edit` because diff calculation is expensive. +/// Track a diff for showing the code fixes. struct Diff<'a> { fix: &'a Fix, diagnostic_source: DiagnosticSource, notebook_index: Option, - stylesheet: &'a DiagnosticStylesheet, - merge_window: usize, + fold: bool, } impl<'a> Diff<'a> { - fn from_diagnostic( - diagnostic: &'a Diagnostic, - stylesheet: &'a DiagnosticStylesheet, - resolver: &'a dyn FileResolver, - config: &DisplayDiagnosticConfig, - ) -> Option> { + fn from_diagnostic(diagnostic: &'a Diagnostic, resolver: &'a dyn FileResolver) -> Option { let file = &diagnostic.primary_span_ref()?.file; - Some(Diff { + Some(Self { fix: diagnostic.fix()?, diagnostic_source: file.diagnostic_source(resolver), notebook_index: resolver.notebook_index(file), - stylesheet, - merge_window: config.merge_window, + fold: !diagnostic + .inner + .annotations + .iter() + .any(|annotation| annotation.is_primary && annotation.hide_snippet), }) } - fn write(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn append_to<'s>(&'s self, mut group: AnnotateGroup<'s>) -> AnnotateGroup<'s> { let source_code = self.diagnostic_source.as_source_code(); let source_text = source_code.text(); @@ -126,7 +121,7 @@ impl<'a> Diff<'a> { for (cell_index, range) in cell_ranges { // For non-notebooks, construct and diff only the source surrounding the edits. - let (range, line_offset) = if cell_index.is_none() + let (range, line_num) = if cell_index.is_none() && let Some(first) = self.fix.edits().first() && let Some(last) = self.fix.edits().last() { @@ -144,7 +139,7 @@ impl<'a> Diff<'a> { source_code.line_start(start_line), source_code.line_end(end_line), ), - start_line.to_zero_indexed(), + start_line.get(), ) } else { (range, 0) @@ -163,125 +158,21 @@ impl<'a> Diff<'a> { let input = source_code.slice(range); - let mut output = String::with_capacity(input.len()); - let mut last_end = range.start(); - - for edit in edits { - output.push_str(source_code.slice(TextRange::new(last_end, edit.start()))); - output.push_str(edit.content().unwrap_or_default()); - last_end = edit.end(); - } - - output.push_str(&source_text[usize::from(last_end)..usize::from(range.end())]); - - let diff = TextDiff::from_lines(input, &output); - - let mut grouped_ops: Vec> = Vec::new(); - for group in diff.grouped_ops(FIX_CONTEXT) { - if let Some(previous) = grouped_ops.last_mut() - && let Some(DiffOp::Equal { new_index, len, .. }) = previous.last_mut() - && let [ - DiffOp::Equal { - new_index: next_new_index, - len: next_len, - .. - }, - rest @ .., - ] = group.as_slice() - && next_new_index.saturating_sub(*new_index + *len) <= self.merge_window - { - // Restore the unchanged lines that `grouped_ops` omitted between the groups. - *len = next_new_index + next_len - *new_index; - previous.extend_from_slice(rest); - } else { - grouped_ops.push(group); - } - } - - // Find the new line number with the largest number of digits to align all of the line - // number separators. - let last_op = grouped_ops.last().and_then(|group| group.last()); - let largest_new = last_op - .map(|op| op.new_range().end + line_offset) - .unwrap_or_default(); - - let digit_with = OneIndexed::new(largest_new).unwrap_or_default().digits(); - - if let Some(cell_index) = cell_index { - // Room for 1 digit, 1 space, 1 `|`, and 1 more following space. This centers the - // three colons on the pipe. - writeln!(f, "{:>1$} cell {cell_index}", ":::", digit_with.get() + 3)?; - } - - self.write_gutter(f, digit_with)?; - - for (idx, group) in grouped_ops.iter().enumerate() { - if idx > 0 { - writeln!(f, "{:-^1$}", "-", 80)?; - } - for op in group { - for change in diff.iter_inline_changes(op) { - let (sign, style, line_no_style, index) = match change.tag() { - ChangeTag::Delete => ( - "-", - self.stylesheet.deletion, - self.stylesheet.deletion_line_no, - None, - ), - ChangeTag::Insert => ( - "+", - self.stylesheet.insertion, - self.stylesheet.insertion_line_no, - change.new_index(), - ), - ChangeTag::Equal => ( - "|", - self.stylesheet.none, - self.stylesheet.line_no, - change.new_index(), - ), - }; - - let line = Line { - index: index.map(|i| { - OneIndexed::from_zero_indexed(i).saturating_add(line_offset) - }), - width: digit_with, - }; - - write!( - f, - "{line} {sign}", - line = fmt_styled(line, self.stylesheet.line_no), - sign = fmt_styled(sign, line_no_style), - )?; - - let mut needs_separator = true; - for (emphasized, value) in change.iter_strings_lossy() { - if needs_separator && !value.trim_end_matches(['\n', '\r']).is_empty() { - f.write_str(" ")?; - needs_separator = false; - } - - let value = show_nonprinting(&value); - let styled = fmt_styled(value, style); - if emphasized { - write!(f, "{}", fmt_styled(styled, self.stylesheet.emphasis))?; - } else { - write!(f, "{styled}")?; - } - } - if change.missing_newline() { - writeln!(f)?; - } - } - } - } - - self.write_gutter(f, digit_with)?; + let snippet = AnnotateSnippet::source(input) + .line_start(line_num) + .cell_index(cell_index) + .fold(self.fold) + .patches(edits.iter().map(|edit| { + let range = edit.range() - range.start(); + AnnotatePatch::new( + range.start().to_usize()..range.end().to_usize(), + edit.content().unwrap_or_default(), + ) + })); + group = group.element(snippet); } - Ok(()) + group } fn cell_ranges(&self) -> Vec<(Option, TextRange)> { @@ -313,58 +204,11 @@ impl<'a> Diff<'a> { cells.push((Some(last_cell_index.get()), range)); cells } - - fn write_gutter(&self, f: &mut std::fmt::Formatter, width: NonZeroUsize) -> std::fmt::Result { - writeln!( - f, - "{line} {separator}", - line = fmt_styled(Line { index: None, width }, self.stylesheet.line_no), - separator = fmt_styled("|", self.stylesheet.line_no), - ) - } } /// Limit diffs to a narrow range around each fix rather than diffing the whole file. const DIFF_CONTEXT_WINDOW: usize = 3; -impl std::fmt::Display for Diff<'_> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.write(f) - } -} - -struct Line { - index: Option, - width: NonZeroUsize, -} - -impl std::fmt::Display for Line { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match self.index { - None => { - for _ in 0..self.width.get() { - f.write_str(" ")?; - } - Ok(()) - } - Some(idx) => write!(f, "{: Cow<'_, str> { - if s.find(['\x07', '\x08', '\x1b', '\x7f']).is_some() { - Cow::Owned( - s.replace('\x07', "␇") - .replace('\x08', "␈") - .replace('\x1b', "␛") - .replace('\x7f', "␡"), - ) - } else { - Cow::Borrowed(s) - } -} - fn to_applicability_annotate(fix: &Fix) -> Option> { let (level, message) = match fix.applicability() { Applicability::Safe => return None, @@ -487,8 +331,7 @@ mod tests { | ^^ help: Remove unused import: `os` | - - import os - 1 | + 1 - import os | note: This is an unsafe fix and may change runtime behavior @@ -504,10 +347,7 @@ mod tests { | help: Remove assignment to unused variable `x` | - 5 | """Compute the nth number in the Fibonacci sequence.""" - - x = 1 - 6 + - 7 | if n == 0: + 6 - x = 1 | note: This is an unsafe fix and may change runtime behavior @@ -729,10 +569,9 @@ print() 2 | import os | ^^ help: Remove unused import: `os` - ::: cell 1 + ::: cell 1:1:1 | - 1 | # cell 1 - - import os + 1 - import os | error[F401][*]: `math` imported but unused @@ -745,11 +584,9 @@ print() 4 | print('hello world') | help: Remove unused import: `math` - ::: cell 2 + ::: cell 2:1:1 | - 1 | # cell 2 - - import math - 2 | + 1 - import math | error[F841]: Local variable `x` is assigned to but never used @@ -1024,11 +861,8 @@ line 10 | help: Start of diff: | - 6 | line 6 - - line 7 - 7 + fixed line 7 - 8 | line 8 - | + 7 | fixed line 7 + | +++++ note: This is an unsafe fix and may change runtime behavior "); } @@ -1079,20 +913,15 @@ line 13 | ^^^^^^ help: Replace three lines | - 1 | line 1 - - line 2 - 2 + fixed line 2 - 3 | line 3 - 4 | line 4 - 5 | line 5 - 6 | line 6 - - line 7 - 7 + fixed line 7 - 8 | line 8 - -------------------------------------------------------------------------------- + 2 ~ fixed line 2 + 3 | line 3 + … + 6 | line 6 + 7 ~ fixed line 7 + 8 | line 8 + … 12 | line 12 - - line 13 - 13 + fixed line 13 + 13 ~ fixed line 13 | "); } diff --git a/crates/ruff_db/src/diagnostic/render/snapshots/ruff_db__diagnostic__render__full__tests__notebook_output_with_diff.snap b/crates/ruff_db/src/diagnostic/render/snapshots/ruff_db__diagnostic__render__full__tests__notebook_output_with_diff.snap index 2e28d0dfd6138..5b7d14d997664 100644 --- a/crates/ruff_db/src/diagnostic/render/snapshots/ruff_db__diagnostic__render__full__tests__notebook_output_with_diff.snap +++ b/crates/ruff_db/src/diagnostic/render/snapshots/ruff_db__diagnostic__render__full__tests__notebook_output_with_diff.snap @@ -9,10 +9,9 @@ error[F401][*]: `os` imported but unused 2 | import os | ^^ help: Remove unused import: `os` - ::: cell 1 + ::: cell 1:1:1 | -1 | # cell 1 - - import os +1 - import os | error[F401][*]: `math` imported but unused @@ -25,11 +24,9 @@ error[F401][*]: `math` imported but unused 4 | print('hello world') | help: Remove unused import: `math` - ::: cell 2 + ::: cell 2:1:1 | -1 | # cell 2 - - import math -2 | +1 - import math | error[F841][*]: Local variable `x` is assigned to but never used @@ -40,10 +37,8 @@ error[F841][*]: Local variable `x` is assigned to but never used 4 | x = 1 | ^ help: Remove assignment to unused variable `x` - ::: cell 3 + ::: cell 3:3:1 | -3 | print() - - x = 1 -4 | +3 - x = 1 | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_db/src/diagnostic/render/snapshots/ruff_db__diagnostic__render__full__tests__notebook_output_with_diff_spanning_cells.snap b/crates/ruff_db/src/diagnostic/render/snapshots/ruff_db__diagnostic__render__full__tests__notebook_output_with_diff_spanning_cells.snap index 4168390a2eecc..c66ed9feed0d4 100644 --- a/crates/ruff_db/src/diagnostic/render/snapshots/ruff_db__diagnostic__render__full__tests__notebook_output_with_diff_spanning_cells.snap +++ b/crates/ruff_db/src/diagnostic/render/snapshots/ruff_db__diagnostic__render__full__tests__notebook_output_with_diff_spanning_cells.snap @@ -9,21 +9,16 @@ error[F401][*]: `os` imported but unused 2 | import os | ^^ help: Remove unused import: `os` - ::: cell 1 + ::: cell 1:1:1 | -1 | # cell 1 - - import os +1 - import os | - ::: cell 2 + ::: cell 2:1:1 | -1 | # cell 2 - - import math -2 | +1 - import math | - ::: cell 3 + ::: cell 3:3:1 | -3 | print() - - x = 1 -4 | +3 - x = 1 | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_db/src/diagnostic/stylesheet.rs b/crates/ruff_db/src/diagnostic/stylesheet.rs index ed4baf37b9fc0..22ff1e7b869b2 100644 --- a/crates/ruff_db/src/diagnostic/stylesheet.rs +++ b/crates/ruff_db/src/diagnostic/stylesheet.rs @@ -72,8 +72,6 @@ pub struct DiagnosticStylesheet { pub(crate) secondary_code: Style, pub(crate) insertion: Style, pub(crate) deletion: Style, - pub(crate) insertion_line_no: Style, - pub(crate) deletion_line_no: Style, pub(crate) hyperlink: bool, } @@ -102,8 +100,6 @@ impl DiagnosticStylesheet { secondary_code: AnsiColor::Red.on_default().effects(Effects::BOLD), insertion: AnsiColor::Green.on_default(), deletion: AnsiColor::Red.on_default(), - insertion_line_no: AnsiColor::Green.on_default().effects(Effects::BOLD), - deletion_line_no: AnsiColor::Red.on_default().effects(Effects::BOLD), hyperlink, } } @@ -131,8 +127,6 @@ impl DiagnosticStylesheet { secondary_code: Style::new(), insertion: Style::new(), deletion: Style::new(), - insertion_line_no: Style::new(), - deletion_line_no: Style::new(), hyperlink: false, } } diff --git a/crates/ruff_linter/resources/mdtest/flake8-pyi/redundant-numeric-union.md b/crates/ruff_linter/resources/mdtest/flake8-pyi/redundant-numeric-union.md index e52d8921de947..7cedced44aed6 100644 --- a/crates/ruff_linter/resources/mdtest/flake8-pyi/redundant-numeric-union.md +++ b/crates/ruff_linter/resources/mdtest/flake8-pyi/redundant-numeric-union.md @@ -67,8 +67,7 @@ error[PYI041]: Use `float` instead of `int | float` | ^^^^^^^^^^^ help: Remove redundant type | -6 | @dispatch.register - - def _(value: float | complex, other: int | float) -> None: ... # snapshot: redundant-numeric-union +7 - def _(value: float | complex, other: int | float) -> None: ... # snapshot: redundant-numeric-union 7 + def _(value: float | complex, other: float) -> None: ... # snapshot: redundant-numeric-union | ``` diff --git a/crates/ruff_linter/resources/mdtest/pyflakes/string-dot-format-extra-positional-arguments.md b/crates/ruff_linter/resources/mdtest/pyflakes/string-dot-format-extra-positional-arguments.md index 6ade98d90f368..0aa5bcc076978 100644 --- a/crates/ruff_linter/resources/mdtest/pyflakes/string-dot-format-extra-positional-arguments.md +++ b/crates/ruff_linter/resources/mdtest/pyflakes/string-dot-format-extra-positional-arguments.md @@ -24,9 +24,8 @@ error[F523]: `.format` call has unused arguments at position(s): 0 | ^^^^^^^^^^^^^^^^ help: Remove extra positional arguments at position(s): 0 | - - print("{{".format("!")) # snapshot: string-dot-format-extra-positional-arguments +1 - print("{{".format("!")) # snapshot: string-dot-format-extra-positional-arguments 1 + print("{{".format()) # snapshot: string-dot-format-extra-positional-arguments -2 | print("{x}".format("!")) # snapshot: string-dot-format-extra-positional-arguments | @@ -37,8 +36,7 @@ error[F523]: `.format` call has unused arguments at position(s): 0 | ^^^^^^^^^^^^^^^^^ help: Remove extra positional arguments at position(s): 0 | -1 | print("{{".format("!")) # snapshot: string-dot-format-extra-positional-arguments - - print("{x}".format("!")) # snapshot: string-dot-format-extra-positional-arguments +2 - print("{x}".format("!")) # snapshot: string-dot-format-extra-positional-arguments 2 + print("{x}".format()) # snapshot: string-dot-format-extra-positional-arguments | ``` diff --git a/crates/ruff_linter/resources/mdtest/pylint/invalid-character-backspace.md b/crates/ruff_linter/resources/mdtest/pylint/invalid-character-backspace.md index fdf7b66cd93b4..a37ac19c1e89d 100644 --- a/crates/ruff_linter/resources/mdtest/pylint/invalid-character-backspace.md +++ b/crates/ruff_linter/resources/mdtest/pylint/invalid-character-backspace.md @@ -54,9 +54,8 @@ error[PLE2510]: Invalid unescaped character backspace, use "\b" instead | ^ help: Replace with escape sequence | - - format_spec = f"{value:␈}" # snapshot: invalid-character-backspace +1 - format_spec = f"{value:␈}" # snapshot: invalid-character-backspace 1 + format_spec = f"{value:\b}" # snapshot: invalid-character-backspace -2 | f_string_literal = f"hello␈" # snapshot: invalid-character-backspace | @@ -67,8 +66,7 @@ error[PLE2510]: Invalid unescaped character backspace, use "\b" instead | ^ help: Replace with escape sequence | -1 | format_spec = f"{value:␈}" # snapshot: invalid-character-backspace - - f_string_literal = f"hello␈" # snapshot: invalid-character-backspace +2 - f_string_literal = f"hello␈" # snapshot: invalid-character-backspace 2 + f_string_literal = f"hello\b" # snapshot: invalid-character-backspace | ``` @@ -99,9 +97,8 @@ error[PLE2510]: Invalid unescaped character backspace, use "\b" instead | ^ help: Replace with escape sequence | - - replacement_field = f"{'␈'}" # snapshot: invalid-character-backspace +1 - replacement_field = f"{'␈'}" # snapshot: invalid-character-backspace 1 + replacement_field = f"{'\b'}" # snapshot: invalid-character-backspace -2 | format_spec = f"{value:␈}" # snapshot: invalid-character-backspace | @@ -112,10 +109,8 @@ error[PLE2510]: Invalid unescaped character backspace, use "\b" instead | ^ help: Replace with escape sequence | -1 | replacement_field = f"{'␈'}" # snapshot: invalid-character-backspace - - format_spec = f"{value:␈}" # snapshot: invalid-character-backspace +2 - format_spec = f"{value:␈}" # snapshot: invalid-character-backspace 2 + format_spec = f"{value:\b}" # snapshot: invalid-character-backspace -3 | f_string_literal = f"hello␈" # snapshot: invalid-character-backspace | @@ -126,10 +121,8 @@ error[PLE2510]: Invalid unescaped character backspace, use "\b" instead | ^ help: Replace with escape sequence | -2 | format_spec = f"{value:␈}" # snapshot: invalid-character-backspace - - f_string_literal = f"hello␈" # snapshot: invalid-character-backspace +3 - f_string_literal = f"hello␈" # snapshot: invalid-character-backspace 3 + f_string_literal = f"hello\b" # snapshot: invalid-character-backspace -4 | nested_f_string = f"{f'hello␈'}" # snapshot: invalid-character-backspace | @@ -140,8 +133,7 @@ error[PLE2510]: Invalid unescaped character backspace, use "\b" instead | ^ help: Replace with escape sequence | -3 | f_string_literal = f"hello␈" # snapshot: invalid-character-backspace - - nested_f_string = f"{f'hello␈'}" # snapshot: invalid-character-backspace +4 - nested_f_string = f"{f'hello␈'}" # snapshot: invalid-character-backspace 4 + nested_f_string = f"{f'hello\b'}" # snapshot: invalid-character-backspace | ``` diff --git a/crates/ruff_linter/resources/mdtest/pyupgrade/deprecated-abc-decorator.md b/crates/ruff_linter/resources/mdtest/pyupgrade/deprecated-abc-decorator.md index 328b7ce563977..e32513f8af168 100644 --- a/crates/ruff_linter/resources/mdtest/pyupgrade/deprecated-abc-decorator.md +++ b/crates/ruff_linter/resources/mdtest/pyupgrade/deprecated-abc-decorator.md @@ -33,11 +33,11 @@ error[UP051]: Use `@classmethod` and `@abstractmethod` instead of `abstractclass | ^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `@classmethod` and `abstractmethod` | +1 ~ import abc +2 | 3 | class Foo(abc.ABC): - - @abc.abstractclassmethod # snapshot: deprecated-abc-decorator -4 + @classmethod -5 + @abc.abstractmethod # snapshot: deprecated-abc-decorator -6 | def class_method(cls, arg1): ... +4 ~ @classmethod +5 ~ @abc.abstractmethod # snapshot: deprecated-abc-decorator | @@ -48,11 +48,12 @@ error[UP051]: Use `@staticmethod` and `@abstractmethod` instead of `abstractstat | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `@staticmethod` and `abstractmethod` | +1 ~ import abc +2 | +… 6 | - - @abc.abstractstaticmethod # snapshot: deprecated-abc-decorator -7 + @staticmethod -8 + @abc.abstractmethod # snapshot: deprecated-abc-decorator -9 | def static_method(arg1): ... +7 ~ @staticmethod +8 ~ @abc.abstractmethod # snapshot: deprecated-abc-decorator | @@ -63,10 +64,11 @@ error[UP051]: Use `@property` and `@abstractmethod` instead of `abstractproperty | ^^^^^^^^^^^^^^^^^^^^^ help: Replace with `@property` and `abstractmethod` | -9 | - - @abc.abstractproperty # snapshot: deprecated-abc-decorator -10 + @property -11 + @abc.abstractmethod # snapshot: deprecated-abc-decorator -12 | def prop(self): ... + 1 ~ import abc + 2 | + … + 9 | +10 ~ @property +11 ~ @abc.abstractmethod # snapshot: deprecated-abc-decorator | ``` diff --git a/crates/ruff_linter/resources/mdtest/pyupgrade/f-string.md b/crates/ruff_linter/resources/mdtest/pyupgrade/f-string.md index da0347d60eabf..e76d39e438796 100644 --- a/crates/ruff_linter/resources/mdtest/pyupgrade/f-string.md +++ b/crates/ruff_linter/resources/mdtest/pyupgrade/f-string.md @@ -43,8 +43,7 @@ error[UP032]: Use f-string instead of `format` call | ^^^^^^^^^^^^^^^^^^^^^ help: Convert to f-string | -3 | - - "{x}".format(x=foo()) # snapshot: f-string +4 - "{x}".format(x=foo()) # snapshot: f-string 4 + f"{foo()}" # snapshot: f-string | ``` @@ -67,9 +66,8 @@ error[UP032]: Use f-string instead of `format` call | ^^^^^^^^^^^^^^^^^ help: Convert to f-string | - - "" "{}".format(x) # snapshot: f-string +1 - "" "{}".format(x) # snapshot: f-string 1 + "" f"{x}" # snapshot: f-string -2 | "a" "" "{}".format(x) # snapshot: f-string | ``` @@ -85,10 +83,8 @@ error[UP032]: Use f-string instead of `format` call | ^^^^^^^^^^^^^^^^^^^^^ help: Convert to f-string | -1 | "" "{}".format(x) # snapshot: f-string - - "a" "" "{}".format(x) # snapshot: f-string +2 - "a" "" "{}".format(x) # snapshot: f-string 2 + "a" f"{x}" # snapshot: f-string -3 | x = ("" "{}").format(value) # snapshot: f-string | ``` @@ -107,10 +103,8 @@ error[UP032]: Use f-string instead of `format` call | ^^^^^^^^^^^^^^^^^^^^^^^ help: Convert to f-string | -2 | "a" "" "{}".format(x) # snapshot: f-string - - x = ("" "{}").format(value) # snapshot: f-string +3 - x = ("" "{}").format(value) # snapshot: f-string 3 + x = ("" f"{value}") # snapshot: f-string -4 | foo( | ``` @@ -134,10 +128,9 @@ error[UP032]: Use f-string instead of `format` call | |______________________^ help: Convert to f-string | -6 | # comment - - "{}".format(value) +5 ~ "" # snapshot: f-string +6 + # comment 7 + f"{value}" -8 | ) | ``` @@ -156,8 +149,7 @@ error[UP032]: Use f-string instead of `format` call | ^^^^^^^^^^^^^^^^^^^^^ help: Convert to f-string | -8 | ) - - y = ("" "").format(value) # snapshot: f-string +9 - y = ("" "").format(value) # snapshot: f-string 9 + y = ("" "") # snapshot: f-string | ``` diff --git a/crates/ruff_linter/resources/mdtest/pyupgrade/pep-695.md b/crates/ruff_linter/resources/mdtest/pyupgrade/pep-695.md index 6eece28c0e255..0d5b3192dd543 100644 --- a/crates/ruff_linter/resources/mdtest/pyupgrade/pep-695.md +++ b/crates/ruff_linter/resources/mdtest/pyupgrade/pep-695.md @@ -62,8 +62,7 @@ error[UP040]: Type alias `Pair` uses `TypeAlias` annotation instead of the `type | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use the `type` keyword | -5 | - - Pair: TypeAlias = tuple[S, T] # snapshot: non-pep695-type-alias +6 - Pair: TypeAlias = tuple[S, T] # snapshot: non-pep695-type-alias 6 + type Pair[S, T = int] = tuple[S, T] # snapshot: non-pep695-type-alias | note: This is an unsafe fix and may change runtime behavior @@ -116,10 +115,8 @@ error[UP046]: Generic class `Pair` uses `Generic` subclass instead of type param | ^^^^^^^^^^^^^ help: Use type parameters | -5 | - - class Pair(Generic[S, T]): # snapshot: non-pep695-generic-class +6 - class Pair(Generic[S, T]): # snapshot: non-pep695-generic-class 6 + class Pair[S, T = int]: # snapshot: non-pep695-generic-class -7 | t: T | note: This is an unsafe fix and may change runtime behavior ``` @@ -158,10 +155,7 @@ error[UP047]: Generic function `pair` should use type parameters | ^^^^^^^^^^^^^^^^ help: Use type parameters | -5 | - - def pair(s: S, t: T) -> tuple[S, T]: # snapshot: non-pep695-generic-function -6 + def pair[S, T = int](s: S, t: T) -> tuple[S, T]: # snapshot: non-pep695-generic-function -7 | return (s, t) - | +6 | def pair[S, T = int](s: S, t: T) -> tuple[S, T]: # snapshot: non-pep695-generic-function + | ++++++++++++ note: This is an unsafe fix and may change runtime behavior ``` diff --git a/crates/ruff_linter/resources/mdtest/ruff/noqa-comments.md b/crates/ruff_linter/resources/mdtest/ruff/noqa-comments.md index 5c339fc7ad618..f2e187dedef4e 100644 --- a/crates/ruff_linter/resources/mdtest/ruff/noqa-comments.md +++ b/crates/ruff_linter/resources/mdtest/ruff/noqa-comments.md @@ -24,10 +24,8 @@ error[RUF105]: `ruff: noqa` comment used instead of `ruff: file-ignore` | ^^^^^^^^^^^^^^^^^^ help: Use `ruff: file-ignore` instead | -1 | # snapshot: noqa-comments - - # ruff: noqa: F401 +2 - # ruff: noqa: F401 2 + # ruff: file-ignore[F401] -3 | import math | ``` @@ -51,10 +49,8 @@ error[RUF105]: `ruff: noqa` comment used instead of `ruff: file-ignore` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use `ruff: file-ignore` instead | -1 | # snapshot: noqa-comments - - # ruff: noqa: F401, F402, F403 +2 - # ruff: noqa: F401, F402, F403 2 + # ruff: file-ignore[F401, F402, F403] -3 | import math | ``` @@ -78,10 +74,8 @@ error[RUF105]: `ruff: noqa` comment used instead of `ruff: file-ignore` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use `ruff: file-ignore` instead | -1 | # snapshot: noqa-comments - - # ruff: noqa: F401, F402, F403 for some reason +2 - # ruff: noqa: F401, F402, F403 for some reason 2 + # ruff: file-ignore[F401, F402, F403] for some reason -3 | import math | ``` @@ -105,10 +99,8 @@ error[RUF105]: `ruff: noqa` comment used instead of `ruff: file-ignore` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use `ruff: file-ignore` instead | -1 | # snapshot: noqa-comments - - # ruff: noqa: F401, F402, F403 # fmt:skip +2 - # ruff: noqa: F401, F402, F403 # fmt:skip 2 + # ruff: file-ignore[F401, F402, F403] # fmt:skip -3 | import math | ``` @@ -137,8 +129,7 @@ error[RUF105]: `noqa` comment used instead of `ruff: ignore` | ^^^^^^^^^^^^^^^^^^^^ help: Use `ruff: ignore` instead | -2 | # snapshot: noqa-comments - - import math # noqa: F401, UNK001 +3 - import math # noqa: F401, UNK001 3 + import math # ruff: ignore[F401, UNK001] | ``` @@ -222,8 +213,7 @@ error[RUF105]: `noqa` comment used instead of `ruff: ignore` | ^^^^^^^^^^^^ help: Use `ruff: ignore` instead | -1 | # snapshot: noqa-comments - - import math # noqa: F401 +2 - import math # noqa: F401 2 + import math # ruff: ignore[F401] | ``` @@ -261,8 +251,7 @@ error[RUF105]: `noqa` comment used instead of `ruff: ignore` | ^^^^^^^^^^^^ help: Use `ruff: ignore` instead | -1 | # snapshot: noqa-comments - - import math # fmt:skip # noqa: F401 +2 - import math # fmt:skip # noqa: F401 2 + import math # fmt:skip # ruff: ignore[F401] | ``` @@ -287,10 +276,8 @@ error[RUF105]: `noqa` comment used instead of `ruff: ignore` | ^^^^^^ help: Use `ruff: ignore` instead | -1 | # snapshot: noqa-comments - - import math # noqa +2 - import math # noqa 2 + import math # ruff: ignore[F401] -3 | # snapshot: noqa-comments | ``` @@ -309,8 +296,7 @@ error[RUF105]: `noqa` comment used instead of `ruff: ignore` | ^^^^^^ help: Use `ruff: ignore` instead | -3 | # snapshot: noqa-comments - - import foo, bar # noqa +4 - import foo, bar # noqa 4 + import foo, bar # ruff: ignore[F401] | ``` diff --git a/crates/ruff_linter/resources/mdtest/ruff/rule-codes-in-selectors.md b/crates/ruff_linter/resources/mdtest/ruff/rule-codes-in-selectors.md index 8c9729f43cced..c74c0b14cfcce 100644 --- a/crates/ruff_linter/resources/mdtest/ruff/rule-codes-in-selectors.md +++ b/crates/ruff_linter/resources/mdtest/ruff/rule-codes-in-selectors.md @@ -28,10 +28,8 @@ error[RUF201]: Rule code used instead of name in `lint.select` | ^^^^ help: Replace rule code with `unused-import` | -2 | select = [ - - "F401", # snapshot: rule-codes-in-selectors +3 - "F401", # snapshot: rule-codes-in-selectors 3 + "unused-import", # snapshot: rule-codes-in-selectors -4 | 'F402', # snapshot: rule-codes-in-selectors | @@ -42,10 +40,8 @@ error[RUF201]: Rule code used instead of name in `lint.select` | ^^^^ help: Replace rule code with `import-shadowed-by-loop-var` | -3 | "F401", # snapshot: rule-codes-in-selectors - - 'F402', # snapshot: rule-codes-in-selectors +4 - 'F402', # snapshot: rule-codes-in-selectors 4 + 'import-shadowed-by-loop-var', # snapshot: rule-codes-in-selectors -5 | """F403""", # snapshot: rule-codes-in-selectors | @@ -56,10 +52,8 @@ error[RUF201]: Rule code used instead of name in `lint.select` | ^^^^ help: Replace rule code with `undefined-local-with-import-star` | -4 | 'F402', # snapshot: rule-codes-in-selectors - - """F403""", # snapshot: rule-codes-in-selectors +5 - """F403""", # snapshot: rule-codes-in-selectors 5 + """undefined-local-with-import-star""", # snapshot: rule-codes-in-selectors -6 | '''F404''', # snapshot: rule-codes-in-selectors | @@ -70,10 +64,8 @@ error[RUF201]: Rule code used instead of name in `lint.select` | ^^^^ help: Replace rule code with `late-future-import` | -5 | """F403""", # snapshot: rule-codes-in-selectors - - '''F404''', # snapshot: rule-codes-in-selectors +6 - '''F404''', # snapshot: rule-codes-in-selectors 6 + '''late-future-import''', # snapshot: rule-codes-in-selectors -7 | ] | ``` @@ -98,8 +90,7 @@ error[RUF201]: Rule code used instead of name in `lint.select` | ^^^^ help: Replace rule code with `import-shadowed-by-loop-var` | -2 | # snapshot: rule-codes-in-selectors - - select = ["'F401'", "F402"] +3 - select = ["'F401'", "F402"] 3 + select = ["'F401'", "import-shadowed-by-loop-var"] | ``` diff --git a/crates/ruff_linter/resources/mdtest/ruff/rule-codes-in-suppression-comments.md b/crates/ruff_linter/resources/mdtest/ruff/rule-codes-in-suppression-comments.md index 8f5d43dbc29d5..79c4a76d09260 100644 --- a/crates/ruff_linter/resources/mdtest/ruff/rule-codes-in-suppression-comments.md +++ b/crates/ruff_linter/resources/mdtest/ruff/rule-codes-in-suppression-comments.md @@ -27,10 +27,8 @@ error[RUF106]: Rule code used instead of name in suppression comment | ^^^^ help: Replace rule code with name | -2 | # snapshot: rule-codes-in-suppression-comments - - # ruff:ignore[F401, undefined-name, EXT001, UNKNOWN, F841] +3 - # ruff:ignore[F401, undefined-name, EXT001, UNKNOWN, F841] 3 + # ruff:ignore[unused-import, undefined-name, EXT001, UNKNOWN, F841] -4 | value = 1 | @@ -41,10 +39,8 @@ error[RUF106]: Rule code used instead of name in suppression comment | ^^^^ help: Replace rule code with name | -2 | # snapshot: rule-codes-in-suppression-comments - - # ruff:ignore[F401, undefined-name, EXT001, UNKNOWN, F841] +3 - # ruff:ignore[F401, undefined-name, EXT001, UNKNOWN, F841] 3 + # ruff:ignore[F401, undefined-name, EXT001, UNKNOWN, unused-variable] -4 | value = 1 | ``` @@ -65,10 +61,8 @@ error[RUF106]: Rule code used instead of name in suppression comment | ^^^^ help: Replace rule code with name | -6 | # snapshot: rule-codes-in-suppression-comments - - # ruff:ignore[F401, undefined-name, F841] +7 - # ruff:ignore[F401, undefined-name, F841] 7 + # ruff:ignore[unused-import, undefined-name, F841] -8 | value = 1 | @@ -79,10 +73,8 @@ error[RUF106]: Rule code used instead of name in suppression comment | ^^^^ help: Replace rule code with name | -6 | # snapshot: rule-codes-in-suppression-comments - - # ruff:ignore[F401, undefined-name, F841] +7 - # ruff:ignore[F401, undefined-name, F841] 7 + # ruff:ignore[F401, undefined-name, unused-variable] -8 | value = 1 | ``` @@ -102,8 +94,7 @@ error[RUF106]: Rule code used instead of name in suppression comment | ^^^^ help: Replace rule code with name | -2 | # snapshot: rule-codes-in-suppression-comments - - # ruff:file-ignore[F401, F841] +3 - # ruff:file-ignore[F401, F841] 3 + # ruff:file-ignore[unused-import, F841] | @@ -115,8 +106,7 @@ error[RUF106]: Rule code used instead of name in suppression comment | ^^^^ help: Replace rule code with name | -2 | # snapshot: rule-codes-in-suppression-comments - - # ruff:file-ignore[F401, F841] +3 - # ruff:file-ignore[F401, F841] 3 + # ruff:file-ignore[F401, unused-variable] | ``` @@ -144,12 +134,9 @@ error[RUF106]: Rule code used instead of name in suppression comment | ---- help: Replace rule code with name | -2 | # snapshot: rule-codes-in-suppression-comments - - # ruff:disable[F401, undefined-name, F841] -3 + # ruff:disable[unused-import, undefined-name, F841] +3 ~ # ruff:disable[unused-import, undefined-name, F841] 4 | value = 1 - - # ruff:enable[F401, undefined-name, F841] -5 + # ruff:enable[unused-import, undefined-name, F841] +5 ~ # ruff:enable[unused-import, undefined-name, F841] | @@ -163,12 +150,9 @@ error[RUF106]: Rule code used instead of name in suppression comment | ---- help: Replace rule code with name | -2 | # snapshot: rule-codes-in-suppression-comments - - # ruff:disable[F401, undefined-name, F841] -3 + # ruff:disable[F401, undefined-name, unused-variable] +3 ~ # ruff:disable[F401, undefined-name, unused-variable] 4 | value = 1 - - # ruff:enable[F401, undefined-name, F841] -5 + # ruff:enable[F401, undefined-name, unused-variable] +5 ~ # ruff:enable[F401, undefined-name, unused-variable] | ``` @@ -190,8 +174,7 @@ error[RUF106]: Rule code used instead of name in suppression comment | ^^^^ help: Replace rule code with name | -1 | # snapshot: rule-codes-in-suppression-comments - - # ruff:disable[F401] +2 - # ruff:disable[F401] 2 + # ruff:disable[unused-import] | ``` @@ -222,10 +205,8 @@ error[RUF106]: Rule code used instead of name in suppression comment | ^^^^^^ help: Replace rule code with name | -1 | # snapshot: rule-codes-in-suppression-comments - - # ruff:ignore[PGH001] +2 - # ruff:ignore[PGH001] 2 + # ruff:ignore[suspicious-eval-usage] -3 | value = 1 | ``` @@ -247,8 +228,7 @@ error[RUF106]: Rule code used instead of name in suppression comment | ^^^^ help: Replace rule code with name | -2 | # snapshot: rule-codes-in-suppression-comments - - value = 1 # explanation # ruff:ignore[F401, F841] reason # another +3 - value = 1 # explanation # ruff:ignore[F401, F841] reason # another 3 + value = 1 # explanation # ruff:ignore[unused-import, F841] reason # another | @@ -260,8 +240,7 @@ error[RUF106]: Rule code used instead of name in suppression comment | ^^^^ help: Replace rule code with name | -2 | # snapshot: rule-codes-in-suppression-comments - - value = 1 # explanation # ruff:ignore[F401, F841] reason # another +3 - value = 1 # explanation # ruff:ignore[F401, F841] reason # another 3 + value = 1 # explanation # ruff:ignore[F401, unused-variable] reason # another | ``` diff --git a/crates/ruff_linter/resources/mdtest/suppression/ignore.md b/crates/ruff_linter/resources/mdtest/suppression/ignore.md index dca3a68ddfc15..f610644c2aced 100644 --- a/crates/ruff_linter/resources/mdtest/suppression/ignore.md +++ b/crates/ruff_linter/resources/mdtest/suppression/ignore.md @@ -263,10 +263,8 @@ error[RUF100]: Unused suppression (unused: `F401`) | ^^^^^^^^^^^^^^^^^^^^ help: Remove unused suppression | -20 | # snapshot: unused-noqa - - import sys # start # ruff:ignore[F401] # end +21 - import sys # start # ruff:ignore[F401] # end 21 + import sys # start # end -22 | # ruff:enable[F401] | note: This is an unsafe fix and may change runtime behavior ``` @@ -339,12 +337,7 @@ error[RUF102]: Invalid rule code in suppression: unused-import help: Enable `lint.preview` to use rule names help: Remove the suppression comment | -1 | # snapshot: invalid-rule-code - - # ruff:disable[unused-import] -2 | # error: [unused-import] -3 | import math - - # ruff:enable[unused-import] -4 | # snapshot: invalid-rule-code +2 + | ``` @@ -372,11 +365,7 @@ help: Add non-Ruff rule codes to the `lint.external` configuration option help: Enable `lint.preview` to use rule names help: Remove the suppression comment | -6 | # snapshot: invalid-rule-code - - # ruff:disable[unused-import, unknown-rule] -7 | # error: [unused-import] -8 | import sys - - # ruff:enable[unused-import, unknown-rule] +7 + | ``` @@ -444,8 +433,7 @@ error[RUF103]: Invalid suppression comment: no matching 'disable' comment | ^^^^^^^^^^^^^^^^^^^ help: Remove suppression comment | -11 | # snapshot: invalid-suppression-comment - - # ruff:enable[F401] +12 - # ruff:enable[F401] | note: This is an unsafe fix and may change runtime behavior ``` @@ -484,10 +472,8 @@ error[RUF102]: Invalid rule code in suppression: not-a-rule help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the rule code `not-a-rule` | -1 | # snapshot: invalid-rule-code - - # ruff:ignore[unused-import, not-a-rule] +2 - # ruff:ignore[unused-import, not-a-rule] 2 + # ruff:ignore[unused-import] -3 | import pathlib | ``` @@ -516,10 +502,8 @@ error[RUF100]: Unused suppression (unused: `unused-import`) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove unused suppression | -7 | # snapshot: unused-noqa - - import math # ruff:ignore[unused-import] +8 - import math # ruff:ignore[unused-import] 8 + import math -9 | | ``` @@ -540,10 +524,8 @@ error[RUF100]: Unused suppression (unused: `unused-import`) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove unused suppression | -11 | # snapshot: unused-noqa - - # ruff:ignore[F401, unused-import] +12 - # ruff:ignore[F401, unused-import] 12 + # ruff:ignore[F401] -13 | import pathlib | ``` @@ -576,10 +558,8 @@ error[RUF103]: Invalid suppression comment: missing suppression codes like `[E50 | ^^^^^^^^^^^^^^ help: Remove suppression comment | -3 | # error: [unused-import] - - import sys # explanation # ruff:ignore # another +4 - import sys # explanation # ruff:ignore # another 4 + import sys # explanation # another -5 | # error: [unmatched-suppression-comment] | note: This is an unsafe fix and may change runtime behavior ``` @@ -625,10 +605,8 @@ error[RUF103]: Invalid suppression comment: trailing comments are only supported | ^^^^^^^^^^^^^^^^^^^^ help: Remove suppression comment | -1 | # snapshot: invalid-suppression-comment - - # explanation # ruff:disable[F401] +2 - # explanation # ruff:disable[F401] 2 + # explanation -3 | # error: [unused-import] | note: This is an unsafe fix and may change runtime behavior ``` @@ -701,10 +679,8 @@ error[RUF100]: Unused suppression (unused: `E501`) | ^^^^^^^^^^^^^^^^^^^^ help: Remove unused suppression | -2 | # error: [invalid-suppression-comment] - - # ruff:ignore[E501] # ruff:file-ignore[F821] +3 - # ruff:ignore[E501] # ruff:file-ignore[F821] 3 + # ruff:file-ignore[F821] -4 | # error: [undefined-name] | note: This is an unsafe fix and may change runtime behavior ``` @@ -735,12 +711,7 @@ error[RUF100]: Unused suppression (unused: `E501`) | ------------------- help: Remove unused suppression | -7 | # error: [unused-noqa] "F821" - - # ruff:disable[E501] # ruff:ignore[F821] -8 + # ruff:ignore[F821] -9 | # error: [undefined-name] -10 | undefined_name - - # ruff:enable[E501] + 8 | # ruff:ignore[F821] | note: This is an unsafe fix and may change runtime behavior ``` @@ -772,11 +743,7 @@ error[RUF100]: Unused suppression (unused: `E501`) | -------------------- help: Remove unused suppression | -1 | # snapshot: unused-noqa - - # ruff:disable[E501] -2 | value = 1 - - # ruff:enable[E501] # TODO # ruff:ignore[FIX002] -3 + # TODO # ruff:ignore[FIX002] +2 + | note: This is an unsafe fix and may change runtime behavior ``` @@ -806,10 +773,8 @@ error[RUF100]: Unused suppression (unused: `E501`) | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove unused suppression | -2 | # error: [invalid-suppression-comment] - - # ruff:ignore[E501, F821] # ruff:file-ignore[F401] +3 - # ruff:ignore[E501, F821] # ruff:file-ignore[F401] 3 + # ruff:ignore[F821] # ruff:file-ignore[F401] -4 | undefined_name | ``` @@ -839,10 +804,8 @@ error[RUF102]: Invalid rule code in suppression: XYZ help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the suppression comment | -2 | # error: [invalid-suppression-comment] - - # ruff:ignore[XYZ] # ruff:file-ignore[F821] +3 - # ruff:ignore[XYZ] # ruff:file-ignore[F821] 3 + # ruff:file-ignore[F821] -4 | # error: [undefined-name] | note: This is an unsafe fix and may change runtime behavior ``` @@ -873,10 +836,8 @@ error[RUF103]: Invalid suppression comment: trailing comments are only supported | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove suppression comment | -3 | # error: [unused-noqa] - - # explanation # ruff:file-ignore[F401] # ruff:ignore[F401] +4 - # explanation # ruff:file-ignore[F401] # ruff:ignore[F401] 4 + # explanation # ruff:ignore[F401] -5 | # error: [unused-import] | note: This is an unsafe fix and may change runtime behavior ``` @@ -898,12 +859,10 @@ error[RUF103]: Invalid suppression comment: missing suppression codes like `[E50 9 | # explanation # ruff:ignore # ruff:ignore[F821] | ^^^^^^^^^^^^^^ help: Remove suppression comment - | -8 | # error: [unused-noqa] - - # explanation # ruff:ignore # ruff:ignore[F821] -9 + # explanation # ruff:ignore[F821] -10 | # error: [undefined-name] - | + | +9 - # explanation # ruff:ignore # ruff:ignore[F821] +9 + # explanation # ruff:ignore[F821] + | note: This is an unsafe fix and may change runtime behavior ``` @@ -931,10 +890,8 @@ error[RUF103]: Invalid suppression comment: unknown ruff directive | ^^^^^^^^^^^^^^^^^^^^^ help: Remove suppression comment | -1 | # snapshot: invalid-suppression-comment - - import os # explanation # ruff:unknown[F401] # another +2 - import os # explanation # ruff:unknown[F401] # another 2 + import os # explanation # another -3 | # snapshot: invalid-suppression-comment | note: This is an unsafe fix and may change runtime behavior @@ -946,8 +903,7 @@ error[RUF103]: Invalid suppression comment: missing comma between codes | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove suppression comment | -3 | # snapshot: invalid-suppression-comment - - import sys # explanation # ruff:ignore[F401 F841] # another +4 - import sys # explanation # ruff:ignore[F401 F841] # another 4 + import sys # explanation # another | note: This is an unsafe fix and may change runtime behavior @@ -992,10 +948,8 @@ error[RUF100]: Unused suppression (non-enabled: `F401`) | ^^^^^^^^^^^^^^^^^^^^ help: Remove unused suppression | -1 | # snapshot: unused-noqa - - value = 1 # before # ruff:ignore[F401] # after +2 - value = 1 # before # ruff:ignore[F401] # after 2 + value = 1 # before # after -3 | | note: This is an unsafe fix and may change runtime behavior @@ -1007,8 +961,7 @@ error[RUF100]: Unused suppression (non-enabled: `F401`) | ^^^^^^^^^^^^^^^^^^^ help: Remove unused suppression | -4 | # snapshot: unused-noqa - - value = 1 # before # ruff:ignore[F401] +5 - value = 1 # before # ruff:ignore[F401] 5 + value = 1 # before | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR201_AIR201.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR201_AIR201.py.snap index d30b8dcab2360..4c1b8177851be 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR201_AIR201.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR201_AIR201.py.snap @@ -12,10 +12,8 @@ AIR201 [*] Use the `.output` attribute on the task object for "task_1" instead o | help: Replace with `task_1.output` | -17 | task_id="task_2", - - bash_command="{{ ti.xcom_pull(task_ids='task_1') }}", # AIR201 (fix: task_1.output) +18 - bash_command="{{ ti.xcom_pull(task_ids='task_1') }}", # AIR201 (fix: task_1.output) 18 + bash_command=task_1.output, # AIR201 (fix: task_1.output) -19 | ) | note: This is an unsafe fix and may change runtime behavior @@ -30,10 +28,8 @@ AIR201 [*] Use the `.output` attribute on the task object for "task_1" instead o | help: Replace with `task_1.output` | -23 | task_id="task_3", - - bash_command="{{ task_instance.xcom_pull(task_ids='task_1') }}", # AIR201 (fix: task_1.output) +24 - bash_command="{{ task_instance.xcom_pull(task_ids='task_1') }}", # AIR201 (fix: task_1.output) 24 + bash_command=task_1.output, # AIR201 (fix: task_1.output) -25 | ) | note: This is an unsafe fix and may change runtime behavior @@ -48,10 +44,8 @@ AIR201 [*] Use the `.output` attribute on the task object for "task_1" instead o | help: Replace with `task_1.output` | -29 | task_id="task_4", - - bash_command="{{ ti.xcom_pull('task_1') }}", # AIR201 (fix: task_1.output) +30 - bash_command="{{ ti.xcom_pull('task_1') }}", # AIR201 (fix: task_1.output) 30 + bash_command=task_1.output, # AIR201 (fix: task_1.output) -31 | ) | note: This is an unsafe fix and may change runtime behavior @@ -66,10 +60,8 @@ AIR201 [*] Use the `.output` attribute on the task object for "task_1" instead o | help: Replace with `task_1.output` | -35 | task_id="task_5", - - bash_command='{{ ti.xcom_pull(task_ids="task_1") }}', # AIR201 (fix: task_1.output) +36 - bash_command='{{ ti.xcom_pull(task_ids="task_1") }}', # AIR201 (fix: task_1.output) 36 + bash_command=task_1.output, # AIR201 (fix: task_1.output) -37 | ) | note: This is an unsafe fix and may change runtime behavior @@ -84,10 +76,8 @@ AIR201 [*] Use the `.output` attribute on the task object for "task_1" instead o | help: Replace with `task_1.output` | -41 | task_id="task_6", - - bash_command="{{ti.xcom_pull(task_ids='task_1')}}", # AIR201 (fix: task_1.output) +42 - bash_command="{{ti.xcom_pull(task_ids='task_1')}}", # AIR201 (fix: task_1.output) 42 + bash_command=task_1.output, # AIR201 (fix: task_1.output) -43 | ) | note: This is an unsafe fix and may change runtime behavior @@ -102,10 +92,8 @@ AIR201 [*] Use the `.output` attribute on the task object for "task_1" instead o | help: Replace with `task_1.output` | -47 | task_id="task_7", - - bash_command="{{ ti.xcom_pull(task_id='task_1') }}", # AIR201 (fix: task_1.output) +48 - bash_command="{{ ti.xcom_pull(task_id='task_1') }}", # AIR201 (fix: task_1.output) 48 + bash_command=task_1.output, # AIR201 (fix: task_1.output) -49 | ) | note: This is an unsafe fix and may change runtime behavior @@ -120,10 +108,8 @@ AIR201 [*] Use the `.output` attribute on the task object for "task_1" instead o | help: Replace with `task_1.output` | -53 | task_id="task_8", - - external_task_id="{{ ti.xcom_pull(task_ids='task_1') }}", # AIR201 (fix: task_1.output) +54 - external_task_id="{{ ti.xcom_pull(task_ids='task_1') }}", # AIR201 (fix: task_1.output) 54 + external_task_id=task_1.output, # AIR201 (fix: task_1.output) -55 | ) | note: This is an unsafe fix and may change runtime behavior @@ -138,10 +124,8 @@ AIR201 [*] Use the `.output` attribute on the task object for "task_1" instead o | help: Replace with `task_1.output` | -59 | task_id="task_9", - - endpoint="{{ ti.xcom_pull(task_ids='task_1') }}", # AIR201 (fix: task_1.output) +60 - endpoint="{{ ti.xcom_pull(task_ids='task_1') }}", # AIR201 (fix: task_1.output) 60 + endpoint=task_1.output, # AIR201 (fix: task_1.output) -61 | ) | note: This is an unsafe fix and may change runtime behavior @@ -156,10 +140,8 @@ AIR201 [*] Use the `.output` attribute on the task object for "task_1" instead o | help: Replace with `task_1.output` | -66 | task_id="task_18", - - bash_command="{{ ti.xcom_pull(task_ids=['task_1']) }}", # AIR201 (fix: task_1.output) +67 - bash_command="{{ ti.xcom_pull(task_ids=['task_1']) }}", # AIR201 (fix: task_1.output) 67 + bash_command=task_1.output, # AIR201 (fix: task_1.output) -68 | ) | note: This is an unsafe fix and may change runtime behavior @@ -174,10 +156,8 @@ AIR201 [*] Use the `.output` attribute on the task object for "task_1" instead o | help: Replace with `task_1.output` | -72 | task_id="task_19", - - bash_command="{{ ti.xcom_pull(task_ids=('task_1',)) }}", # AIR201 (fix: task_1.output) +73 - bash_command="{{ ti.xcom_pull(task_ids=('task_1',)) }}", # AIR201 (fix: task_1.output) 73 + bash_command=task_1.output, # AIR201 (fix: task_1.output) -74 | ) | note: This is an unsafe fix and may change runtime behavior @@ -192,10 +172,8 @@ AIR201 [*] Use the `.output` attribute on the task object for "task_1" instead o | help: Replace with `task_1.output` | -78 | task_id="task_20", - - bash_command="{{ ti.xcom_pull(task_ids='task_1', key='return_value') }}", # AIR201 (fix: task_1.output) +79 - bash_command="{{ ti.xcom_pull(task_ids='task_1', key='return_value') }}", # AIR201 (fix: task_1.output) 79 + bash_command=task_1.output, # AIR201 (fix: task_1.output) -80 | ) | note: This is an unsafe fix and may change runtime behavior @@ -210,10 +188,8 @@ AIR201 [*] Use the `.output` attribute on the task object for "task_1" instead o | help: Replace with `task_1.output` | -84 | task_id="task_21", - - bash_command="{{ ti.xcom_pull(task_ids=['task_1'], key='return_value') }}", # AIR201 (fix: task_1.output) +85 - bash_command="{{ ti.xcom_pull(task_ids=['task_1'], key='return_value') }}", # AIR201 (fix: task_1.output) 85 + bash_command=task_1.output, # AIR201 (fix: task_1.output) -86 | ) | note: This is an unsafe fix and may change runtime behavior @@ -228,10 +204,8 @@ AIR201 [*] Use the `.output` attribute on the task object for "task_1" instead o | help: Replace with `task_1.output` | -90 | task_id="task_22", - - bash_command='{{ task_instance.xcom_pull(task_ids=["task_1"], key="return_value") }}', # AIR201 (fix: task_1.output) +91 - bash_command='{{ task_instance.xcom_pull(task_ids=["task_1"], key="return_value") }}', # AIR201 (fix: task_1.output) 91 + bash_command=task_1.output, # AIR201 (fix: task_1.output) -92 | ) | note: This is an unsafe fix and may change runtime behavior @@ -246,10 +220,8 @@ AIR201 [*] Use the `.output` attribute on the task object for "task_1" instead o | help: Replace with `task_1.output` | -96 | task_id="task_25", - - bash_command="{{ ti.xcom_pull(key='return_value', task_ids='task_1') }}", # AIR201 (fix: task_1.output) +97 - bash_command="{{ ti.xcom_pull(key='return_value', task_ids='task_1') }}", # AIR201 (fix: task_1.output) 97 + bash_command=task_1.output, # AIR201 (fix: task_1.output) -98 | ) | note: This is an unsafe fix and may change runtime behavior @@ -264,10 +236,8 @@ AIR201 [*] Use the `.output` attribute on the task object for "extract_data" ins | help: Replace with `extract_data.output` | -107 | task_id="task_16", - - bash_command="{{ ti.xcom_pull(task_ids='extract_data') }}", # AIR201 (fix: extract_data.output) +108 - bash_command="{{ ti.xcom_pull(task_ids='extract_data') }}", # AIR201 (fix: extract_data.output) 108 + bash_command=extract_data.output, # AIR201 (fix: extract_data.output) -109 | ) | note: This is an unsafe fix and may change runtime behavior @@ -315,9 +285,7 @@ AIR201 [*] Use the `.output` attribute on the task object for "len" instead of ` | help: Replace with `len.output` | -133 | task_id="task_28", - - op_args="{{ ti.xcom_pull(task_ids='len') }}", # AIR201 (fix: len.output) +134 - op_args="{{ ti.xcom_pull(task_ids='len') }}", # AIR201 (fix: len.output) 134 + op_args=len.output, # AIR201 (fix: len.output) -135 | ) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR202_AIR202.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR202_AIR202.py.snap index 240e6a59a657a..54f60bcbd8c3b 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR202_AIR202.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR202_AIR202.py.snap @@ -11,11 +11,8 @@ AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference | help: Add `multiple_outputs=True` | -14 | - - @task -15 + @task(multiple_outputs=True) -16 | def annotated_dict() -> dict: # AIR202 - | +15 | @task(multiple_outputs=True) + | +++++++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference @@ -28,11 +25,8 @@ AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference | help: Add `multiple_outputs=True` | -19 | - - @task() -20 + @task(multiple_outputs=True) -21 | def annotated_dict_subscript() -> dict[str, int]: # AIR202 - | +20 | @task(multiple_outputs=True) + | +++++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference @@ -45,11 +39,8 @@ AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference | help: Add `multiple_outputs=True` | -24 | - - @task -25 + @task(multiple_outputs=True) -26 | def annotated_typing_dict() -> Dict[str, int]: # AIR202 - | +25 | @task(multiple_outputs=True) + | +++++++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference @@ -62,11 +53,8 @@ AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference | help: Add `multiple_outputs=True` | -29 | - - @task -30 + @task(multiple_outputs=True) -31 | def annotated_typing_mapping() -> Mapping[str, int]: # AIR202 - | +30 | @task(multiple_outputs=True) + | +++++++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference @@ -79,11 +67,8 @@ AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference | help: Add `multiple_outputs=True` | -34 | - - @task -35 + @task(multiple_outputs=True) -36 | def annotated_collections_abc_mapping() -> collections.abc.Mapping: # AIR202 - | +35 | @task(multiple_outputs=True) + | +++++++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference @@ -96,11 +81,8 @@ AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference | help: Add `multiple_outputs=True` | -39 | - - @task -40 + @task(multiple_outputs=True) -41 | def annotated_mutable_mapping() -> MutableMapping[str, int]: # AIR202 - | +40 | @task(multiple_outputs=True) + | +++++++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference @@ -113,11 +95,8 @@ AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference | help: Add `multiple_outputs=True` | -48 | - - @task -49 + @task(multiple_outputs=True) -50 | def annotated_typed_dict() -> MyTD: # AIR202 - | +49 | @task(multiple_outputs=True) + | +++++++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference @@ -130,11 +109,8 @@ AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference | help: Add `multiple_outputs=True` | -53 | - - @sdk_task -54 + @sdk_task(multiple_outputs=True) -55 | def annotated_dict_via_sdk() -> dict: # AIR202 - | +54 | @sdk_task(multiple_outputs=True) + | +++++++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference @@ -147,11 +123,8 @@ AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference | help: Add `multiple_outputs=False` | -61 | - - @task -62 + @task(multiple_outputs=False) -63 | def body_dict_literal(): # AIR202 - | +62 | @task(multiple_outputs=False) + | ++++++++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference @@ -164,11 +137,8 @@ AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference | help: Add `multiple_outputs=False` | -66 | - - @task -67 + @task(multiple_outputs=False) -68 | def body_dict_comp(): # AIR202 - | +67 | @task(multiple_outputs=False) + | ++++++++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference @@ -181,11 +151,8 @@ AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference | help: Add `multiple_outputs=False` | -71 | - - @task -72 + @task(multiple_outputs=False) -73 | def body_dict_call(): # AIR202 - | +72 | @task(multiple_outputs=False) + | ++++++++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference @@ -198,11 +165,8 @@ AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference | help: Add `multiple_outputs=False` | -76 | - - @task -77 + @task(multiple_outputs=False) -78 | def body_dict_literal_annotated_non_mapping() -> int: # AIR202 - | +77 | @task(multiple_outputs=False) + | ++++++++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference @@ -215,11 +179,8 @@ AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference | help: Add `multiple_outputs=True` | -84 | - - @task(retries=3) -85 + @task(multiple_outputs=True, retries=3) -86 | def call_form_with_kwarg() -> dict: # AIR202 - | +85 | @task(multiple_outputs=True, retries=3) + | ++++++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference @@ -234,11 +195,8 @@ AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference | help: Add `multiple_outputs=True` | -90 | @task( - - retries=3, -91 + multiple_outputs=True, retries=3, -92 | ) - | +91 | multiple_outputs=True, retries=3, + | ++++++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference @@ -251,11 +209,8 @@ AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference | help: Add `multiple_outputs=False` | -99 | - - @task.branch -100 + @task.branch(multiple_outputs=False) -101 | def variant_branch(): # AIR202 - | +100 | @task.branch(multiple_outputs=False) + | ++++++++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference @@ -268,11 +223,8 @@ AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference | help: Add `multiple_outputs=False` | -104 | - - @task.short_circuit -105 + @task.short_circuit(multiple_outputs=False) -106 | def variant_short_circuit(): # AIR202 - | +105 | @task.short_circuit(multiple_outputs=False) + | ++++++++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference @@ -285,11 +237,8 @@ AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference | help: Add `multiple_outputs=True` | -109 | - - @task.virtualenv -110 + @task.virtualenv(multiple_outputs=True) -111 | def variant_virtualenv() -> dict: # AIR202 - | +110 | @task.virtualenv(multiple_outputs=True) + | +++++++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference @@ -302,11 +251,8 @@ AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference | help: Add `multiple_outputs=True` | -114 | - - @task.docker(image="python:3.11") -115 + @task.docker(multiple_outputs=True, image="python:3.11") -116 | def variant_docker() -> Mapping[str, int]: # AIR202 - | +115 | @task.docker(multiple_outputs=True, image="python:3.11") + | ++++++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference @@ -319,11 +265,8 @@ AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference | help: Add `multiple_outputs=False` | -119 | - - @task.kubernetes -120 + @task.kubernetes(multiple_outputs=False) -121 | def variant_kubernetes(): # AIR202 - | +120 | @task.kubernetes(multiple_outputs=False) + | ++++++++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference @@ -336,9 +279,6 @@ AIR202 [*] `@task`-decorated function relies on `multiple_outputs` inference | help: Add `multiple_outputs=True` | -124 | - - @task.short_circuit(trigger_rule="all_done") -125 + @task.short_circuit(multiple_outputs=True, trigger_rule="all_done") -126 | def variant_short_circuit_call() -> dict: # AIR202 - | +125 | @task.short_circuit(multiple_outputs=True, trigger_rule="all_done") + | ++++++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_args.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_args.py.snap index ec4d7fd6f73ab..75773fba7a533 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_args.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_args.py.snap @@ -13,10 +13,8 @@ AIR301 [*] `schedule_interval` is removed in Airflow 3.0 | help: Use `schedule` instead | -20 | - - DAG(dag_id="class_schedule_interval", schedule_interval="@hourly") +21 - DAG(dag_id="class_schedule_interval", schedule_interval="@hourly") 21 + DAG(dag_id="class_schedule_interval", schedule="@hourly") -22 | | AIR301 [*] `timetable` is removed in Airflow 3.0 @@ -31,10 +29,8 @@ AIR301 [*] `timetable` is removed in Airflow 3.0 | help: Use `schedule` instead | -22 | - - DAG(dag_id="class_timetable", timetable=NullTimetable()) +23 - DAG(dag_id="class_timetable", timetable=NullTimetable()) 23 + DAG(dag_id="class_timetable", schedule=NullTimetable()) -24 | | AIR301 [*] `concurrency` is removed in Airflow 3.0 @@ -49,10 +45,8 @@ AIR301 [*] `concurrency` is removed in Airflow 3.0 | help: Use `max_active_tasks` instead | -24 | - - DAG(dag_id="class_concurrency", concurrency=12) +25 - DAG(dag_id="class_concurrency", concurrency=12) 25 + DAG(dag_id="class_concurrency", max_active_tasks=12) -26 | | AIR301 [*] `fail_stop` is removed in Airflow 3.0 @@ -67,10 +61,8 @@ AIR301 [*] `fail_stop` is removed in Airflow 3.0 | help: Use `fail_fast` instead | -26 | - - DAG(dag_id="class_fail_stop", fail_stop=True) +27 - DAG(dag_id="class_fail_stop", fail_stop=True) 27 + DAG(dag_id="class_fail_stop", fail_fast=True) -28 | | AIR301 `default_view` is removed in Airflow 3.0 @@ -105,10 +97,8 @@ AIR301 [*] `schedule_interval` is removed in Airflow 3.0 | help: Use `schedule` instead | -41 | - - @dag(schedule_interval="0 * * * *") +42 - @dag(schedule_interval="0 * * * *") 42 + @dag(schedule="0 * * * *") -43 | def decorator_schedule_interval(): | AIR301 [*] `timetable` is removed in Airflow 3.0 @@ -121,10 +111,8 @@ AIR301 [*] `timetable` is removed in Airflow 3.0 | help: Use `schedule` instead | -46 | - - @dag(timetable=NullTimetable()) +47 - @dag(timetable=NullTimetable()) 47 + @dag(schedule=NullTimetable()) -48 | def decorator_timetable(): | AIR301 [*] `execution_date` is removed in Airflow 3.0 @@ -139,10 +127,8 @@ AIR301 [*] `execution_date` is removed in Airflow 3.0 | help: Use `logical_date` instead | -54 | trigger_dagrun_op = trigger_dagrun.TriggerDagRunOperator( - - task_id="trigger_dagrun_op1", trigger_dag_id="test", execution_date="2024-12-04" +55 - task_id="trigger_dagrun_op1", trigger_dag_id="test", execution_date="2024-12-04" 55 + task_id="trigger_dagrun_op1", trigger_dag_id="test", logical_date="2024-12-04" -56 | ) | AIR301 [*] `execution_date` is removed in Airflow 3.0 @@ -156,10 +142,8 @@ AIR301 [*] `execution_date` is removed in Airflow 3.0 | help: Use `logical_date` instead | -57 | trigger_dagrun_op2 = TriggerDagRunOperator( - - task_id="trigger_dagrun_op2", trigger_dag_id="test", execution_date="2024-12-04" +58 - task_id="trigger_dagrun_op2", trigger_dag_id="test", execution_date="2024-12-04" 58 + task_id="trigger_dagrun_op2", trigger_dag_id="test", logical_date="2024-12-04" -59 | ) | AIR301 [*] `use_task_execution_day` is removed in Airflow 3.0 @@ -173,10 +157,8 @@ AIR301 [*] `use_task_execution_day` is removed in Airflow 3.0 | help: Use `use_task_logical_date` instead | -61 | branch_dt_op = datetime.BranchDateTimeOperator( - - task_id="branch_dt_op", use_task_execution_day=True, task_concurrency=5 +62 - task_id="branch_dt_op", use_task_execution_day=True, task_concurrency=5 62 + task_id="branch_dt_op", use_task_logical_date=True, task_concurrency=5 -63 | ) | AIR301 [*] `task_concurrency` is removed in Airflow 3.0 @@ -190,10 +172,8 @@ AIR301 [*] `task_concurrency` is removed in Airflow 3.0 | help: Use `max_active_tis_per_dag` instead | -61 | branch_dt_op = datetime.BranchDateTimeOperator( - - task_id="branch_dt_op", use_task_execution_day=True, task_concurrency=5 +62 - task_id="branch_dt_op", use_task_execution_day=True, task_concurrency=5 62 + task_id="branch_dt_op", use_task_execution_day=True, max_active_tis_per_dag=5 -63 | ) | AIR301 [*] `use_task_execution_day` is removed in Airflow 3.0 @@ -208,10 +188,8 @@ AIR301 [*] `use_task_execution_day` is removed in Airflow 3.0 | help: Use `use_task_logical_date` instead | -65 | task_id="branch_dt_op2", - - use_task_execution_day=True, +66 - use_task_execution_day=True, 66 + use_task_logical_date=True, -67 | sla=timedelta(seconds=10), | AIR301 [*] `use_task_execution_day` is removed in Airflow 3.0 @@ -225,10 +203,8 @@ AIR301 [*] `use_task_execution_day` is removed in Airflow 3.0 | help: Use `use_task_logical_date` instead | -92 | week_day=1, - - use_task_execution_day=True, +93 - use_task_execution_day=True, 93 + use_task_logical_date=True, -94 | ) | AIR301 `filename_template` is removed in Airflow 3.0 @@ -293,10 +269,8 @@ AIR301 [*] `default_var` is removed in Airflow 3.0 | help: Use `default` instead | -113 | - - Variable.get("key", default_var="deprecated") +114 - Variable.get("key", default_var="deprecated") 114 + Variable.get("key", default="deprecated") -115 | Variable.get(key="key", default_var="deprecated") | AIR301 [*] `default_var` is removed in Airflow 3.0 @@ -310,10 +284,8 @@ AIR301 [*] `default_var` is removed in Airflow 3.0 | help: Use `default` instead | -114 | Variable.get("key", default_var="deprecated") - - Variable.get(key="key", default_var="deprecated") +115 - Variable.get(key="key", default_var="deprecated") 115 + Variable.get(key="key", default="deprecated") -116 | | AIR301 `provide_context` is removed in Airflow 3.0 @@ -478,10 +450,8 @@ AIR301 [*] `none_failed_or_skipped` is removed in Airflow 3.0 | help: Use `none_failed_min_one_success` instead | -273 | - - @task(trigger_rule="none_failed_or_skipped") +274 - @task(trigger_rule="none_failed_or_skipped") 274 + @task(trigger_rule="none_failed_min_one_success") -275 | def invalid_trigger_rule_task(): | AIR301 [*] `airflow.utils.trigger_rule.TriggerRule.NONE_FAILED_OR_SKIPPED` is removed in Airflow 3.0 @@ -496,10 +466,8 @@ AIR301 [*] `airflow.utils.trigger_rule.TriggerRule.NONE_FAILED_OR_SKIPPED` is re | help: Use `NONE_FAILED_MIN_ONE_SUCCESS` instead | -277 | - - @task(trigger_rule=TriggerRule.NONE_FAILED_OR_SKIPPED) +278 - @task(trigger_rule=TriggerRule.NONE_FAILED_OR_SKIPPED) 278 + @task(trigger_rule=TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS) -279 | def invalid_trigger_rule_task(): | AIR301 [*] `none_failed_or_skipped` is removed in Airflow 3.0 @@ -514,10 +482,8 @@ AIR301 [*] `none_failed_or_skipped` is removed in Airflow 3.0 | help: Use `none_failed_min_one_success` instead | -285 | - - PythonOperator(task_id="invalid_trigger_rule_task", python_callable=lambda: None, trigger_rule="none_failed_or_skipped") +286 - PythonOperator(task_id="invalid_trigger_rule_task", python_callable=lambda: None, trigger_rule="none_failed_or_skipped") 286 + PythonOperator(task_id="invalid_trigger_rule_task", python_callable=lambda: None, trigger_rule="none_failed_min_one_success") -287 | | AIR301 [*] `airflow.utils.trigger_rule.TriggerRule.NONE_FAILED_OR_SKIPPED` is removed in Airflow 3.0 @@ -532,10 +498,8 @@ AIR301 [*] `airflow.utils.trigger_rule.TriggerRule.NONE_FAILED_OR_SKIPPED` is re | help: Use `NONE_FAILED_MIN_ONE_SUCCESS` instead | -287 | - - PythonOperator(task_id="invalid_trigger_rule_task", python_callable=lambda: None, trigger_rule=TriggerRule.NONE_FAILED_OR_SKIPPED) +288 - PythonOperator(task_id="invalid_trigger_rule_task", python_callable=lambda: None, trigger_rule=TriggerRule.NONE_FAILED_OR_SKIPPED) 288 + PythonOperator(task_id="invalid_trigger_rule_task", python_callable=lambda: None, trigger_rule=TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS) -289 | | AIR301 [*] `none_failed_or_skipped` is removed in Airflow 3.0 @@ -550,10 +514,8 @@ AIR301 [*] `none_failed_or_skipped` is removed in Airflow 3.0 | help: Use `none_failed_min_one_success` instead | -294 | - - @task(trigger_rule="none_failed_or_skipped") +295 - @task(trigger_rule="none_failed_or_skipped") 295 + @task(trigger_rule="none_failed_min_one_success") -296 | def invalid_trigger_rule_task(): | AIR301 [*] `airflow.utils.trigger_rule.TriggerRule.NONE_FAILED_OR_SKIPPED` is removed in Airflow 3.0 @@ -568,10 +530,8 @@ AIR301 [*] `airflow.utils.trigger_rule.TriggerRule.NONE_FAILED_OR_SKIPPED` is re | help: Use `NONE_FAILED_MIN_ONE_SUCCESS` instead | -298 | - - @task(trigger_rule=TriggerRule.NONE_FAILED_OR_SKIPPED) +299 - @task(trigger_rule=TriggerRule.NONE_FAILED_OR_SKIPPED) 299 + @task(trigger_rule=TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS) -300 | def invalid_trigger_rule_task(): | AIR301 [*] `none_failed_or_skipped` is removed in Airflow 3.0 @@ -586,10 +546,8 @@ AIR301 [*] `none_failed_or_skipped` is removed in Airflow 3.0 | help: Use `none_failed_min_one_success` instead | -306 | - - PythonOperator(task_id="invalid_trigger_rule_task", python_callable=lambda: None, trigger_rule="none_failed_or_skipped") +307 - PythonOperator(task_id="invalid_trigger_rule_task", python_callable=lambda: None, trigger_rule="none_failed_or_skipped") 307 + PythonOperator(task_id="invalid_trigger_rule_task", python_callable=lambda: None, trigger_rule="none_failed_min_one_success") -308 | | AIR301 [*] `airflow.utils.trigger_rule.TriggerRule.NONE_FAILED_OR_SKIPPED` is removed in Airflow 3.0 @@ -604,10 +562,8 @@ AIR301 [*] `airflow.utils.trigger_rule.TriggerRule.NONE_FAILED_OR_SKIPPED` is re | help: Use `NONE_FAILED_MIN_ONE_SUCCESS` instead | -308 | - - PythonOperator(task_id="invalid_trigger_rule_task", python_callable=lambda: None, trigger_rule=TriggerRule.NONE_FAILED_OR_SKIPPED) +309 - PythonOperator(task_id="invalid_trigger_rule_task", python_callable=lambda: None, trigger_rule=TriggerRule.NONE_FAILED_OR_SKIPPED) 309 + PythonOperator(task_id="invalid_trigger_rule_task", python_callable=lambda: None, trigger_rule=TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS) -310 | | AIR301 [*] `none_failed_or_skipped` is removed in Airflow 3.0 @@ -621,10 +577,8 @@ AIR301 [*] `none_failed_or_skipped` is removed in Airflow 3.0 | help: Use `none_failed_min_one_success` instead | -319 | return_last=False, - - trigger_rule="none_failed_or_skipped", +320 - trigger_rule="none_failed_or_skipped", 320 + trigger_rule="none_failed_min_one_success", -321 | ) | AIR301 [*] `airflow.utils.trigger_rule.TriggerRule.NONE_FAILED_OR_SKIPPED` is removed in Airflow 3.0 @@ -638,10 +592,8 @@ AIR301 [*] `airflow.utils.trigger_rule.TriggerRule.NONE_FAILED_OR_SKIPPED` is re | help: Use `NONE_FAILED_MIN_ONE_SUCCESS` instead | -327 | return_last=False, - - trigger_rule=TriggerRule.NONE_FAILED_OR_SKIPPED, +328 - trigger_rule=TriggerRule.NONE_FAILED_OR_SKIPPED, 328 + trigger_rule=TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS, -329 | ) | AIR301 [*] `none_failed_or_skipped` is removed in Airflow 3.0 @@ -655,10 +607,8 @@ AIR301 [*] `none_failed_or_skipped` is removed in Airflow 3.0 | help: Use `none_failed_min_one_success` instead | -338 | replace=True, - - trigger_rule="none_failed_or_skipped", +339 - trigger_rule="none_failed_or_skipped", 339 + trigger_rule="none_failed_min_one_success", -340 | ) | AIR301 [*] `airflow.utils.trigger_rule.TriggerRule.NONE_FAILED_OR_SKIPPED` is removed in Airflow 3.0 @@ -672,8 +622,6 @@ AIR301 [*] `airflow.utils.trigger_rule.TriggerRule.NONE_FAILED_OR_SKIPPED` is re | help: Use `NONE_FAILED_MIN_ONE_SUCCESS` instead | -347 | replace=True, - - trigger_rule=TriggerRule.NONE_FAILED_OR_SKIPPED, +348 - trigger_rule=TriggerRule.NONE_FAILED_OR_SKIPPED, 348 + trigger_rule=TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS, -349 | ) | diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_class_attribute.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_class_attribute.py.snap index 512903692da77..172702892364f 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_class_attribute.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_class_attribute.py.snap @@ -12,10 +12,8 @@ AIR301 [*] `iter_datasets` is removed in Airflow 3.0 | help: Use `iter_assets` instead | -26 | dataset_from_root = DatasetFromRoot() - - dataset_from_root.iter_datasets() +27 - dataset_from_root.iter_datasets() 27 + dataset_from_root.iter_assets() -28 | dataset_from_root.iter_dataset_aliases() | AIR301 [*] `iter_dataset_aliases` is removed in Airflow 3.0 @@ -30,10 +28,8 @@ AIR301 [*] `iter_dataset_aliases` is removed in Airflow 3.0 | help: Use `iter_asset_aliases` instead | -27 | dataset_from_root.iter_datasets() - - dataset_from_root.iter_dataset_aliases() +28 - dataset_from_root.iter_dataset_aliases() 28 + dataset_from_root.iter_asset_aliases() -29 | | AIR301 [*] `iter_datasets` is removed in Airflow 3.0 @@ -47,10 +43,8 @@ AIR301 [*] `iter_datasets` is removed in Airflow 3.0 | help: Use `iter_assets` instead | -31 | dataset_to_test_method_call = Dataset() - - dataset_to_test_method_call.iter_datasets() +32 - dataset_to_test_method_call.iter_datasets() 32 + dataset_to_test_method_call.iter_assets() -33 | dataset_to_test_method_call.iter_dataset_aliases() | AIR301 [*] `iter_dataset_aliases` is removed in Airflow 3.0 @@ -65,10 +59,8 @@ AIR301 [*] `iter_dataset_aliases` is removed in Airflow 3.0 | help: Use `iter_asset_aliases` instead | -32 | dataset_to_test_method_call.iter_datasets() - - dataset_to_test_method_call.iter_dataset_aliases() +33 - dataset_to_test_method_call.iter_dataset_aliases() 33 + dataset_to_test_method_call.iter_asset_aliases() -34 | | AIR301 [*] `iter_datasets` is removed in Airflow 3.0 @@ -81,10 +73,8 @@ AIR301 [*] `iter_datasets` is removed in Airflow 3.0 | help: Use `iter_assets` instead | -35 | alias_to_test_method_call = DatasetAlias() - - alias_to_test_method_call.iter_datasets() +36 - alias_to_test_method_call.iter_datasets() 36 + alias_to_test_method_call.iter_assets() -37 | alias_to_test_method_call.iter_dataset_aliases() | AIR301 [*] `iter_dataset_aliases` is removed in Airflow 3.0 @@ -99,10 +89,8 @@ AIR301 [*] `iter_dataset_aliases` is removed in Airflow 3.0 | help: Use `iter_asset_aliases` instead | -36 | alias_to_test_method_call.iter_datasets() - - alias_to_test_method_call.iter_dataset_aliases() +37 - alias_to_test_method_call.iter_dataset_aliases() 37 + alias_to_test_method_call.iter_asset_aliases() -38 | | AIR301 [*] `iter_datasets` is removed in Airflow 3.0 @@ -115,10 +103,8 @@ AIR301 [*] `iter_datasets` is removed in Airflow 3.0 | help: Use `iter_assets` instead | -39 | any_to_test_method_call = DatasetAny() - - any_to_test_method_call.iter_datasets() +40 - any_to_test_method_call.iter_datasets() 40 + any_to_test_method_call.iter_assets() -41 | any_to_test_method_call.iter_dataset_aliases() | AIR301 [*] `iter_dataset_aliases` is removed in Airflow 3.0 @@ -133,10 +119,8 @@ AIR301 [*] `iter_dataset_aliases` is removed in Airflow 3.0 | help: Use `iter_asset_aliases` instead | -40 | any_to_test_method_call.iter_datasets() - - any_to_test_method_call.iter_dataset_aliases() +41 - any_to_test_method_call.iter_dataset_aliases() 41 + any_to_test_method_call.iter_asset_aliases() -42 | | AIR301 [*] `airflow.datasets.manager.DatasetManager` is removed in Airflow 3.0 @@ -150,14 +134,12 @@ AIR301 [*] `airflow.datasets.manager.DatasetManager` is removed in Airflow 3.0 | help: Use `AssetManager` from `airflow.assets.manager` instead. | -22 | from airflow.secrets.local_filesystem import LocalFilesystemBackend 23 + from airflow.assets.manager import AssetManager -24 | --------------------------------------------------------------------------------- +24 + +25 | + … 44 | # airflow.datasets.manager - - dm = DatasetManager() -45 + dm = AssetManager() -46 | dm.register_dataset_change() +45 ~ dm = AssetManager() | AIR301 [*] `register_dataset_change` is removed in Airflow 3.0 @@ -172,10 +154,8 @@ AIR301 [*] `register_dataset_change` is removed in Airflow 3.0 | help: Use `register_asset_change` instead | -44 | dm = DatasetManager() - - dm.register_dataset_change() +45 - dm.register_dataset_change() 45 + dm.register_asset_change() -46 | dm.create_datasets() | AIR301 [*] `create_datasets` is removed in Airflow 3.0 @@ -190,10 +170,8 @@ AIR301 [*] `create_datasets` is removed in Airflow 3.0 | help: Use `create_assets` instead | -45 | dm.register_dataset_change() - - dm.create_datasets() +46 - dm.create_datasets() 46 + dm.create_assets() -47 | dm.notify_dataset_created() | AIR301 [*] `notify_dataset_created` is removed in Airflow 3.0 @@ -208,10 +186,8 @@ AIR301 [*] `notify_dataset_created` is removed in Airflow 3.0 | help: Use `notify_asset_created` instead | -46 | dm.create_datasets() - - dm.notify_dataset_created() +47 - dm.notify_dataset_created() 47 + dm.notify_asset_created() -48 | dm.notify_dataset_changed() | AIR301 [*] `notify_dataset_changed` is removed in Airflow 3.0 @@ -225,10 +201,8 @@ AIR301 [*] `notify_dataset_changed` is removed in Airflow 3.0 | help: Use `notify_asset_changed` instead | -47 | dm.notify_dataset_created() - - dm.notify_dataset_changed() +48 - dm.notify_dataset_changed() 48 + dm.notify_asset_changed() -49 | dm.notify_dataset_alias_created() | AIR301 [*] `notify_dataset_alias_created` is removed in Airflow 3.0 @@ -243,10 +217,8 @@ AIR301 [*] `notify_dataset_alias_created` is removed in Airflow 3.0 | help: Use `notify_asset_alias_created` instead | -48 | dm.notify_dataset_changed() - - dm.notify_dataset_alias_created() +49 - dm.notify_dataset_alias_created() 49 + dm.notify_asset_alias_created() -50 | | AIR301 [*] `airflow.lineage.hook.DatasetLineageInfo` is removed in Airflow 3.0 @@ -259,15 +231,11 @@ AIR301 [*] `airflow.lineage.hook.DatasetLineageInfo` is removed in Airflow 3.0 | help: Use `AssetLineageInfo` from `airflow.lineage.hook` instead. | -11 | from airflow.datasets.manager import DatasetManager - - from airflow.lineage.hook import DatasetLineageInfo, HookLineageCollector -12 + from airflow.lineage.hook import DatasetLineageInfo, HookLineageCollector, AssetLineageInfo +12 ~ from airflow.lineage.hook import DatasetLineageInfo, HookLineageCollector, AssetLineageInfo 13 | from airflow.models.dag import DAG --------------------------------------------------------------------------------- + … 51 | # airflow.lineage.hook - - dl_info = DatasetLineageInfo() -52 + dl_info = AssetLineageInfo() -53 | dl_info.dataset +52 ~ dl_info = AssetLineageInfo() | AIR301 [*] `dataset` is removed in Airflow 3.0 @@ -282,10 +250,8 @@ AIR301 [*] `dataset` is removed in Airflow 3.0 | help: Use `asset` instead | -52 | dl_info = DatasetLineageInfo() - - dl_info.dataset +53 - dl_info.dataset 53 + dl_info.asset -54 | | AIR301 [*] `create_dataset` is removed in Airflow 3.0 @@ -299,10 +265,8 @@ AIR301 [*] `create_dataset` is removed in Airflow 3.0 | help: Use `create_asset` instead | -55 | hlc = HookLineageCollector() - - hlc.create_dataset() +56 - hlc.create_dataset() 56 + hlc.create_asset() -57 | hlc.add_input_dataset() | AIR301 [*] `add_input_dataset` is removed in Airflow 3.0 @@ -317,10 +281,8 @@ AIR301 [*] `add_input_dataset` is removed in Airflow 3.0 | help: Use `add_input_asset` instead | -56 | hlc.create_dataset() - - hlc.add_input_dataset() +57 - hlc.add_input_dataset() 57 + hlc.add_input_asset() -58 | hlc.add_output_dataset() | AIR301 [*] `add_output_dataset` is removed in Airflow 3.0 @@ -334,10 +296,8 @@ AIR301 [*] `add_output_dataset` is removed in Airflow 3.0 | help: Use `add_output_asset` instead | -57 | hlc.add_input_dataset() - - hlc.add_output_dataset() +58 - hlc.add_output_dataset() 58 + hlc.add_output_asset() -59 | hlc.collected_datasets() | AIR301 [*] `collected_datasets` is removed in Airflow 3.0 @@ -352,10 +312,8 @@ AIR301 [*] `collected_datasets` is removed in Airflow 3.0 | help: Use `collected_assets` instead | -58 | hlc.add_output_dataset() - - hlc.collected_datasets() +59 - hlc.collected_datasets() 59 + hlc.collected_assets() -60 | | AIR301 `create_dagrun` is removed in Airflow 3.0 @@ -381,10 +339,8 @@ AIR301 [*] `is_authorized_dataset` is removed in Airflow 3.0 | help: Use `is_authorized_asset` instead | -66 | aam = AwsAuthManager() - - aam.is_authorized_dataset() +67 - aam.is_authorized_dataset() 67 + aam.is_authorized_asset() -68 | | AIR301 [*] `get_conn_uri` is removed in Airflow 3.0 @@ -398,10 +354,8 @@ AIR301 [*] `get_conn_uri` is removed in Airflow 3.0 | help: Use `get_conn_value` instead | -78 | csm_backend = CloudSecretManagerBackend() - - csm_backend.get_conn_uri() +79 - csm_backend.get_conn_uri() 79 + csm_backend.get_conn_value() -80 | csm_backend.get_connections() | AIR301 [*] `get_connections` is removed in Airflow 3.0 @@ -416,10 +370,8 @@ AIR301 [*] `get_connections` is removed in Airflow 3.0 | help: Use `get_connection` instead | -79 | csm_backend.get_conn_uri() - - csm_backend.get_connections() +80 - csm_backend.get_connections() 80 + csm_backend.get_connection() -81 | | AIR301 [*] `get_conn_uri` is removed in Airflow 3.0 @@ -433,10 +385,8 @@ AIR301 [*] `get_conn_uri` is removed in Airflow 3.0 | help: Use `get_conn_value` instead | -83 | vault_backend = VaultBackend() - - vault_backend.get_conn_uri() +84 - vault_backend.get_conn_uri() 84 + vault_backend.get_conn_value() -85 | vault_backend.get_connections() | AIR301 [*] `get_connections` is removed in Airflow 3.0 @@ -451,10 +401,8 @@ AIR301 [*] `get_connections` is removed in Airflow 3.0 | help: Use `get_connection` instead | -84 | vault_backend.get_conn_uri() - - vault_backend.get_connections() +85 - vault_backend.get_connections() 85 + vault_backend.get_connection() -86 | | AIR301 [*] `initialize_providers_dataset_uri_resources` is removed in Airflow 3.0 @@ -469,10 +417,8 @@ AIR301 [*] `initialize_providers_dataset_uri_resources` is removed in Airflow 3. | help: Use `initialize_providers_asset_uri_resources` instead | -91 | pm = ProvidersManager() - - pm.initialize_providers_dataset_uri_resources() +92 - pm.initialize_providers_dataset_uri_resources() 92 + pm.initialize_providers_asset_uri_resources() -93 | pm.dataset_factories | AIR301 [*] `dataset_factories` is removed in Airflow 3.0 @@ -487,10 +433,8 @@ AIR301 [*] `dataset_factories` is removed in Airflow 3.0 | help: Use `asset_factories` instead | -92 | pm.initialize_providers_dataset_uri_resources() - - pm.dataset_factories +93 - pm.dataset_factories 93 + pm.asset_factories -94 | pm.dataset_uri_handlers | AIR301 [*] `dataset_uri_handlers` is removed in Airflow 3.0 @@ -504,10 +448,8 @@ AIR301 [*] `dataset_uri_handlers` is removed in Airflow 3.0 | help: Use `asset_uri_handlers` instead | -93 | pm.dataset_factories - - pm.dataset_uri_handlers +94 - pm.dataset_uri_handlers 94 + pm.asset_uri_handlers -95 | pm.dataset_to_openlineage_converters | AIR301 [*] `dataset_to_openlineage_converters` is removed in Airflow 3.0 @@ -522,10 +464,8 @@ AIR301 [*] `dataset_to_openlineage_converters` is removed in Airflow 3.0 | help: Use `asset_to_openlineage_converters` instead | -94 | pm.dataset_uri_handlers - - pm.dataset_to_openlineage_converters +95 - pm.dataset_to_openlineage_converters 95 + pm.asset_to_openlineage_converters -96 | | AIR301 [*] `get_conn_uri` is removed in Airflow 3.0 @@ -538,12 +478,10 @@ AIR301 [*] `get_conn_uri` is removed in Airflow 3.0 100 | base_secret_backend.get_connections() | help: Use `get_conn_value` instead - | -98 | base_secret_backend = BaseSecretsBackend() - - base_secret_backend.get_conn_uri() -99 + base_secret_backend.get_conn_value() -100 | base_secret_backend.get_connections() - | + | +99 - base_secret_backend.get_conn_uri() +99 + base_secret_backend.get_conn_value() + | AIR301 [*] `get_connections` is removed in Airflow 3.0 --> AIR301_class_attribute.py:100:21 @@ -557,10 +495,8 @@ AIR301 [*] `get_connections` is removed in Airflow 3.0 | help: Use `get_connection` instead | -99 | base_secret_backend.get_conn_uri() - - base_secret_backend.get_connections() +100 - base_secret_backend.get_connections() 100 + base_secret_backend.get_connection() -101 | | AIR301 [*] `get_connections` is removed in Airflow 3.0 @@ -575,10 +511,8 @@ AIR301 [*] `get_connections` is removed in Airflow 3.0 | help: Use `get_connection` instead | -103 | lfb = LocalFilesystemBackend() - - lfb.get_connections() +104 - lfb.get_connections() 104 + lfb.get_connection() -105 | | AIR301 `create_dagrun` is removed in Airflow 3.0 diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_context.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_context.py.snap index ade9431e79c74..f7dd97ea3f02a 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_context.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_context.py.snap @@ -177,10 +177,8 @@ AIR301 [*] `triggering_dataset_events` is removed in Airflow 3.0 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use `triggering_asset_events` instead | -50 | yesterday_ds_nodash = context["yesterday_ds_nodash"] - - events = context["triggering_dataset_events"] +51 - events = context["triggering_dataset_events"] 51 + events = context["triggering_asset_events"] -52 | | AIR301 `execution_date` is removed in Airflow 3.0 @@ -312,10 +310,8 @@ AIR301 [*] `triggering_dataset_events` is removed in Airflow 3.0 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use `triggering_asset_events` instead | -67 | yesterday_ds_nodash = context["yesterday_ds_nodash"] - - events = context["triggering_dataset_events"] +68 - events = context["triggering_dataset_events"] 68 + events = context["triggering_asset_events"] -69 | | AIR301 `tomorrow_ds` is removed in Airflow 3.0 @@ -369,10 +365,8 @@ AIR301 [*] `schedule_interval` is removed in Airflow 3.0 | help: Use `schedule` instead | -112 | dag_id="example_dag", - - schedule_interval="@daily", +113 - schedule_interval="@daily", 113 + schedule="@daily", -114 | start_date=datetime(2023, 1, 1), | AIR301 `next_ds` is removed in Airflow 3.0 diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_decorator.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_decorator.py.snap index b5dfadb689db7..533f229e4e5b7 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_decorator.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_decorator.py.snap @@ -12,7 +12,5 @@ AIR301 [*] `apply_defaults` is removed in Airflow 3.0 | help: `apply_defaults` is now unconditionally done and can be safely removed. | -6 | class DecoratedOperator(BaseOperator): - - @apply_defaults -7 | def __init__(self, message, **kwargs): +7 - @apply_defaults | diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_names_fix.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_names_fix.py.snap index 213b8d78301c4..82c2ad82a2e09 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_names_fix.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_names_fix.py.snap @@ -13,12 +13,9 @@ AIR301 [*] `airflow.api_connexion.security.requires_access_dataset` is removed i | help: Use `requires_access_asset` from `airflow.api_fastapi.core_api.security` instead. | -15 | from airflow.security.permissions import RESOURCE_DATASET 16 + from airflow.api_fastapi.core_api.security import requires_access_asset -17 | - - requires_access_dataset() -18 + requires_access_asset() -19 | +17 + +18 ~ requires_access_asset() | AIR301 [*] `airflow.auth.managers.models.resource_details.DatasetDetails` is removed in Airflow 3.0 @@ -33,14 +30,11 @@ AIR301 [*] `airflow.auth.managers.models.resource_details.DatasetDetails` is rem | help: Use `AssetDetails` from `airflow.api_fastapi.auth.managers.models.resource_details` instead. | -15 | from airflow.security.permissions import RESOURCE_DATASET 16 + from airflow.api_fastapi.auth.managers.models.resource_details import AssetDetails -17 | +17 + 18 | requires_access_dataset() 19 | - - DatasetDetails() -20 + AssetDetails() -21 | +20 ~ AssetDetails() | AIR301 [*] `airflow.datasets.manager.DatasetManager` is removed in Airflow 3.0 @@ -55,14 +49,12 @@ AIR301 [*] `airflow.datasets.manager.DatasetManager` is removed in Airflow 3.0 | help: Use `AssetManager` from `airflow.assets.manager` instead. | -15 | from airflow.security.permissions import RESOURCE_DATASET 16 + from airflow.assets.manager import AssetManager -17 | --------------------------------------------------------------------------------- +17 + +18 | requires_access_dataset() + … 21 | - - DatasetManager() -22 + AssetManager() -23 | dataset_manager() +22 ~ AssetManager() | AIR301 [*] `airflow.datasets.manager.dataset_manager` is removed in Airflow 3.0 @@ -75,14 +67,12 @@ AIR301 [*] `airflow.datasets.manager.dataset_manager` is removed in Airflow 3.0 | help: Use `asset_manager` from `airflow.assets.manager` instead. | -15 | from airflow.security.permissions import RESOURCE_DATASET 16 + from airflow.assets.manager import asset_manager -17 | --------------------------------------------------------------------------------- +17 + +18 | requires_access_dataset() + … 22 | DatasetManager() - - dataset_manager() -23 + asset_manager() -24 | resolve_dataset_manager() +23 ~ asset_manager() | AIR301 [*] `airflow.datasets.manager.resolve_dataset_manager` is removed in Airflow 3.0 @@ -97,14 +87,12 @@ AIR301 [*] `airflow.datasets.manager.resolve_dataset_manager` is removed in Airf | help: Use `resolve_asset_manager` from `airflow.assets.manager` instead. | -15 | from airflow.security.permissions import RESOURCE_DATASET 16 + from airflow.assets.manager import resolve_asset_manager -17 | --------------------------------------------------------------------------------- +17 + +18 | requires_access_dataset() + … 23 | dataset_manager() - - resolve_dataset_manager() -24 + resolve_asset_manager() -25 | +24 ~ resolve_asset_manager() | AIR301 [*] `airflow.lineage.hook.DatasetLineageInfo` is removed in Airflow 3.0 @@ -119,15 +107,11 @@ AIR301 [*] `airflow.lineage.hook.DatasetLineageInfo` is removed in Airflow 3.0 | help: Use `AssetLineageInfo` from `airflow.lineage.hook` instead. | -11 | ) - - from airflow.lineage.hook import DatasetLineageInfo -12 + from airflow.lineage.hook import DatasetLineageInfo, AssetLineageInfo +12 ~ from airflow.lineage.hook import DatasetLineageInfo, AssetLineageInfo 13 | from airflow.metrics.validators import AllowListValidator, BlockListValidator --------------------------------------------------------------------------------- + … 24 | - - DatasetLineageInfo() -25 + AssetLineageInfo() -26 | +25 ~ AssetLineageInfo() | AIR301 [*] `airflow.metrics.validators.AllowListValidator` is removed in Airflow 3.0 @@ -141,15 +125,11 @@ AIR301 [*] `airflow.metrics.validators.AllowListValidator` is removed in Airflow | help: Use `PatternAllowListValidator` from `airflow.metrics.validators` instead. | -12 | from airflow.lineage.hook import DatasetLineageInfo - - from airflow.metrics.validators import AllowListValidator, BlockListValidator -13 + from airflow.metrics.validators import AllowListValidator, BlockListValidator, PatternAllowListValidator +13 ~ from airflow.metrics.validators import AllowListValidator, BlockListValidator, PatternAllowListValidator 14 | from airflow.secrets.local_filesystem import load_connections --------------------------------------------------------------------------------- + … 26 | - - AllowListValidator() -27 + PatternAllowListValidator() -28 | BlockListValidator() +27 ~ PatternAllowListValidator() | AIR301 [*] `airflow.metrics.validators.BlockListValidator` is removed in Airflow 3.0 @@ -163,15 +143,11 @@ AIR301 [*] `airflow.metrics.validators.BlockListValidator` is removed in Airflow | help: Use `PatternBlockListValidator` from `airflow.metrics.validators` instead. | -12 | from airflow.lineage.hook import DatasetLineageInfo - - from airflow.metrics.validators import AllowListValidator, BlockListValidator -13 + from airflow.metrics.validators import AllowListValidator, BlockListValidator, PatternBlockListValidator +13 ~ from airflow.metrics.validators import AllowListValidator, BlockListValidator, PatternBlockListValidator 14 | from airflow.secrets.local_filesystem import load_connections --------------------------------------------------------------------------------- + … 27 | AllowListValidator() - - BlockListValidator() -28 + PatternBlockListValidator() -29 | +28 ~ PatternBlockListValidator() | AIR301 [*] `airflow.secrets.local_filesystem.load_connections` is removed in Airflow 3.0 @@ -186,15 +162,11 @@ AIR301 [*] `airflow.secrets.local_filesystem.load_connections` is removed in Air | help: Use `load_connections_dict` from `airflow.secrets.local_filesystem` instead. | -13 | from airflow.metrics.validators import AllowListValidator, BlockListValidator - - from airflow.secrets.local_filesystem import load_connections -14 + from airflow.secrets.local_filesystem import load_connections, load_connections_dict +14 ~ from airflow.secrets.local_filesystem import load_connections, load_connections_dict 15 | from airflow.security.permissions import RESOURCE_DATASET --------------------------------------------------------------------------------- + … 29 | - - load_connections() -30 + load_connections_dict() -31 | +30 ~ load_connections_dict() | AIR301 [*] `airflow.security.permissions.RESOURCE_DATASET` is removed in Airflow 3.0 @@ -206,15 +178,11 @@ AIR301 [*] `airflow.security.permissions.RESOURCE_DATASET` is removed in Airflow | ^^^^^^^^^^^^^^^^ help: Use `RESOURCE_ASSET` from `airflow.security.permissions` instead. | -14 | from airflow.secrets.local_filesystem import load_connections - - from airflow.security.permissions import RESOURCE_DATASET -15 + from airflow.security.permissions import RESOURCE_DATASET, RESOURCE_ASSET +15 ~ from airflow.security.permissions import RESOURCE_DATASET, RESOURCE_ASSET 16 | --------------------------------------------------------------------------------- + … 31 | - - RESOURCE_DATASET 32 + RESOURCE_ASSET -33 | | AIR301 [*] `airflow.listeners.spec.dataset.on_dataset_created` is removed in Airflow 3.0 @@ -228,12 +196,9 @@ AIR301 [*] `airflow.listeners.spec.dataset.on_dataset_created` is removed in Air | help: Use `on_asset_created` from `airflow.listeners.spec.asset` instead. | -38 | ) 39 + from airflow.listeners.spec.asset import on_asset_created -40 | - - on_dataset_created() -41 + on_asset_created() -42 | on_dataset_changed() +40 + +41 ~ on_asset_created() | AIR301 [*] `airflow.listeners.spec.dataset.on_dataset_changed` is removed in Airflow 3.0 @@ -244,13 +209,10 @@ AIR301 [*] `airflow.listeners.spec.dataset.on_dataset_changed` is removed in Air | ^^^^^^^^^^^^^^^^^^ help: Use `on_asset_changed` from `airflow.listeners.spec.asset` instead. | -38 | ) 39 + from airflow.listeners.spec.asset import on_asset_changed -40 | +40 + 41 | on_dataset_created() - - on_dataset_changed() -42 + on_asset_changed() -43 | +42 ~ on_asset_changed() | AIR301 [*] `airflow.operators.python.get_current_context` is removed in Airflow 3.0 @@ -265,10 +227,8 @@ AIR301 [*] `airflow.operators.python.get_current_context` is removed in Airflow | help: `get_current_context` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -44 | # airflow.operators.python - - from airflow.operators.python import get_current_context -45 + from airflow.sdk import get_current_context -46 | +45 + +46 + from airflow.sdk import get_current_context | note: This is an unsafe fix and may change runtime behavior @@ -284,10 +244,8 @@ AIR301 [*] `airflow.providers.mysql.datasets.mysql.sanitize_uri` is removed in A | help: Use `sanitize_uri` from `airflow.providers.mysql.assets.mysql` instead. | -49 | # airflow.providers.mysql - - from airflow.providers.mysql.datasets.mysql import sanitize_uri -50 + from airflow.providers.mysql.assets.mysql import sanitize_uri -51 | +50 + +51 + from airflow.providers.mysql.assets.mysql import sanitize_uri | note: This is an unsafe fix and may change runtime behavior @@ -303,10 +261,8 @@ AIR301 [*] `airflow.providers.postgres.datasets.postgres.sanitize_uri` is remove | help: Use `sanitize_uri` from `airflow.providers.postgres.assets.postgres` instead. | -54 | # airflow.providers.postgres - - from airflow.providers.postgres.datasets.postgres import sanitize_uri -55 + from airflow.providers.postgres.assets.postgres import sanitize_uri -56 | +55 + +56 + from airflow.providers.postgres.assets.postgres import sanitize_uri | note: This is an unsafe fix and may change runtime behavior @@ -322,10 +278,8 @@ AIR301 [*] `airflow.providers.trino.datasets.trino.sanitize_uri` is removed in A | help: Use `sanitize_uri` from `airflow.providers.trino.assets.trino` instead. | -59 | # airflow.providers.trino - - from airflow.providers.trino.datasets.trino import sanitize_uri -60 + from airflow.providers.trino.assets.trino import sanitize_uri -61 | +60 + +61 + from airflow.providers.trino.assets.trino import sanitize_uri | note: This is an unsafe fix and may change runtime behavior @@ -341,10 +295,8 @@ AIR301 [*] `airflow.notifications.basenotifier.BaseNotifier` is removed in Airfl | help: `BaseNotifier` has been moved to `airflow.sdk.bases.notifier` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -64 | # airflow.notifications.basenotifier - - from airflow.notifications.basenotifier import BaseNotifier -65 + from airflow.sdk.bases.notifier import BaseNotifier -66 | +65 + +66 + from airflow.sdk.bases.notifier import BaseNotifier | note: This is an unsafe fix and may change runtime behavior @@ -357,10 +309,8 @@ AIR301 [*] `airflow.auth.managers.base_auth_manager.BaseAuthManager` is removed | ^^^^^^^^^^^^^^^ help: Use `BaseAuthManager` from `airflow.api_fastapi.auth.managers.base_auth_manager` instead. | -69 | # airflow.auth.manager - - from airflow.auth.managers.base_auth_manager import BaseAuthManager -70 + from airflow.api_fastapi.auth.managers.base_auth_manager import BaseAuthManager -71 | +70 + +71 + from airflow.api_fastapi.auth.managers.base_auth_manager import BaseAuthManager | note: This is an unsafe fix and may change runtime behavior @@ -374,14 +324,14 @@ AIR301 [*] `airflow.configuration.get` is removed in Airflow 3.0 | help: Use `conf.get` from `airflow.configuration` instead. | +75 | from airflow.configuration import ( + … 83 | set, 84 + conf, 85 | ) 86 | 87 | # airflow.configuration - - get, getboolean, getfloat, getint, has_option, remove_option, as_dict, set -88 + conf, getboolean, getfloat, getint, has_option, remove_option, as_dict, set -89 | from airflow.hooks.base_hook import BaseHook +88 ~ conf, getboolean, getfloat, getint, has_option, remove_option, as_dict, set | AIR301 [*] `airflow.configuration.getboolean` is removed in Airflow 3.0 @@ -394,14 +344,14 @@ AIR301 [*] `airflow.configuration.getboolean` is removed in Airflow 3.0 | help: Use `conf.getboolean` from `airflow.configuration` instead. | +75 | from airflow.configuration import ( + … 83 | set, 84 + conf, 85 | ) 86 | 87 | # airflow.configuration - - get, getboolean, getfloat, getint, has_option, remove_option, as_dict, set -88 + get, conf, getfloat, getint, has_option, remove_option, as_dict, set -89 | from airflow.hooks.base_hook import BaseHook +88 ~ get, conf, getfloat, getint, has_option, remove_option, as_dict, set | AIR301 [*] `airflow.configuration.getfloat` is removed in Airflow 3.0 @@ -414,14 +364,14 @@ AIR301 [*] `airflow.configuration.getfloat` is removed in Airflow 3.0 | help: Use `conf.getfloat` from `airflow.configuration` instead. | +75 | from airflow.configuration import ( + … 83 | set, 84 + conf, 85 | ) 86 | 87 | # airflow.configuration - - get, getboolean, getfloat, getint, has_option, remove_option, as_dict, set -88 + get, getboolean, conf, getint, has_option, remove_option, as_dict, set -89 | from airflow.hooks.base_hook import BaseHook +88 ~ get, getboolean, conf, getint, has_option, remove_option, as_dict, set | AIR301 [*] `airflow.configuration.getint` is removed in Airflow 3.0 @@ -434,14 +384,14 @@ AIR301 [*] `airflow.configuration.getint` is removed in Airflow 3.0 | help: Use `conf.getint` from `airflow.configuration` instead. | +75 | from airflow.configuration import ( + … 83 | set, 84 + conf, 85 | ) 86 | 87 | # airflow.configuration - - get, getboolean, getfloat, getint, has_option, remove_option, as_dict, set -88 + get, getboolean, getfloat, conf, has_option, remove_option, as_dict, set -89 | from airflow.hooks.base_hook import BaseHook +88 ~ get, getboolean, getfloat, conf, has_option, remove_option, as_dict, set | AIR301 [*] `airflow.configuration.has_option` is removed in Airflow 3.0 @@ -454,14 +404,14 @@ AIR301 [*] `airflow.configuration.has_option` is removed in Airflow 3.0 | help: Use `conf.has_option` from `airflow.configuration` instead. | +75 | from airflow.configuration import ( + … 83 | set, 84 + conf, 85 | ) 86 | 87 | # airflow.configuration - - get, getboolean, getfloat, getint, has_option, remove_option, as_dict, set -88 + get, getboolean, getfloat, getint, conf, remove_option, as_dict, set -89 | from airflow.hooks.base_hook import BaseHook +88 ~ get, getboolean, getfloat, getint, conf, remove_option, as_dict, set | AIR301 [*] `airflow.configuration.remove_option` is removed in Airflow 3.0 @@ -474,14 +424,14 @@ AIR301 [*] `airflow.configuration.remove_option` is removed in Airflow 3.0 | help: Use `conf.remove_option` from `airflow.configuration` instead. | +75 | from airflow.configuration import ( + … 83 | set, 84 + conf, 85 | ) 86 | 87 | # airflow.configuration - - get, getboolean, getfloat, getint, has_option, remove_option, as_dict, set -88 + get, getboolean, getfloat, getint, has_option, conf, as_dict, set -89 | from airflow.hooks.base_hook import BaseHook +88 ~ get, getboolean, getfloat, getint, has_option, conf, as_dict, set | AIR301 [*] `airflow.configuration.as_dict` is removed in Airflow 3.0 @@ -494,14 +444,14 @@ AIR301 [*] `airflow.configuration.as_dict` is removed in Airflow 3.0 | help: Use `conf.as_dict` from `airflow.configuration` instead. | +75 | from airflow.configuration import ( + … 83 | set, 84 + conf, 85 | ) 86 | 87 | # airflow.configuration - - get, getboolean, getfloat, getint, has_option, remove_option, as_dict, set -88 + get, getboolean, getfloat, getint, has_option, remove_option, conf, set -89 | from airflow.hooks.base_hook import BaseHook +88 ~ get, getboolean, getfloat, getint, has_option, remove_option, conf, set | AIR301 [*] `airflow.configuration.set` is removed in Airflow 3.0 @@ -514,14 +464,14 @@ AIR301 [*] `airflow.configuration.set` is removed in Airflow 3.0 | help: Use `conf.set` from `airflow.configuration` instead. | +75 | from airflow.configuration import ( + … 83 | set, 84 + conf, 85 | ) 86 | 87 | # airflow.configuration - - get, getboolean, getfloat, getint, has_option, remove_option, as_dict, set -88 + get, getboolean, getfloat, getint, has_option, remove_option, as_dict, conf -89 | from airflow.hooks.base_hook import BaseHook +88 ~ get, getboolean, getfloat, getint, has_option, remove_option, as_dict, conf | AIR301 [*] `airflow.hooks.base_hook.BaseHook` is removed in Airflow 3.0 @@ -535,10 +485,8 @@ AIR301 [*] `airflow.hooks.base_hook.BaseHook` is removed in Airflow 3.0 | help: `BaseHook` has been moved to `airflow.hooks.base` since Airflow 3.0. Import `BaseHook` from `airflow.hooks.base` is suggested in Airflow 3.0, but it is deprecated in Airflow 3.1+. | -87 | get, getboolean, getfloat, getint, has_option, remove_option, as_dict, set - - from airflow.hooks.base_hook import BaseHook -88 + from airflow.hooks.base import BaseHook -89 | +88 + +89 + from airflow.hooks.base import BaseHook | note: This is an unsafe fix and may change runtime behavior @@ -552,10 +500,8 @@ AIR301 [*] `airflow.sensors.base_sensor_operator.BaseSensorOperator` is removed | help: `BaseSensorOperator` has been moved to `airflow.sdk.bases.sensor` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -92 | - - from airflow.sensors.base_sensor_operator import BaseSensorOperator -93 + from airflow.sdk.bases.sensor import BaseSensorOperator -94 | +93 + +94 + from airflow.sdk.bases.sensor import BaseSensorOperator | note: This is an unsafe fix and may change runtime behavior @@ -571,13 +517,11 @@ AIR301 [*] `airflow.hooks.base_hook.BaseHook` is removed in Airflow 3.0 | help: `BaseHook` has been moved to `airflow.hooks.base` since Airflow 3.0. Import `BaseHook` from `airflow.hooks.base` is suggested in Airflow 3.0, but it is deprecated in Airflow 3.1+. | -87 | get, getboolean, getfloat, getint, has_option, remove_option, as_dict, set - - from airflow.hooks.base_hook import BaseHook -88 | --------------------------------------------------------------------------------- -92 | from airflow.sensors.base_sensor_operator import BaseSensorOperator -93 + from airflow.hooks.base import BaseHook -94 | +88 + +89 | + … +93 | from airflow.sensors.base_sensor_operator import BaseSensorOperator +94 + from airflow.hooks.base import BaseHook | note: This is an unsafe fix and may change runtime behavior @@ -591,13 +535,10 @@ AIR301 [*] `airflow.utils.helpers.chain` is removed in Airflow 3.0 | help: `chain` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -100 | from airflow.utils.helpers import cross_downstream as helper_cross_downstream 101 + from airflow.sdk import chain -102 | +102 + 103 | # airflow.utils.helpers - - helper_chain 104 + chain -105 | helper_cross_downstream | AIR301 [*] `airflow.utils.helpers.cross_downstream` is removed in Airflow 3.0 @@ -612,14 +553,11 @@ AIR301 [*] `airflow.utils.helpers.cross_downstream` is removed in Airflow 3.0 | help: `cross_downstream` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -100 | from airflow.utils.helpers import cross_downstream as helper_cross_downstream 101 + from airflow.sdk import cross_downstream -102 | +102 + 103 | # airflow.utils.helpers 104 | helper_chain - - helper_cross_downstream 105 + cross_downstream -106 | | AIR301 [*] `airflow.utils.file.TemporaryDirectory` is removed in Airflow 3.0 @@ -634,10 +572,8 @@ AIR301 [*] `airflow.utils.file.TemporaryDirectory` is removed in Airflow 3.0 | help: Use `TemporaryDirectory` from `tempfile` instead. | -106 | # airflow.utils.file - - from airflow.utils.file import TemporaryDirectory -107 + from tempfile import TemporaryDirectory -108 | +107 + +108 + from tempfile import TemporaryDirectory | note: This is an unsafe fix and may change runtime behavior @@ -649,9 +585,7 @@ AIR301 [*] `airflow.utils.log.secrets_masker` is removed in Airflow 3.0 | ^^^^^^^^^^^^^^ help: `secrets_masker` has been moved to `airflow.sdk.execution_time` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -110 | - - from airflow.utils.log import secrets_masker -111 + from airflow.sdk.execution_time import secrets_masker -112 | +111 + +112 + from airflow.sdk.execution_time import secrets_masker | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_provider_names_fix.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_provider_names_fix.py.snap index 48d2bd2658b45..579eb884fbd97 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_provider_names_fix.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR301_AIR301_provider_names_fix.py.snap @@ -13,10 +13,11 @@ AIR301 [*] `airflow.providers.amazon.aws.auth_manager.avp.entities.AvpEntities.D | help: Use `AvpEntities.ASSET` from `airflow.providers.amazon.aws.auth_manager.avp.entities` instead. | + 3 ~ from airflow.providers.amazon.aws.auth_manager.avp.entities import AvpEntities + 4 | from airflow.providers.openlineage.utils.utils import ( + … 10 | - - AvpEntities.DATASET 11 + AvpEntities -12 | | AIR301 [*] `airflow.providers.openlineage.utils.utils.DatasetInfo` is removed in Airflow 3.0 @@ -29,14 +30,15 @@ AIR301 [*] `airflow.providers.openlineage.utils.utils.DatasetInfo` is removed in | help: Use `AssetInfo` from `airflow.providers.openlineage.utils.utils` instead. | -6 | translate_airflow_dataset, -7 + AssetInfo, -8 | ) --------------------------------------------------------------------------------- + 4 | from airflow.providers.openlineage.utils.utils import ( + 5 | DatasetInfo, + 6 | translate_airflow_dataset, + 7 + AssetInfo, + 8 | ) + 9 | from airflow.secrets.local_filesystem import load_connections + … 14 | # airflow.providers.openlineage.utils.utils - - DatasetInfo() -15 + AssetInfo() -16 | translate_airflow_dataset() +15 ~ AssetInfo() | AIR301 [*] `airflow.providers.openlineage.utils.utils.translate_airflow_dataset` is removed in Airflow 3.0 @@ -51,14 +53,15 @@ AIR301 [*] `airflow.providers.openlineage.utils.utils.translate_airflow_dataset` | help: Use `translate_airflow_asset` from `airflow.providers.openlineage.utils.utils` instead. | -6 | translate_airflow_dataset, -7 + translate_airflow_asset, -8 | ) --------------------------------------------------------------------------------- + 4 | from airflow.providers.openlineage.utils.utils import ( + 5 | DatasetInfo, + 6 | translate_airflow_dataset, + 7 + translate_airflow_asset, + 8 | ) + 9 | from airflow.secrets.local_filesystem import load_connections + … 15 | DatasetInfo() - - translate_airflow_dataset() -16 + translate_airflow_asset() -17 | +16 ~ translate_airflow_asset() | AIR301 [*] `airflow.secrets.local_filesystem.load_connections` is removed in Airflow 3.0 @@ -72,15 +75,11 @@ AIR301 [*] `airflow.secrets.local_filesystem.load_connections` is removed in Air | help: Use `load_connections_dict` from `airflow.secrets.local_filesystem` instead. | -7 | ) - - from airflow.secrets.local_filesystem import load_connections -8 + from airflow.secrets.local_filesystem import load_connections, load_connections_dict -9 | from airflow.security.permissions import RESOURCE_DATASET --------------------------------------------------------------------------------- + 8 ~ from airflow.secrets.local_filesystem import load_connections, load_connections_dict + 9 | from airflow.security.permissions import RESOURCE_DATASET + … 17 | # airflow.secrets.local_filesystem - - load_connections() -18 + load_connections_dict() -19 | +18 ~ load_connections_dict() | AIR301 [*] `airflow.security.permissions.RESOURCE_DATASET` is removed in Airflow 3.0 @@ -94,15 +93,11 @@ AIR301 [*] `airflow.security.permissions.RESOURCE_DATASET` is removed in Airflow | help: Use `RESOURCE_ASSET` from `airflow.security.permissions` instead. | -8 | from airflow.secrets.local_filesystem import load_connections - - from airflow.security.permissions import RESOURCE_DATASET -9 + from airflow.security.permissions import RESOURCE_DATASET, RESOURCE_ASSET + 9 ~ from airflow.security.permissions import RESOURCE_DATASET, RESOURCE_ASSET 10 | --------------------------------------------------------------------------------- + … 20 | # airflow.security.permissions - - RESOURCE_DATASET 21 + RESOURCE_ASSET -22 | | AIR301 [*] `airflow.providers.amazon.aws.datasets.s3.create_dataset` is removed in Airflow 3.0 @@ -116,12 +111,9 @@ AIR301 [*] `airflow.providers.amazon.aws.datasets.s3.create_dataset` is removed | help: Use `create_asset` from `airflow.providers.amazon.aws.assets.s3` instead. | -26 | from airflow.providers.amazon.aws.datasets.s3 import create_dataset as s3_create_dataset 27 + from airflow.providers.amazon.aws.assets.s3 import create_asset -28 | - - s3_create_dataset() -29 + create_asset() -30 | s3_convert_dataset_to_openlineage() +28 + +29 ~ create_asset() | AIR301 [*] `airflow.providers.amazon.aws.datasets.s3.convert_dataset_to_openlineage` is removed in Airflow 3.0 @@ -135,13 +127,10 @@ AIR301 [*] `airflow.providers.amazon.aws.datasets.s3.convert_dataset_to_openline | help: Use `convert_asset_to_openlineage` from `airflow.providers.amazon.aws.assets.s3` instead. | -26 | from airflow.providers.amazon.aws.datasets.s3 import create_dataset as s3_create_dataset 27 + from airflow.providers.amazon.aws.assets.s3 import convert_asset_to_openlineage -28 | +28 + 29 | s3_create_dataset() - - s3_convert_dataset_to_openlineage() -30 + convert_asset_to_openlineage() -31 | +30 ~ convert_asset_to_openlineage() | AIR301 [*] `airflow.providers.google.datasets.bigquery.create_dataset` is removed in Airflow 3.0 @@ -156,12 +145,9 @@ AIR301 [*] `airflow.providers.google.datasets.bigquery.create_dataset` is remove | help: Use `create_asset` from `airflow.providers.google.assets.bigquery` instead. | -43 | ) 44 + from airflow.providers.google.assets.bigquery import create_asset -45 | - - bigquery_create_dataset() -46 + create_asset() -47 | +45 + +46 ~ create_asset() | AIR301 [*] `airflow.providers.google.datasets.gcs.create_dataset` is removed in Airflow 3.0 @@ -175,12 +161,9 @@ AIR301 [*] `airflow.providers.google.datasets.gcs.create_dataset` is removed in | help: Use `create_asset` from `airflow.providers.google.assets.gcs` instead. | -51 | from airflow.providers.google.datasets.gcs import create_dataset as gcs_create_dataset 52 + from airflow.providers.google.assets.gcs import create_asset -53 | - - gcs_create_dataset() -54 + create_asset() -55 | gcs_convert_dataset_to_openlineage() +53 + +54 ~ create_asset() | AIR301 [*] `airflow.providers.google.datasets.gcs.convert_dataset_to_openlineage` is removed in Airflow 3.0 @@ -191,10 +174,8 @@ AIR301 [*] `airflow.providers.google.datasets.gcs.convert_dataset_to_openlineage | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use `convert_asset_to_openlineage` from `airflow.providers.google.assets.gcs` instead. | -51 | from airflow.providers.google.datasets.gcs import create_dataset as gcs_create_dataset 52 + from airflow.providers.google.assets.gcs import convert_asset_to_openlineage -53 | +53 + 54 | gcs_create_dataset() - - gcs_convert_dataset_to_openlineage() -55 + convert_asset_to_openlineage() +55 ~ convert_asset_to_openlineage() | diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_amazon.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_amazon.py.snap index b270328a92a80..a86e6159233b6 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_amazon.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_amazon.py.snap @@ -12,13 +12,13 @@ AIR302 [*] `airflow.hooks.S3_hook.S3Hook` is moved into `amazon` provider in Air | help: Install `apache-airflow-providers-amazon>=1.0.0` and use `S3Hook` from `airflow.providers.amazon.aws.hooks.s3` instead. | -3 | from airflow.hooks.S3_hook import ( - - S3Hook, -4 | provide_bucket_name, --------------------------------------------------------------------------------- + 3 + from airflow.hooks.S3_hook import ( + 4 + provide_bucket_name, + 5 + ) + 6 | from airflow.operators.gcs_to_s3 import GCSToS3Operator + … 11 | from airflow.sensors.s3_key_sensor import S3KeySensor 12 + from airflow.providers.amazon.aws.hooks.s3 import S3Hook -13 | | note: This is an unsafe fix and may change runtime behavior @@ -33,13 +33,13 @@ AIR302 [*] `airflow.hooks.S3_hook.provide_bucket_name` is moved into `amazon` pr | help: Install `apache-airflow-providers-amazon>=1.0.0` and use `provide_bucket_name` from `airflow.providers.amazon.aws.hooks.s3` instead. | -4 | S3Hook, - - provide_bucket_name, -5 | ) --------------------------------------------------------------------------------- + 3 + from airflow.hooks.S3_hook import ( + 4 + S3Hook, + 5 + ) + 6 | from airflow.operators.gcs_to_s3 import GCSToS3Operator + … 11 | from airflow.sensors.s3_key_sensor import S3KeySensor 12 + from airflow.providers.amazon.aws.hooks.s3 import provide_bucket_name -13 | | note: This is an unsafe fix and may change runtime behavior @@ -55,13 +55,11 @@ AIR302 [*] `airflow.operators.gcs_to_s3.GCSToS3Operator` is moved into `amazon` | help: Install `apache-airflow-providers-amazon>=1.0.0` and use `GCSToS3Operator` from `airflow.providers.amazon.aws.transfers.gcs_to_s3` instead. | -6 | ) - - from airflow.operators.gcs_to_s3 import GCSToS3Operator -7 | from airflow.operators.google_api_to_s3_transfer import GoogleApiToS3Operator --------------------------------------------------------------------------------- -11 | from airflow.sensors.s3_key_sensor import S3KeySensor -12 + from airflow.providers.amazon.aws.transfers.gcs_to_s3 import GCSToS3Operator -13 | + 7 + + 8 | from airflow.operators.google_api_to_s3_transfer import GoogleApiToS3Operator + … +12 | from airflow.sensors.s3_key_sensor import S3KeySensor +13 + from airflow.providers.amazon.aws.transfers.gcs_to_s3 import GCSToS3Operator | note: This is an unsafe fix and may change runtime behavior @@ -76,14 +74,11 @@ AIR302 [*] `airflow.operators.google_api_to_s3_transfer.GoogleApiToS3Operator` i | help: Install `apache-airflow-providers-amazon>=1.0.0` and use `GoogleApiToS3Operator` from `airflow.providers.amazon.aws.transfers.google_api_to_s3` instead. | -7 | from airflow.operators.gcs_to_s3 import GCSToS3Operator - - from airflow.operators.google_api_to_s3_transfer import GoogleApiToS3Operator -8 | from airflow.operators.redshift_to_s3_operator import RedshiftToS3Operator -9 | from airflow.operators.s3_file_transform_operator import S3FileTransformOperator -10 | from airflow.operators.s3_to_redshift_operator import S3ToRedshiftOperator -11 | from airflow.sensors.s3_key_sensor import S3KeySensor -12 + from airflow.providers.amazon.aws.transfers.google_api_to_s3 import GoogleApiToS3Operator -13 | + 8 + + 9 | from airflow.operators.redshift_to_s3_operator import RedshiftToS3Operator + … +12 | from airflow.sensors.s3_key_sensor import S3KeySensor +13 + from airflow.providers.amazon.aws.transfers.google_api_to_s3 import GoogleApiToS3Operator | note: This is an unsafe fix and may change runtime behavior @@ -99,13 +94,11 @@ AIR302 [*] `airflow.operators.redshift_to_s3_operator.RedshiftToS3Operator` is m | help: Install `apache-airflow-providers-amazon>=1.0.0` and use `RedshiftToS3Operator` from `airflow.providers.amazon.aws.transfers.redshift_to_s3` instead. | -8 | from airflow.operators.google_api_to_s3_transfer import GoogleApiToS3Operator - - from airflow.operators.redshift_to_s3_operator import RedshiftToS3Operator -9 | from airflow.operators.s3_file_transform_operator import S3FileTransformOperator -10 | from airflow.operators.s3_to_redshift_operator import S3ToRedshiftOperator -11 | from airflow.sensors.s3_key_sensor import S3KeySensor -12 + from airflow.providers.amazon.aws.transfers.redshift_to_s3 import RedshiftToS3Operator -13 | + 9 + +10 | from airflow.operators.s3_file_transform_operator import S3FileTransformOperator +11 | from airflow.operators.s3_to_redshift_operator import S3ToRedshiftOperator +12 | from airflow.sensors.s3_key_sensor import S3KeySensor +13 + from airflow.providers.amazon.aws.transfers.redshift_to_s3 import RedshiftToS3Operator | note: This is an unsafe fix and may change runtime behavior @@ -121,12 +114,10 @@ AIR302 [*] `airflow.operators.s3_file_transform_operator.S3FileTransformOperator | help: Install `apache-airflow-providers-amazon>=3.0.0` and use `S3FileTransformOperator` from `airflow.providers.amazon.aws.operators.s3` instead. | -9 | from airflow.operators.redshift_to_s3_operator import RedshiftToS3Operator - - from airflow.operators.s3_file_transform_operator import S3FileTransformOperator -10 | from airflow.operators.s3_to_redshift_operator import S3ToRedshiftOperator -11 | from airflow.sensors.s3_key_sensor import S3KeySensor -12 + from airflow.providers.amazon.aws.operators.s3 import S3FileTransformOperator -13 | +10 + +11 | from airflow.operators.s3_to_redshift_operator import S3ToRedshiftOperator +12 | from airflow.sensors.s3_key_sensor import S3KeySensor +13 + from airflow.providers.amazon.aws.operators.s3 import S3FileTransformOperator | note: This is an unsafe fix and may change runtime behavior @@ -141,11 +132,9 @@ AIR302 [*] `airflow.operators.s3_to_redshift_operator.S3ToRedshiftOperator` is m | help: Install `apache-airflow-providers-amazon>=1.0.0` and use `S3ToRedshiftOperator` from `airflow.providers.amazon.aws.transfers.s3_to_redshift` instead. | -10 | from airflow.operators.s3_file_transform_operator import S3FileTransformOperator - - from airflow.operators.s3_to_redshift_operator import S3ToRedshiftOperator -11 | from airflow.sensors.s3_key_sensor import S3KeySensor -12 + from airflow.providers.amazon.aws.transfers.s3_to_redshift import S3ToRedshiftOperator -13 | +11 + +12 | from airflow.sensors.s3_key_sensor import S3KeySensor +13 + from airflow.providers.amazon.aws.transfers.s3_to_redshift import S3ToRedshiftOperator | note: This is an unsafe fix and may change runtime behavior @@ -161,10 +150,8 @@ AIR302 [*] `airflow.sensors.s3_key_sensor.S3KeySensor` is moved into `amazon` pr | help: Install `apache-airflow-providers-amazon>=1.0.0` and use `S3KeySensor` from `airflow.providers.amazon.aws.sensors.s3` instead. | -11 | from airflow.operators.s3_to_redshift_operator import S3ToRedshiftOperator - - from airflow.sensors.s3_key_sensor import S3KeySensor -12 + from airflow.providers.amazon.aws.sensors.s3 import S3KeySensor -13 | +12 + +13 + from airflow.providers.amazon.aws.sensors.s3 import S3KeySensor | note: This is an unsafe fix and may change runtime behavior @@ -180,9 +167,8 @@ AIR302 [*] `airflow.operators.google_api_to_s3_transfer.GoogleApiToS3Transfer` i | help: Install `apache-airflow-providers-amazon>=1.0.0` and use `GoogleApiToS3Operator` from `airflow.providers.amazon.aws.transfers.google_api_to_s3` instead. | -24 | from airflow.operators.google_api_to_s3_transfer import GoogleApiToS3Transfer +24 ~ from airflow.operators.google_api_to_s3_transfer import GoogleApiToS3Transfer 25 + from airflow.providers.amazon.aws.transfers.google_api_to_s3 import GoogleApiToS3Operator -26 | | note: This is an unsafe fix and may change runtime behavior @@ -198,9 +184,8 @@ AIR302 [*] `airflow.operators.redshift_to_s3_operator.RedshiftToS3Transfer` is m | help: Install `apache-airflow-providers-amazon>=1.0.0` and use `RedshiftToS3Operator` from `airflow.providers.amazon.aws.transfers.redshift_to_s3` instead. | -28 | from airflow.operators.redshift_to_s3_operator import RedshiftToS3Transfer +28 ~ from airflow.operators.redshift_to_s3_operator import RedshiftToS3Transfer 29 + from airflow.providers.amazon.aws.transfers.redshift_to_s3 import RedshiftToS3Operator -30 | | note: This is an unsafe fix and may change runtime behavior @@ -213,8 +198,7 @@ AIR302 [*] `airflow.operators.s3_to_redshift_operator.S3ToRedshiftTransfer` is m | ^^^^^^^^^^^^^^^^^^^^ help: Install `apache-airflow-providers-amazon>=1.0.0` and use `S3ToRedshiftOperator` from `airflow.providers.amazon.aws.transfers.s3_to_redshift` instead. | -32 | from airflow.operators.s3_to_redshift_operator import S3ToRedshiftTransfer +32 ~ from airflow.operators.s3_to_redshift_operator import S3ToRedshiftTransfer 33 + from airflow.providers.amazon.aws.transfers.s3_to_redshift import S3ToRedshiftOperator -34 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_celery.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_celery.py.snap index 5fa835ca2ea5c..4fcb5b746358d 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_celery.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_celery.py.snap @@ -13,14 +13,11 @@ AIR302 [*] `airflow.config_templates.default_celery.DEFAULT_CELERY_CONFIG` is mo | help: Install `apache-airflow-providers-celery>=3.3.0` and use `DEFAULT_CELERY_CONFIG` from `airflow.providers.celery.executors.default_celery` instead. | -2 | - - from airflow.config_templates.default_celery import DEFAULT_CELERY_CONFIG -3 | from airflow.executors.celery_executor import ( -4 | CeleryExecutor, -5 | app, -6 | ) -7 + from airflow.providers.celery.executors.default_celery import DEFAULT_CELERY_CONFIG -8 | +3 + +4 | from airflow.executors.celery_executor import ( +… +7 | ) +8 + from airflow.providers.celery.executors.default_celery import DEFAULT_CELERY_CONFIG | note: This is an unsafe fix and may change runtime behavior @@ -35,11 +32,10 @@ AIR302 [*] `airflow.executors.celery_executor.app` is moved into `celery` provid | help: Install `apache-airflow-providers-celery>=3.3.0` and use `app` from `airflow.providers.celery.executors.celery_executor_utils` instead. | -5 | CeleryExecutor, - - app, -6 | ) +4 + from airflow.executors.celery_executor import ( +5 + CeleryExecutor, +6 + ) 7 + from airflow.providers.celery.executors.celery_executor_utils import app -8 | | note: This is an unsafe fix and may change runtime behavior @@ -51,11 +47,9 @@ AIR302 [*] `airflow.executors.celery_executor.CeleryExecutor` is moved into `cel | ^^^^^^^^^^^^^^ help: Install `apache-airflow-providers-celery>=3.3.0` and use `CeleryExecutor` from `airflow.providers.celery.executors.celery_executor` instead. | -4 | from airflow.executors.celery_executor import ( - - CeleryExecutor, -5 | app, -6 | ) +4 + from airflow.executors.celery_executor import ( +5 + app, +6 + ) 7 + from airflow.providers.celery.executors.celery_executor import CeleryExecutor -8 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_common_sql.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_common_sql.py.snap index 1eb33784729ff..834238d92e8bf 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_common_sql.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_common_sql.py.snap @@ -12,12 +12,10 @@ AIR302 [*] `airflow.hooks.dbapi.ConnectorProtocol` is moved into `common-sql` pr | help: Install `apache-airflow-providers-common-sql>=1.0.0` and use `ConnectorProtocol` from `airflow.providers.common.sql.hooks.sql` instead. | -3 | from airflow.hooks.dbapi import ( - - ConnectorProtocol, -4 | DbApiHook, -5 | ) +3 + from airflow.hooks.dbapi import ( +4 + DbApiHook, +5 + ) 6 + from airflow.providers.common.sql.hooks.sql import ConnectorProtocol -7 | | note: This is an unsafe fix and may change runtime behavior @@ -32,11 +30,10 @@ AIR302 [*] `airflow.hooks.dbapi.DbApiHook` is moved into `common-sql` provider i | help: Install `apache-airflow-providers-common-sql>=1.0.0` and use `DbApiHook` from `airflow.providers.common.sql.hooks.sql` instead. | -4 | ConnectorProtocol, - - DbApiHook, -5 | ) +3 + from airflow.hooks.dbapi import ( +4 + ConnectorProtocol, +5 + ) 6 + from airflow.providers.common.sql.hooks.sql import DbApiHook -7 | | note: This is an unsafe fix and may change runtime behavior @@ -51,11 +48,9 @@ AIR302 [*] `airflow.hooks.dbapi_hook.DbApiHook` is moved into `common-sql` provi | help: Install `apache-airflow-providers-common-sql>=1.0.0` and use `DbApiHook` from `airflow.providers.common.sql.hooks.sql` instead. | -10 | - - from airflow.hooks.dbapi_hook import DbApiHook -11 | from airflow.operators.check_operator import SQLCheckOperator -12 + from airflow.providers.common.sql.hooks.sql import DbApiHook -13 | +11 + +12 | from airflow.operators.check_operator import SQLCheckOperator +13 + from airflow.providers.common.sql.hooks.sql import DbApiHook | note: This is an unsafe fix and may change runtime behavior @@ -67,10 +62,8 @@ AIR302 [*] `airflow.operators.check_operator.SQLCheckOperator` is moved into `co | ^^^^^^^^^^^^^^^^ help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `SQLCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | -11 | from airflow.hooks.dbapi_hook import DbApiHook - - from airflow.operators.check_operator import SQLCheckOperator -12 + from airflow.providers.common.sql.operators.sql import SQLCheckOperator -13 | +12 + +13 + from airflow.providers.common.sql.operators.sql import SQLCheckOperator | note: This is an unsafe fix and may change runtime behavior @@ -85,10 +78,8 @@ AIR302 [*] `airflow.operators.sql.SQLCheckOperator` is moved into `common-sql` p | help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `SQLCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | -18 | from airflow.operators.check_operator import CheckOperator - - from airflow.operators.sql import SQLCheckOperator -19 + from airflow.providers.common.sql.operators.sql import SQLCheckOperator -20 | +19 + +20 + from airflow.providers.common.sql.operators.sql import SQLCheckOperator | note: This is an unsafe fix and may change runtime behavior @@ -100,9 +91,9 @@ AIR302 [*] `airflow.operators.check_operator.CheckOperator` is moved into `commo | ^^^^^^^^^^^^^ help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `SQLCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | +18 ~ from airflow.operators.check_operator import CheckOperator 19 | from airflow.operators.sql import SQLCheckOperator 20 + from airflow.providers.common.sql.operators.sql import SQLCheckOperator -21 | | note: This is an unsafe fix and may change runtime behavior @@ -115,9 +106,8 @@ AIR302 [*] `airflow.operators.druid_check_operator.CheckOperator` is moved into | ^^^^^^^^^^^^^ help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `SQLCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | -25 | from airflow.operators.druid_check_operator import CheckOperator +25 ~ from airflow.operators.druid_check_operator import CheckOperator 26 + from airflow.providers.common.sql.operators.sql import SQLCheckOperator -27 | | note: This is an unsafe fix and may change runtime behavior @@ -130,9 +120,8 @@ AIR302 [*] `airflow.operators.presto_check_operator.CheckOperator` is moved into | ^^^^^^^^^^^^^ help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `SQLCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | -30 | from airflow.operators.presto_check_operator import CheckOperator +30 ~ from airflow.operators.presto_check_operator import CheckOperator 31 + from airflow.providers.common.sql.operators.sql import SQLCheckOperator -32 | | note: This is an unsafe fix and may change runtime behavior @@ -148,9 +137,9 @@ AIR302 [*] `airflow.operators.druid_check_operator.DruidCheckOperator` is moved | help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `SQLCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | +39 ~ from airflow.operators.druid_check_operator import DruidCheckOperator 40 | from airflow.operators.presto_check_operator import PrestoCheckOperator 41 + from airflow.providers.common.sql.operators.sql import SQLCheckOperator -42 | | note: This is an unsafe fix and may change runtime behavior @@ -165,9 +154,8 @@ AIR302 [*] `airflow.operators.presto_check_operator.PrestoCheckOperator` is move | help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `SQLCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | -40 | from airflow.operators.presto_check_operator import PrestoCheckOperator +40 ~ from airflow.operators.presto_check_operator import PrestoCheckOperator 41 + from airflow.providers.common.sql.operators.sql import SQLCheckOperator -42 | | note: This is an unsafe fix and may change runtime behavior @@ -182,13 +170,12 @@ AIR302 [*] `airflow.operators.check_operator.IntervalCheckOperator` is moved int | help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `SQLIntervalCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | -36 | IntervalCheckOperator, - - SQLIntervalCheckOperator, -37 | ) +35 + from airflow.operators.check_operator import ( +36 + IntervalCheckOperator, +37 + ) 38 | from airflow.operators.druid_check_operator import DruidCheckOperator 39 | from airflow.operators.presto_check_operator import PrestoCheckOperator 40 + from airflow.providers.common.sql.operators.sql import SQLIntervalCheckOperator -41 | | note: This is an unsafe fix and may change runtime behavior @@ -201,13 +188,12 @@ AIR302 [*] `airflow.operators.check_operator.SQLIntervalCheckOperator` is moved | ^^^^^^^^^^^^^^^^^^^^^^^^ help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `SQLIntervalCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | -36 | IntervalCheckOperator, - - SQLIntervalCheckOperator, -37 | ) +35 + from airflow.operators.check_operator import ( +36 + IntervalCheckOperator, +37 + ) 38 | from airflow.operators.druid_check_operator import DruidCheckOperator 39 | from airflow.operators.presto_check_operator import PrestoCheckOperator 40 + from airflow.providers.common.sql.operators.sql import SQLIntervalCheckOperator -41 | | note: This is an unsafe fix and may change runtime behavior @@ -223,9 +209,12 @@ AIR302 [*] `airflow.operators.presto_check_operator.IntervalCheckOperator` is mo | help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `SQLIntervalCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | +48 | from airflow.operators.presto_check_operator import ( +49 | IntervalCheckOperator, +50 | PrestoIntervalCheckOperator, +51 ~ ) 52 | from airflow.operators.sql import SQLIntervalCheckOperator 53 + from airflow.providers.common.sql.operators.sql import SQLIntervalCheckOperator -54 | | note: This is an unsafe fix and may change runtime behavior @@ -239,10 +228,8 @@ AIR302 [*] `airflow.operators.sql.SQLIntervalCheckOperator` is moved into `commo | help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `SQLIntervalCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | -51 | ) - - from airflow.operators.sql import SQLIntervalCheckOperator -52 + from airflow.providers.common.sql.operators.sql import SQLIntervalCheckOperator -53 | +52 + +53 + from airflow.providers.common.sql.operators.sql import SQLIntervalCheckOperator | note: This is an unsafe fix and may change runtime behavior @@ -255,9 +242,12 @@ AIR302 [*] `airflow.operators.presto_check_operator.PrestoIntervalCheckOperator` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `SQLIntervalCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | +48 | from airflow.operators.presto_check_operator import ( +49 | IntervalCheckOperator, +50 | PrestoIntervalCheckOperator, +51 ~ ) 52 | from airflow.operators.sql import SQLIntervalCheckOperator 53 + from airflow.providers.common.sql.operators.sql import SQLIntervalCheckOperator -54 | | note: This is an unsafe fix and may change runtime behavior @@ -272,12 +262,10 @@ AIR302 [*] `airflow.operators.check_operator.SQLThresholdCheckOperator` is moved | help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `SQLThresholdCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | -59 | from airflow.operators.check_operator import ( - - SQLThresholdCheckOperator, -60 | ThresholdCheckOperator, -61 | ) +59 + from airflow.operators.check_operator import ( +60 + ThresholdCheckOperator, +61 + ) 62 + from airflow.providers.common.sql.operators.sql import SQLThresholdCheckOperator -63 | | note: This is an unsafe fix and may change runtime behavior @@ -289,12 +277,10 @@ AIR302 [*] `airflow.operators.check_operator.ThresholdCheckOperator` is moved in | ^^^^^^^^^^^^^^^^^^^^^^ help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `SQLThresholdCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | -59 | from airflow.operators.check_operator import ( - - SQLThresholdCheckOperator, -60 | ThresholdCheckOperator, -61 | ) +59 + from airflow.operators.check_operator import ( +60 + ThresholdCheckOperator, +61 + ) 62 + from airflow.providers.common.sql.operators.sql import SQLThresholdCheckOperator -63 | | note: This is an unsafe fix and may change runtime behavior @@ -307,10 +293,8 @@ AIR302 [*] `airflow.operators.sql.SQLThresholdCheckOperator` is moved into `comm | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `SQLThresholdCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | -67 | - - from airflow.operators.sql import SQLThresholdCheckOperator -68 + from airflow.providers.common.sql.operators.sql import SQLThresholdCheckOperator -69 | +68 + +69 + from airflow.providers.common.sql.operators.sql import SQLThresholdCheckOperator | note: This is an unsafe fix and may change runtime behavior @@ -325,12 +309,10 @@ AIR302 [*] `airflow.operators.check_operator.SQLValueCheckOperator` is moved int | help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `SQLValueCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | -73 | from airflow.operators.check_operator import ( - - SQLValueCheckOperator, -74 | ValueCheckOperator, -75 | ) +73 + from airflow.operators.check_operator import ( +74 + ValueCheckOperator, +75 + ) 76 + from airflow.providers.common.sql.operators.sql import SQLValueCheckOperator -77 | | note: This is an unsafe fix and may change runtime behavior @@ -342,12 +324,10 @@ AIR302 [*] `airflow.operators.check_operator.ValueCheckOperator` is moved into ` | ^^^^^^^^^^^^^^^^^^ help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `SQLValueCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | -73 | from airflow.operators.check_operator import ( - - SQLValueCheckOperator, -74 | ValueCheckOperator, -75 | ) +73 + from airflow.operators.check_operator import ( +74 + ValueCheckOperator, +75 + ) 76 + from airflow.providers.common.sql.operators.sql import SQLValueCheckOperator -77 | | note: This is an unsafe fix and may change runtime behavior @@ -363,10 +343,8 @@ AIR302 [*] `airflow.operators.sql.SQLValueCheckOperator` is moved into `common-s | help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `SQLValueCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | -85 | ) - - from airflow.operators.sql import SQLValueCheckOperator -86 + from airflow.providers.common.sql.operators.sql import SQLValueCheckOperator -87 | +86 + +87 + from airflow.providers.common.sql.operators.sql import SQLValueCheckOperator | note: This is an unsafe fix and may change runtime behavior @@ -380,9 +358,12 @@ AIR302 [*] `airflow.operators.presto_check_operator.ValueCheckOperator` is moved | help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `SQLValueCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | +82 | from airflow.operators.presto_check_operator import ( +83 | PrestoValueCheckOperator, +84 | ValueCheckOperator, +85 ~ ) 86 | from airflow.operators.sql import SQLValueCheckOperator 87 + from airflow.providers.common.sql.operators.sql import SQLValueCheckOperator -88 | | note: This is an unsafe fix and may change runtime behavior @@ -395,9 +376,12 @@ AIR302 [*] `airflow.operators.presto_check_operator.PrestoValueCheckOperator` is | ^^^^^^^^^^^^^^^^^^^^^^^^ help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `SQLValueCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | +82 | from airflow.operators.presto_check_operator import ( +83 | PrestoValueCheckOperator, +84 | ValueCheckOperator, +85 ~ ) 86 | from airflow.operators.sql import SQLValueCheckOperator 87 + from airflow.providers.common.sql.operators.sql import SQLValueCheckOperator -88 | | note: This is an unsafe fix and may change runtime behavior @@ -413,13 +397,14 @@ AIR302 [*] `airflow.operators.sql.BaseSQLOperator` is moved into `common-sql` pr | help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `BaseSQLOperator` from `airflow.providers.common.sql.operators.sql` instead. | -93 | from airflow.operators.sql import ( - - BaseSQLOperator, -94 | BranchSQLOperator, --------------------------------------------------------------------------------- -99 | ) + 93 + from airflow.operators.sql import ( + 94 + BranchSQLOperator, + 95 + SQLColumnCheckOperator, + 96 + SQLTableCheckOperator, + 97 + _convert_to_float_if_possible, + 98 + parse_boolean, + 99 + ) 100 + from airflow.providers.common.sql.operators.sql import BaseSQLOperator -101 | | note: This is an unsafe fix and may change runtime behavior @@ -434,13 +419,14 @@ AIR302 [*] `airflow.operators.sql.BranchSQLOperator` is moved into `common-sql` | help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `BranchSQLOperator` from `airflow.providers.common.sql.operators.sql` instead. | -94 | BaseSQLOperator, - - BranchSQLOperator, -95 | SQLColumnCheckOperator, --------------------------------------------------------------------------------- -99 | ) + 93 + from airflow.operators.sql import ( + 94 + BaseSQLOperator, + 95 + SQLColumnCheckOperator, + 96 + SQLTableCheckOperator, + 97 + _convert_to_float_if_possible, + 98 + parse_boolean, + 99 + ) 100 + from airflow.providers.common.sql.operators.sql import BranchSQLOperator -101 | | note: This is an unsafe fix and may change runtime behavior @@ -456,13 +442,14 @@ AIR302 [*] `airflow.operators.sql.SQLTableCheckOperator` is moved into `common-s | help: Install `apache-airflow-providers-common-sql>=1.1.0` and use `SQLTableCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | -96 | SQLColumnCheckOperator, - - SQLTableCheckOperator, -97 | _convert_to_float_if_possible, -98 | parse_boolean, -99 | ) + 93 + from airflow.operators.sql import ( + 94 + BaseSQLOperator, + 95 + BranchSQLOperator, + 96 + SQLColumnCheckOperator, + 97 + _convert_to_float_if_possible, + 98 + parse_boolean, + 99 + ) 100 + from airflow.providers.common.sql.operators.sql import SQLTableCheckOperator -101 | | note: This is an unsafe fix and may change runtime behavior @@ -478,14 +465,14 @@ AIR302 [*] `airflow.operators.sql.SQLColumnCheckOperator` is moved into `common- | help: Install `apache-airflow-providers-common-sql>=1.0.0` and use `SQLColumnCheckOperator` from `airflow.providers.common.sql.operators.sql` instead. | -95 | BranchSQLOperator, - - SQLColumnCheckOperator, -96 | SQLTableCheckOperator, -97 | _convert_to_float_if_possible, -98 | parse_boolean, -99 | ) + 93 + from airflow.operators.sql import ( + 94 + BaseSQLOperator, + 95 + BranchSQLOperator, + 96 + SQLTableCheckOperator, + 97 + _convert_to_float_if_possible, + 98 + parse_boolean, + 99 + ) 100 + from airflow.providers.common.sql.operators.sql import SQLColumnCheckOperator -101 | | note: This is an unsafe fix and may change runtime behavior @@ -500,12 +487,14 @@ AIR302 [*] `airflow.operators.sql._convert_to_float_if_possible` is moved into ` | help: Install `apache-airflow-providers-common-sql>=1.0.0` and use `_convert_to_float_if_possible` from `airflow.providers.common.sql.operators.sql` instead. | -97 | SQLTableCheckOperator, - - _convert_to_float_if_possible, -98 | parse_boolean, -99 | ) + 93 + from airflow.operators.sql import ( + 94 + BaseSQLOperator, + 95 + BranchSQLOperator, + 96 + SQLColumnCheckOperator, + 97 + SQLTableCheckOperator, + 98 + parse_boolean, + 99 + ) 100 + from airflow.providers.common.sql.operators.sql import _convert_to_float_if_possible -101 | | note: This is an unsafe fix and may change runtime behavior @@ -518,11 +507,14 @@ AIR302 [*] `airflow.operators.sql.parse_boolean` is moved into `common-sql` prov | ^^^^^^^^^^^^^ help: Install `apache-airflow-providers-common-sql>=1.0.0` and use `parse_boolean` from `airflow.providers.common.sql.operators.sql` instead. | -98 | _convert_to_float_if_possible, - - parse_boolean, -99 | ) + 93 + from airflow.operators.sql import ( + 94 + BaseSQLOperator, + 95 + BranchSQLOperator, + 96 + SQLColumnCheckOperator, + 97 + SQLTableCheckOperator, + 98 + _convert_to_float_if_possible, + 99 + ) 100 + from airflow.providers.common.sql.operators.sql import parse_boolean -101 | | note: This is an unsafe fix and may change runtime behavior @@ -535,10 +527,8 @@ AIR302 [*] `airflow.sensors.sql.SqlSensor` is moved into `common-sql` provider i | ^^^^^^^^^ help: Install `apache-airflow-providers-common-sql>=1.0.0` and use `SqlSensor` from `airflow.providers.common.sql.sensors.sql` instead. | -109 | - - from airflow.sensors.sql import SqlSensor -110 + from airflow.providers.common.sql.sensors.sql import SqlSensor -111 | +110 + +111 + from airflow.providers.common.sql.sensors.sql import SqlSensor | note: This is an unsafe fix and may change runtime behavior @@ -551,9 +541,7 @@ AIR302 [*] `airflow.sensors.sql_sensor.SqlSensor` is moved into `common-sql` pro | ^^^^^^^^^ help: Install `apache-airflow-providers-common-sql>=1.0.0` and use `SqlSensor` from `airflow.providers.common.sql.sensors.sql` instead. | -114 | - - from airflow.sensors.sql_sensor import SqlSensor -115 + from airflow.providers.common.sql.sensors.sql import SqlSensor -116 | +115 + +116 + from airflow.providers.common.sql.sensors.sql import SqlSensor | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_daskexecutor.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_daskexecutor.py.snap index 5c0ee422ed29b..4eca6b01b2cc7 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_daskexecutor.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_daskexecutor.py.snap @@ -10,9 +10,7 @@ AIR302 [*] `airflow.executors.dask_executor.DaskExecutor` is moved into `daskexe | ^^^^^^^^^^^^ help: Install `apache-airflow-providers-daskexecutor>=1.0.0` and use `DaskExecutor` from `airflow.providers.daskexecutor.executors.dask_executor` instead. | -2 | - - from airflow.executors.dask_executor import DaskExecutor -3 + from airflow.providers.daskexecutor.executors.dask_executor import DaskExecutor -4 | +3 + +4 + from airflow.providers.daskexecutor.executors.dask_executor import DaskExecutor | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_druid.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_druid.py.snap index 9558e07336138..1968bbf014951 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_druid.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_druid.py.snap @@ -12,13 +12,13 @@ AIR302 [*] `airflow.hooks.druid_hook.DruidDbApiHook` is moved into `apache-druid | help: Install `apache-airflow-providers-apache-druid>=1.0.0` and use `DruidDbApiHook` from `airflow.providers.apache.druid.hooks.druid` instead. | -3 | from airflow.hooks.druid_hook import ( - - DruidDbApiHook, -4 | DruidHook, --------------------------------------------------------------------------------- -9 | ) + 3 + from airflow.hooks.druid_hook import ( + 4 + DruidHook, + 5 + ) + 6 | from airflow.operators.hive_to_druid import ( + … + 9 | ) 10 + from airflow.providers.apache.druid.hooks.druid import DruidDbApiHook -11 | | note: This is an unsafe fix and may change runtime behavior @@ -33,13 +33,13 @@ AIR302 [*] `airflow.hooks.druid_hook.DruidHook` is moved into `apache-druid` pro | help: Install `apache-airflow-providers-apache-druid>=1.0.0` and use `DruidHook` from `airflow.providers.apache.druid.hooks.druid` instead. | -4 | DruidDbApiHook, - - DruidHook, -5 | ) --------------------------------------------------------------------------------- -9 | ) + 3 + from airflow.hooks.druid_hook import ( + 4 + DruidDbApiHook, + 5 + ) + 6 | from airflow.operators.hive_to_druid import ( + … + 9 | ) 10 + from airflow.providers.apache.druid.hooks.druid import DruidHook -11 | | note: This is an unsafe fix and may change runtime behavior @@ -54,12 +54,10 @@ AIR302 [*] `airflow.operators.hive_to_druid.HiveToDruidOperator` is moved into ` | help: Install `apache-airflow-providers-apache-druid>=1.0.0` and use `HiveToDruidOperator` from `airflow.providers.apache.druid.transfers.hive_to_druid` instead. | -7 | from airflow.operators.hive_to_druid import ( - - HiveToDruidOperator, -8 | HiveToDruidTransfer, -9 | ) + 7 + from airflow.operators.hive_to_druid import ( + 8 + HiveToDruidTransfer, + 9 + ) 10 + from airflow.providers.apache.druid.transfers.hive_to_druid import HiveToDruidOperator -11 | | note: This is an unsafe fix and may change runtime behavior @@ -71,11 +69,9 @@ AIR302 [*] `airflow.operators.hive_to_druid.HiveToDruidTransfer` is moved into ` | ^^^^^^^^^^^^^^^^^^^ help: Install `apache-airflow-providers-apache-druid>=1.0.0` and use `HiveToDruidOperator` from `airflow.providers.apache.druid.transfers.hive_to_druid` instead. | -7 | from airflow.operators.hive_to_druid import ( - - HiveToDruidOperator, -8 | HiveToDruidTransfer, -9 | ) + 7 + from airflow.operators.hive_to_druid import ( + 8 + HiveToDruidTransfer, + 9 + ) 10 + from airflow.providers.apache.druid.transfers.hive_to_druid import HiveToDruidOperator -11 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_fab.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_fab.py.snap index 77b7ae496e582..1eed6b9e28a6e 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_fab.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_fab.py.snap @@ -13,14 +13,12 @@ AIR302 [*] `airflow.api.auth.backend.basic_auth.CLIENT_AUTH` is moved into `fab` | help: Install `apache-airflow-providers-fab>=1.0.0` and use `CLIENT_AUTH` from `airflow.providers.fab.auth_manager.api.auth.backend.basic_auth` instead. | -3 | from airflow.api.auth.backend.basic_auth import ( - - CLIENT_AUTH, -4 | auth_current_user, -5 | init_app, -6 | requires_authentication, -7 | ) +3 + from airflow.api.auth.backend.basic_auth import ( +4 + auth_current_user, +5 + init_app, +6 + requires_authentication, +7 + ) 8 + from airflow.providers.fab.auth_manager.api.auth.backend.basic_auth import CLIENT_AUTH -9 | | note: This is an unsafe fix and may change runtime behavior @@ -35,12 +33,12 @@ AIR302 [*] `airflow.api.auth.backend.basic_auth.init_app` is moved into `fab` pr | help: Install `apache-airflow-providers-fab>=1.0.0` and use `init_app` from `airflow.providers.fab.auth_manager.api.auth.backend.basic_auth` instead. | -5 | auth_current_user, - - init_app, -6 | requires_authentication, -7 | ) +3 + from airflow.api.auth.backend.basic_auth import ( +4 + CLIENT_AUTH, +5 + auth_current_user, +6 + requires_authentication, +7 + ) 8 + from airflow.providers.fab.auth_manager.api.auth.backend.basic_auth import init_app -9 | | note: This is an unsafe fix and may change runtime behavior @@ -55,13 +53,12 @@ AIR302 [*] `airflow.api.auth.backend.basic_auth.auth_current_user` is moved into | help: Install `apache-airflow-providers-fab>=1.0.0` and use `auth_current_user` from `airflow.providers.fab.auth_manager.api.auth.backend.basic_auth` instead. | -4 | CLIENT_AUTH, - - auth_current_user, -5 | init_app, -6 | requires_authentication, -7 | ) +3 + from airflow.api.auth.backend.basic_auth import ( +4 + CLIENT_AUTH, +5 + init_app, +6 + requires_authentication, +7 + ) 8 + from airflow.providers.fab.auth_manager.api.auth.backend.basic_auth import auth_current_user -9 | | note: This is an unsafe fix and may change runtime behavior @@ -77,11 +74,12 @@ AIR302 [*] `airflow.api.auth.backend.basic_auth.requires_authentication` is move | help: Install `apache-airflow-providers-fab>=1.0.0` and use `requires_authentication` from `airflow.providers.fab.auth_manager.api.auth.backend.basic_auth` instead. | -6 | init_app, - - requires_authentication, -7 | ) +3 + from airflow.api.auth.backend.basic_auth import ( +4 + CLIENT_AUTH, +5 + auth_current_user, +6 + init_app, +7 + ) 8 + from airflow.providers.fab.auth_manager.api.auth.backend.basic_auth import requires_authentication -9 | | note: This is an unsafe fix and may change runtime behavior @@ -97,12 +95,13 @@ AIR302 [*] `airflow.api.auth.backend.kerberos_auth.log` is moved into `fab` prov | help: Install `apache-airflow-providers-fab>=1.0.0` and use `log` from `airflow.providers.fab.auth_manager.api.auth.backend.kerberos_auth` instead. | -18 | init_app, - - log, -19 | requires_authentication, -20 | ) +15 + from airflow.api.auth.backend.kerberos_auth import ( +16 + CLIENT_AUTH, +17 + find_user, +18 + init_app, +19 + requires_authentication, +20 + ) 21 + from airflow.providers.fab.auth_manager.api.auth.backend.kerberos_auth import log -22 | | note: This is an unsafe fix and may change runtime behavior @@ -117,13 +116,13 @@ AIR302 [*] `airflow.api.auth.backend.kerberos_auth.CLIENT_AUTH` is moved into `f | help: Install `apache-airflow-providers-fab>=1.0.0` and use `CLIENT_AUTH` from `airflow.providers.fab.auth_manager.api.auth.backend.kerberos_auth` instead. | -15 | from airflow.api.auth.backend.kerberos_auth import ( - - CLIENT_AUTH, -16 | find_user, --------------------------------------------------------------------------------- -20 | ) +15 + from airflow.api.auth.backend.kerberos_auth import ( +16 + find_user, +17 + init_app, +18 + log, +19 + requires_authentication, +20 + ) 21 + from airflow.providers.fab.auth_manager.api.auth.backend.kerberos_auth import CLIENT_AUTH -22 | | note: This is an unsafe fix and may change runtime behavior @@ -139,14 +138,13 @@ AIR302 [*] `airflow.api.auth.backend.kerberos_auth.find_user` is moved into `fab | help: Install `apache-airflow-providers-fab>=1.0.0` and use `find_user` from `airflow.providers.fab.auth_manager.api.auth.backend.kerberos_auth` instead. | -16 | CLIENT_AUTH, - - find_user, -17 | init_app, -18 | log, -19 | requires_authentication, -20 | ) +15 + from airflow.api.auth.backend.kerberos_auth import ( +16 + CLIENT_AUTH, +17 + init_app, +18 + log, +19 + requires_authentication, +20 + ) 21 + from airflow.providers.fab.auth_manager.api.auth.backend.kerberos_auth import find_user -22 | | note: This is an unsafe fix and may change runtime behavior @@ -161,13 +159,13 @@ AIR302 [*] `airflow.api.auth.backend.kerberos_auth.init_app` is moved into `fab` | help: Install `apache-airflow-providers-fab>=1.0.0` and use `init_app` from `airflow.providers.fab.auth_manager.api.auth.backend.kerberos_auth` instead. | -17 | find_user, - - init_app, -18 | log, -19 | requires_authentication, -20 | ) +15 + from airflow.api.auth.backend.kerberos_auth import ( +16 + CLIENT_AUTH, +17 + find_user, +18 + log, +19 + requires_authentication, +20 + ) 21 + from airflow.providers.fab.auth_manager.api.auth.backend.kerberos_auth import init_app -22 | | note: This is an unsafe fix and may change runtime behavior @@ -183,11 +181,13 @@ AIR302 [*] `airflow.api.auth.backend.kerberos_auth.requires_authentication` is m | help: Install `apache-airflow-providers-fab>=1.0.0` and use `requires_authentication` from `airflow.providers.fab.auth_manager.api.auth.backend.kerberos_auth` instead. | -19 | log, - - requires_authentication, -20 | ) +15 + from airflow.api.auth.backend.kerberos_auth import ( +16 + CLIENT_AUTH, +17 + find_user, +18 + init_app, +19 + log, +20 + ) 21 + from airflow.providers.fab.auth_manager.api.auth.backend.kerberos_auth import requires_authentication -22 | | note: This is an unsafe fix and may change runtime behavior @@ -203,12 +203,13 @@ AIR302 [*] `airflow.auth.managers.fab.api.auth.backend.kerberos_auth.log` is mov | help: Install `apache-airflow-providers-fab>=1.0.0` and use `log` from `airflow.providers.fab.auth_manager.api.auth.backend.kerberos_auth` instead. | -32 | init_app, - - log, -33 | requires_authentication, -34 | ) +29 + from airflow.auth.managers.fab.api.auth.backend.kerberos_auth import ( +30 + CLIENT_AUTH, +31 + find_user, +32 + init_app, +33 + requires_authentication, +34 + ) 35 + from airflow.providers.fab.auth_manager.api.auth.backend.kerberos_auth import log -36 | | note: This is an unsafe fix and may change runtime behavior @@ -223,13 +224,13 @@ AIR302 [*] `airflow.auth.managers.fab.api.auth.backend.kerberos_auth.CLIENT_AUTH | help: Install `apache-airflow-providers-fab>=1.0.0` and use `CLIENT_AUTH` from `airflow.providers.fab.auth_manager.api.auth.backend.kerberos_auth` instead. | -29 | from airflow.auth.managers.fab.api.auth.backend.kerberos_auth import ( - - CLIENT_AUTH, -30 | find_user, --------------------------------------------------------------------------------- -34 | ) +29 + from airflow.auth.managers.fab.api.auth.backend.kerberos_auth import ( +30 + find_user, +31 + init_app, +32 + log, +33 + requires_authentication, +34 + ) 35 + from airflow.providers.fab.auth_manager.api.auth.backend.kerberos_auth import CLIENT_AUTH -36 | | note: This is an unsafe fix and may change runtime behavior @@ -245,14 +246,13 @@ AIR302 [*] `airflow.auth.managers.fab.api.auth.backend.kerberos_auth.find_user` | help: Install `apache-airflow-providers-fab>=1.0.0` and use `find_user` from `airflow.providers.fab.auth_manager.api.auth.backend.kerberos_auth` instead. | -30 | CLIENT_AUTH, - - find_user, -31 | init_app, -32 | log, -33 | requires_authentication, -34 | ) +29 + from airflow.auth.managers.fab.api.auth.backend.kerberos_auth import ( +30 + CLIENT_AUTH, +31 + init_app, +32 + log, +33 + requires_authentication, +34 + ) 35 + from airflow.providers.fab.auth_manager.api.auth.backend.kerberos_auth import find_user -36 | | note: This is an unsafe fix and may change runtime behavior @@ -267,13 +267,13 @@ AIR302 [*] `airflow.auth.managers.fab.api.auth.backend.kerberos_auth.init_app` i | help: Install `apache-airflow-providers-fab>=1.0.0` and use `init_app` from `airflow.providers.fab.auth_manager.api.auth.backend.kerberos_auth` instead. | -31 | find_user, - - init_app, -32 | log, -33 | requires_authentication, -34 | ) +29 + from airflow.auth.managers.fab.api.auth.backend.kerberos_auth import ( +30 + CLIENT_AUTH, +31 + find_user, +32 + log, +33 + requires_authentication, +34 + ) 35 + from airflow.providers.fab.auth_manager.api.auth.backend.kerberos_auth import init_app -36 | | note: This is an unsafe fix and may change runtime behavior @@ -289,11 +289,13 @@ AIR302 [*] `airflow.auth.managers.fab.api.auth.backend.kerberos_auth.requires_au | help: Install `apache-airflow-providers-fab>=1.0.0` and use `requires_authentication` from `airflow.providers.fab.auth_manager.api.auth.backend.kerberos_auth` instead. | -33 | log, - - requires_authentication, -34 | ) +29 + from airflow.auth.managers.fab.api.auth.backend.kerberos_auth import ( +30 + CLIENT_AUTH, +31 + find_user, +32 + init_app, +33 + log, +34 + ) 35 + from airflow.providers.fab.auth_manager.api.auth.backend.kerberos_auth import requires_authentication -36 | | note: This is an unsafe fix and may change runtime behavior @@ -309,14 +311,11 @@ AIR302 [*] `airflow.auth.managers.fab.fab_auth_manager.FabAuthManager` is moved | help: Install `apache-airflow-providers-fab>=1.0.0` and use `FabAuthManager` from `airflow.providers.fab.auth_manager.fab_auth_manager` instead. | -42 | - - from airflow.auth.managers.fab.fab_auth_manager import FabAuthManager -43 | from airflow.auth.managers.fab.security_manager.override import ( -44 | MAX_NUM_DATABASE_USER_SESSIONS, -45 | FabAirflowSecurityManagerOverride, -46 | ) -47 + from airflow.providers.fab.auth_manager.fab_auth_manager import FabAuthManager -48 | +43 + +44 | from airflow.auth.managers.fab.security_manager.override import ( + … +47 | ) +48 + from airflow.providers.fab.auth_manager.fab_auth_manager import FabAuthManager | note: This is an unsafe fix and may change runtime behavior @@ -330,12 +329,10 @@ AIR302 [*] `airflow.auth.managers.fab.security_manager.override.MAX_NUM_DATABASE | help: Install `apache-airflow-providers-fab>=1.0.0` and use `MAX_NUM_DATABASE_USER_SESSIONS` from `airflow.providers.fab.auth_manager.security_manager.override` instead. | -44 | from airflow.auth.managers.fab.security_manager.override import ( - - MAX_NUM_DATABASE_USER_SESSIONS, -45 | FabAirflowSecurityManagerOverride, -46 | ) +44 + from airflow.auth.managers.fab.security_manager.override import ( +45 + FabAirflowSecurityManagerOverride, +46 + ) 47 + from airflow.providers.fab.auth_manager.security_manager.override import MAX_NUM_DATABASE_USER_SESSIONS -48 | | note: This is an unsafe fix and may change runtime behavior @@ -351,11 +348,10 @@ AIR302 [*] `airflow.auth.managers.fab.security_manager.override.FabAirflowSecuri | help: Install `apache-airflow-providers-fab>=1.0.0` and use `FabAirflowSecurityManagerOverride` from `airflow.providers.fab.auth_manager.security_manager.override` instead. | -45 | MAX_NUM_DATABASE_USER_SESSIONS, - - FabAirflowSecurityManagerOverride, -46 | ) +44 + from airflow.auth.managers.fab.security_manager.override import ( +45 + MAX_NUM_DATABASE_USER_SESSIONS, +46 + ) 47 + from airflow.providers.fab.auth_manager.security_manager.override import FabAirflowSecurityManagerOverride -48 | | note: This is an unsafe fix and may change runtime behavior @@ -368,9 +364,7 @@ AIR302 [*] `airflow.www.security.FabAirflowSecurityManagerOverride` is moved int | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Install `apache-airflow-providers-fab>=1.0.0` and use `FabAirflowSecurityManagerOverride` from `airflow.providers.fab.auth_manager.security_manager.override` instead. | -52 | - - from airflow.www.security import FabAirflowSecurityManagerOverride -53 + from airflow.providers.fab.auth_manager.security_manager.override import FabAirflowSecurityManagerOverride -54 | +53 + +54 + from airflow.providers.fab.auth_manager.security_manager.override import FabAirflowSecurityManagerOverride | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_hdfs.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_hdfs.py.snap index d0b17d61c46a2..04de98d7c435c 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_hdfs.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_hdfs.py.snap @@ -12,11 +12,9 @@ AIR302 [*] `airflow.hooks.webhdfs_hook.WebHDFSHook` is moved into `apache-hdfs` | help: Install `apache-airflow-providers-apache-hdfs>=1.0.0` and use `WebHDFSHook` from `airflow.providers.apache.hdfs.hooks.webhdfs` instead. | -2 | - - from airflow.hooks.webhdfs_hook import WebHDFSHook -3 | from airflow.sensors.web_hdfs_sensor import WebHdfsSensor -4 + from airflow.providers.apache.hdfs.hooks.webhdfs import WebHDFSHook -5 | +3 + +4 | from airflow.sensors.web_hdfs_sensor import WebHdfsSensor +5 + from airflow.providers.apache.hdfs.hooks.webhdfs import WebHDFSHook | note: This is an unsafe fix and may change runtime behavior @@ -28,9 +26,7 @@ AIR302 [*] `airflow.sensors.web_hdfs_sensor.WebHdfsSensor` is moved into `apache | ^^^^^^^^^^^^^ help: Install `apache-airflow-providers-apache-hdfs>=1.0.0` and use `WebHdfsSensor` from `airflow.providers.apache.hdfs.sensors.web_hdfs` instead. | -3 | from airflow.hooks.webhdfs_hook import WebHDFSHook - - from airflow.sensors.web_hdfs_sensor import WebHdfsSensor -4 + from airflow.providers.apache.hdfs.sensors.web_hdfs import WebHdfsSensor -5 | +4 + +5 + from airflow.providers.apache.hdfs.sensors.web_hdfs import WebHdfsSensor | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_hive.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_hive.py.snap index 9ea949fabf828..23a294eb40863 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_hive.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_hive.py.snap @@ -13,13 +13,15 @@ AIR302 [*] `airflow.hooks.hive_hooks.HIVE_QUEUE_PRIORITIES` is moved into `apach | help: Install `apache-airflow-providers-apache-hive>=1.0.0` and use `HIVE_QUEUE_PRIORITIES` from `airflow.providers.apache.hive.hooks.hive` instead. | -3 | from airflow.hooks.hive_hooks import ( - - HIVE_QUEUE_PRIORITIES, -4 | HiveCliHook, --------------------------------------------------------------------------------- + 3 + from airflow.hooks.hive_hooks import ( + 4 + HiveCliHook, + 5 + HiveMetastoreHook, + 6 + HiveServer2Hook, + 7 + ) + 8 | from airflow.macros.hive import ( + … 15 | from airflow.operators.hive_to_samba_operator import HiveToSambaOperator 16 + from airflow.providers.apache.hive.hooks.hive import HIVE_QUEUE_PRIORITIES -17 | | note: This is an unsafe fix and may change runtime behavior @@ -34,13 +36,15 @@ AIR302 [*] `airflow.hooks.hive_hooks.HiveCliHook` is moved into `apache-hive` pr | help: Install `apache-airflow-providers-apache-hive>=1.0.0` and use `HiveCliHook` from `airflow.providers.apache.hive.hooks.hive` instead. | -4 | HIVE_QUEUE_PRIORITIES, - - HiveCliHook, -5 | HiveMetastoreHook, --------------------------------------------------------------------------------- + 3 + from airflow.hooks.hive_hooks import ( + 4 + HIVE_QUEUE_PRIORITIES, + 5 + HiveMetastoreHook, + 6 + HiveServer2Hook, + 7 + ) + 8 | from airflow.macros.hive import ( + … 15 | from airflow.operators.hive_to_samba_operator import HiveToSambaOperator 16 + from airflow.providers.apache.hive.hooks.hive import HiveCliHook -17 | | note: This is an unsafe fix and may change runtime behavior @@ -55,13 +59,15 @@ AIR302 [*] `airflow.hooks.hive_hooks.HiveMetastoreHook` is moved into `apache-hi | help: Install `apache-airflow-providers-apache-hive>=1.0.0` and use `HiveMetastoreHook` from `airflow.providers.apache.hive.hooks.hive` instead. | -5 | HiveCliHook, - - HiveMetastoreHook, -6 | HiveServer2Hook, --------------------------------------------------------------------------------- + 3 + from airflow.hooks.hive_hooks import ( + 4 + HIVE_QUEUE_PRIORITIES, + 5 + HiveCliHook, + 6 + HiveServer2Hook, + 7 + ) + 8 | from airflow.macros.hive import ( + … 15 | from airflow.operators.hive_to_samba_operator import HiveToSambaOperator 16 + from airflow.providers.apache.hive.hooks.hive import HiveMetastoreHook -17 | | note: This is an unsafe fix and may change runtime behavior @@ -77,13 +83,15 @@ AIR302 [*] `airflow.hooks.hive_hooks.HiveServer2Hook` is moved into `apache-hive | help: Install `apache-airflow-providers-apache-hive>=1.0.0` and use `HiveServer2Hook` from `airflow.providers.apache.hive.hooks.hive` instead. | -6 | HiveMetastoreHook, - - HiveServer2Hook, -7 | ) --------------------------------------------------------------------------------- + 3 + from airflow.hooks.hive_hooks import ( + 4 + HIVE_QUEUE_PRIORITIES, + 5 + HiveCliHook, + 6 + HiveMetastoreHook, + 7 + ) + 8 | from airflow.macros.hive import ( + … 15 | from airflow.operators.hive_to_samba_operator import HiveToSambaOperator 16 + from airflow.providers.apache.hive.hooks.hive import HiveServer2Hook -17 | | note: This is an unsafe fix and may change runtime behavior @@ -98,13 +106,13 @@ AIR302 [*] `airflow.macros.hive.closest_ds_partition` is moved into `apache-hive | help: Install `apache-airflow-providers-apache-hive>=5.1.0` and use `closest_ds_partition` from `airflow.providers.apache.hive.macros.hive` instead. | -9 | from airflow.macros.hive import ( - - closest_ds_partition, -10 | max_partition, --------------------------------------------------------------------------------- + 9 + from airflow.macros.hive import ( +10 + max_partition, +11 + ) +12 | from airflow.operators.hive_operator import HiveOperator + … 15 | from airflow.operators.hive_to_samba_operator import HiveToSambaOperator 16 + from airflow.providers.apache.hive.macros.hive import closest_ds_partition -17 | | note: This is an unsafe fix and may change runtime behavior @@ -119,13 +127,13 @@ AIR302 [*] `airflow.macros.hive.max_partition` is moved into `apache-hive` provi | help: Install `apache-airflow-providers-apache-hive>=5.1.0` and use `max_partition` from `airflow.providers.apache.hive.macros.hive` instead. | -10 | closest_ds_partition, - - max_partition, -11 | ) --------------------------------------------------------------------------------- + 9 + from airflow.macros.hive import ( +10 + closest_ds_partition, +11 + ) +12 | from airflow.operators.hive_operator import HiveOperator + … 15 | from airflow.operators.hive_to_samba_operator import HiveToSambaOperator 16 + from airflow.providers.apache.hive.macros.hive import max_partition -17 | | note: This is an unsafe fix and may change runtime behavior @@ -141,13 +149,11 @@ AIR302 [*] `airflow.operators.hive_operator.HiveOperator` is moved into `apache- | help: Install `apache-airflow-providers-apache-hive>=1.0.0` and use `HiveOperator` from `airflow.providers.apache.hive.operators.hive` instead. | -12 | ) - - from airflow.operators.hive_operator import HiveOperator -13 | from airflow.operators.hive_stats_operator import HiveStatsCollectionOperator -14 | from airflow.operators.hive_to_mysql import HiveToMySqlOperator -15 | from airflow.operators.hive_to_samba_operator import HiveToSambaOperator -16 + from airflow.providers.apache.hive.operators.hive import HiveOperator -17 | +13 + +14 | from airflow.operators.hive_stats_operator import HiveStatsCollectionOperator +15 | from airflow.operators.hive_to_mysql import HiveToMySqlOperator +16 | from airflow.operators.hive_to_samba_operator import HiveToSambaOperator +17 + from airflow.providers.apache.hive.operators.hive import HiveOperator | note: This is an unsafe fix and may change runtime behavior @@ -162,12 +168,10 @@ AIR302 [*] `airflow.operators.hive_stats_operator.HiveStatsCollectionOperator` i | help: Install `apache-airflow-providers-apache-hive>=1.0.0` and use `HiveStatsCollectionOperator` from `airflow.providers.apache.hive.operators.hive_stats` instead. | -13 | from airflow.operators.hive_operator import HiveOperator - - from airflow.operators.hive_stats_operator import HiveStatsCollectionOperator -14 | from airflow.operators.hive_to_mysql import HiveToMySqlOperator -15 | from airflow.operators.hive_to_samba_operator import HiveToSambaOperator -16 + from airflow.providers.apache.hive.operators.hive_stats import HiveStatsCollectionOperator -17 | +14 + +15 | from airflow.operators.hive_to_mysql import HiveToMySqlOperator +16 | from airflow.operators.hive_to_samba_operator import HiveToSambaOperator +17 + from airflow.providers.apache.hive.operators.hive_stats import HiveStatsCollectionOperator | note: This is an unsafe fix and may change runtime behavior @@ -182,11 +186,9 @@ AIR302 [*] `airflow.operators.hive_to_mysql.HiveToMySqlOperator` is moved into ` | help: Install `apache-airflow-providers-apache-hive>=1.0.0` and use `HiveToMySqlOperator` from `airflow.providers.apache.hive.transfers.hive_to_mysql` instead. | -14 | from airflow.operators.hive_stats_operator import HiveStatsCollectionOperator - - from airflow.operators.hive_to_mysql import HiveToMySqlOperator -15 | from airflow.operators.hive_to_samba_operator import HiveToSambaOperator -16 + from airflow.providers.apache.hive.transfers.hive_to_mysql import HiveToMySqlOperator -17 | +15 + +16 | from airflow.operators.hive_to_samba_operator import HiveToSambaOperator +17 + from airflow.providers.apache.hive.transfers.hive_to_mysql import HiveToMySqlOperator | note: This is an unsafe fix and may change runtime behavior @@ -199,10 +201,8 @@ AIR302 [*] `airflow.operators.hive_to_samba_operator.HiveToSambaOperator` is mov | ^^^^^^^^^^^^^^^^^^^ help: Install `apache-airflow-providers-apache-hive>=1.0.0` and use `HiveToSambaOperator` from `airflow.providers.apache.hive.transfers.hive_to_samba` instead. | -15 | from airflow.operators.hive_to_mysql import HiveToMySqlOperator - - from airflow.operators.hive_to_samba_operator import HiveToSambaOperator -16 + from airflow.providers.apache.hive.transfers.hive_to_samba import HiveToSambaOperator -17 | +16 + +17 + from airflow.providers.apache.hive.transfers.hive_to_samba import HiveToSambaOperator | note: This is an unsafe fix and may change runtime behavior @@ -218,9 +218,8 @@ AIR302 [*] `airflow.operators.hive_to_mysql.HiveToMySqlTransfer` is moved into ` | help: Install `apache-airflow-providers-apache-hive>=1.0.0` and use `HiveToMySqlOperator` from `airflow.providers.apache.hive.transfers.hive_to_mysql` instead. | -32 | from airflow.operators.hive_to_mysql import HiveToMySqlTransfer +32 ~ from airflow.operators.hive_to_mysql import HiveToMySqlTransfer 33 + from airflow.providers.apache.hive.transfers.hive_to_mysql import HiveToMySqlOperator -34 | | note: This is an unsafe fix and may change runtime behavior @@ -236,10 +235,8 @@ AIR302 [*] `airflow.operators.mysql_to_hive.MySqlToHiveOperator` is moved into ` | help: Install `apache-airflow-providers-apache-hive>=1.0.0` and use `MySqlToHiveOperator` from `airflow.providers.apache.hive.transfers.mysql_to_hive` instead. | -35 | - - from airflow.operators.mysql_to_hive import MySqlToHiveOperator -36 + from airflow.providers.apache.hive.transfers.mysql_to_hive import MySqlToHiveOperator -37 | +36 + +37 + from airflow.providers.apache.hive.transfers.mysql_to_hive import MySqlToHiveOperator | note: This is an unsafe fix and may change runtime behavior @@ -255,9 +252,8 @@ AIR302 [*] `airflow.operators.mysql_to_hive.MySqlToHiveTransfer` is moved into ` | help: Install `apache-airflow-providers-apache-hive>=1.0.0` and use `MySqlToHiveOperator` from `airflow.providers.apache.hive.transfers.mysql_to_hive` instead. | -40 | from airflow.operators.mysql_to_hive import MySqlToHiveTransfer +40 ~ from airflow.operators.mysql_to_hive import MySqlToHiveTransfer 41 + from airflow.providers.apache.hive.transfers.mysql_to_hive import MySqlToHiveOperator -42 | | note: This is an unsafe fix and may change runtime behavior @@ -273,10 +269,8 @@ AIR302 [*] `airflow.operators.mssql_to_hive.MsSqlToHiveOperator` is moved into ` | help: Install `apache-airflow-providers-apache-hive>=1.0.0` and use `MsSqlToHiveOperator` from `airflow.providers.apache.hive.transfers.mssql_to_hive` instead. | -43 | - - from airflow.operators.mssql_to_hive import MsSqlToHiveOperator -44 + from airflow.providers.apache.hive.transfers.mssql_to_hive import MsSqlToHiveOperator -45 | +44 + +45 + from airflow.providers.apache.hive.transfers.mssql_to_hive import MsSqlToHiveOperator | note: This is an unsafe fix and may change runtime behavior @@ -292,9 +286,8 @@ AIR302 [*] `airflow.operators.mssql_to_hive.MsSqlToHiveTransfer` is moved into ` | help: Install `apache-airflow-providers-apache-hive>=1.0.0` and use `MsSqlToHiveOperator` from `airflow.providers.apache.hive.transfers.mssql_to_hive` instead. | -48 | from airflow.operators.mssql_to_hive import MsSqlToHiveTransfer +48 ~ from airflow.operators.mssql_to_hive import MsSqlToHiveTransfer 49 + from airflow.providers.apache.hive.transfers.mssql_to_hive import MsSqlToHiveOperator -50 | | note: This is an unsafe fix and may change runtime behavior @@ -310,10 +303,8 @@ AIR302 [*] `airflow.operators.s3_to_hive_operator.S3ToHiveOperator` is moved int | help: Install `apache-airflow-providers-apache-hive>=1.0.0` and use `S3ToHiveOperator` from `airflow.providers.apache.hive.transfers.s3_to_hive` instead. | -51 | - - from airflow.operators.s3_to_hive_operator import S3ToHiveOperator -52 + from airflow.providers.apache.hive.transfers.s3_to_hive import S3ToHiveOperator -53 | +52 + +53 + from airflow.providers.apache.hive.transfers.s3_to_hive import S3ToHiveOperator | note: This is an unsafe fix and may change runtime behavior @@ -329,9 +320,8 @@ AIR302 [*] `airflow.operators.s3_to_hive_operator.S3ToHiveTransfer` is moved int | help: Install `apache-airflow-providers-apache-hive>=1.0.0` and use `S3ToHiveOperator` from `airflow.providers.apache.hive.transfers.s3_to_hive` instead. | -56 | from airflow.operators.s3_to_hive_operator import S3ToHiveTransfer +56 ~ from airflow.operators.s3_to_hive_operator import S3ToHiveTransfer 57 + from airflow.providers.apache.hive.transfers.s3_to_hive import S3ToHiveOperator -58 | | note: This is an unsafe fix and may change runtime behavior @@ -347,10 +337,8 @@ AIR302 [*] `airflow.sensors.hive_partition_sensor.HivePartitionSensor` is moved | help: Install `apache-airflow-providers-apache-hive>=1.0.0` and use `HivePartitionSensor` from `airflow.providers.apache.hive.sensors.hive_partition` instead. | -59 | - - from airflow.sensors.hive_partition_sensor import HivePartitionSensor -60 + from airflow.providers.apache.hive.sensors.hive_partition import HivePartitionSensor -61 | +60 + +61 + from airflow.providers.apache.hive.sensors.hive_partition import HivePartitionSensor | note: This is an unsafe fix and may change runtime behavior @@ -366,10 +354,8 @@ AIR302 [*] `airflow.sensors.metastore_partition_sensor.MetastorePartitionSensor` | help: Install `apache-airflow-providers-apache-hive>=1.0.0` and use `MetastorePartitionSensor` from `airflow.providers.apache.hive.sensors.metastore_partition` instead. | -63 | - - from airflow.sensors.metastore_partition_sensor import MetastorePartitionSensor -64 + from airflow.providers.apache.hive.sensors.metastore_partition import MetastorePartitionSensor -65 | +64 + +65 + from airflow.providers.apache.hive.sensors.metastore_partition import MetastorePartitionSensor | note: This is an unsafe fix and may change runtime behavior @@ -382,9 +368,7 @@ AIR302 [*] `airflow.sensors.named_hive_partition_sensor.NamedHivePartitionSensor | ^^^^^^^^^^^^^^^^^^^^^^^^ help: Install `apache-airflow-providers-apache-hive>=1.0.0` and use `NamedHivePartitionSensor` from `airflow.providers.apache.hive.sensors.named_hive_partition` instead. | -67 | - - from airflow.sensors.named_hive_partition_sensor import NamedHivePartitionSensor -68 + from airflow.providers.apache.hive.sensors.named_hive_partition import NamedHivePartitionSensor -69 | +68 + +69 + from airflow.providers.apache.hive.sensors.named_hive_partition import NamedHivePartitionSensor | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_http.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_http.py.snap index e14dae880c204..b398e1460668c 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_http.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_http.py.snap @@ -13,12 +13,10 @@ AIR302 [*] `airflow.hooks.http_hook.HttpHook` is moved into `http` provider in A | help: Install `apache-airflow-providers-http>=1.0.0` and use `HttpHook` from `airflow.providers.http.hooks.http` instead. | -2 | - - from airflow.hooks.http_hook import HttpHook -3 | from airflow.operators.http_operator import SimpleHttpOperator -4 | from airflow.sensors.http_sensor import HttpSensor -5 + from airflow.providers.http.hooks.http import HttpHook -6 | +3 + +4 | from airflow.operators.http_operator import SimpleHttpOperator +5 | from airflow.sensors.http_sensor import HttpSensor +6 + from airflow.providers.http.hooks.http import HttpHook | note: This is an unsafe fix and may change runtime behavior @@ -31,15 +29,12 @@ AIR302 [*] `airflow.operators.http_operator.SimpleHttpOperator` is moved into `h 9 | HttpSensor() | help: Install `apache-airflow-providers-http>=5.0.0` and use `HttpOperator` from `airflow.providers.http.operators.http` instead. - | -5 | from airflow.sensors.http_sensor import HttpSensor -6 + from airflow.providers.http.operators.http import HttpOperator -7 | -8 | HttpHook() - - SimpleHttpOperator() -9 + HttpOperator() -10 | HttpSensor() - | + | +6 + from airflow.providers.http.operators.http import HttpOperator +7 + +8 | HttpHook() +9 ~ HttpOperator() + | AIR302 [*] `airflow.sensors.http_sensor.HttpSensor` is moved into `http` provider in Airflow 3.0; --> AIR302_http.py:9:1 @@ -50,9 +45,7 @@ AIR302 [*] `airflow.sensors.http_sensor.HttpSensor` is moved into `http` provide | ^^^^^^^^^^ help: Install `apache-airflow-providers-http>=1.0.0` and use `HttpSensor` from `airflow.providers.http.sensors.http` instead. | -4 | from airflow.operators.http_operator import SimpleHttpOperator - - from airflow.sensors.http_sensor import HttpSensor -5 + from airflow.providers.http.sensors.http import HttpSensor -6 | +5 + +6 + from airflow.providers.http.sensors.http import HttpSensor | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_jdbc.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_jdbc.py.snap index d488b793b5cd5..a9a7e2aa5afde 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_jdbc.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_jdbc.py.snap @@ -12,12 +12,10 @@ AIR302 [*] `airflow.hooks.jdbc_hook.JdbcHook` is moved into `jdbc` provider in A | help: Install `apache-airflow-providers-jdbc>=1.0.0` and use `JdbcHook` from `airflow.providers.jdbc.hooks.jdbc` instead. | -3 | from airflow.hooks.jdbc_hook import ( - - JdbcHook, -4 | jaydebeapi, -5 | ) +3 + from airflow.hooks.jdbc_hook import ( +4 + jaydebeapi, +5 + ) 6 + from airflow.providers.jdbc.hooks.jdbc import JdbcHook -7 | | note: This is an unsafe fix and may change runtime behavior @@ -29,10 +27,9 @@ AIR302 [*] `airflow.hooks.jdbc_hook.jaydebeapi` is moved into `jdbc` provider in | ^^^^^^^^^^ help: Install `apache-airflow-providers-jdbc>=1.0.0` and use `jaydebeapi` from `airflow.providers.jdbc.hooks.jdbc` instead. | -4 | JdbcHook, - - jaydebeapi, -5 | ) +3 + from airflow.hooks.jdbc_hook import ( +4 + JdbcHook, +5 + ) 6 + from airflow.providers.jdbc.hooks.jdbc import jaydebeapi -7 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_kubernetes.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_kubernetes.py.snap index 749fc444ffc70..f4015b6fd8a69 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_kubernetes.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_kubernetes.py.snap @@ -12,13 +12,13 @@ AIR302 [*] `airflow.executors.kubernetes_executor_types.ALL_NAMESPACES` is moved | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `ALL_NAMESPACES` from `airflow.providers.cncf.kubernetes.executors.kubernetes_executor_types` instead. | -3 | from airflow.executors.kubernetes_executor_types import ( - - ALL_NAMESPACES, -4 | POD_EXECUTOR_DONE_KEY, --------------------------------------------------------------------------------- + 3 + from airflow.executors.kubernetes_executor_types import ( + 4 + POD_EXECUTOR_DONE_KEY, + 5 + ) + 6 | from airflow.kubernetes.k8s_model import ( + … 19 | ) 20 + from airflow.providers.cncf.kubernetes.executors.kubernetes_executor_types import ALL_NAMESPACES -21 | | note: This is an unsafe fix and may change runtime behavior @@ -33,13 +33,13 @@ AIR302 [*] `airflow.executors.kubernetes_executor_types.POD_EXECUTOR_DONE_KEY` i | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `POD_EXECUTOR_DONE_KEY` from `airflow.providers.cncf.kubernetes.executors.kubernetes_executor_types` instead. | -4 | ALL_NAMESPACES, - - POD_EXECUTOR_DONE_KEY, -5 | ) --------------------------------------------------------------------------------- + 3 + from airflow.executors.kubernetes_executor_types import ( + 4 + ALL_NAMESPACES, + 5 + ) + 6 | from airflow.kubernetes.k8s_model import ( + … 19 | ) 20 + from airflow.providers.cncf.kubernetes.executors.kubernetes_executor_types import POD_EXECUTOR_DONE_KEY -21 | | note: This is an unsafe fix and may change runtime behavior @@ -54,13 +54,13 @@ AIR302 [*] `airflow.kubernetes.k8s_model.K8SModel` is moved into `cncf-kubernete | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `K8SModel` from `airflow.providers.cncf.kubernetes.k8s_model` instead. | -7 | from airflow.kubernetes.k8s_model import ( - - K8SModel, -8 | append_to_pod, --------------------------------------------------------------------------------- + 7 + from airflow.kubernetes.k8s_model import ( + 8 + append_to_pod, + 9 + ) +10 | from airflow.kubernetes.kube_client import ( + … 19 | ) 20 + from airflow.providers.cncf.kubernetes.k8s_model import K8SModel -21 | | note: This is an unsafe fix and may change runtime behavior @@ -75,13 +75,13 @@ AIR302 [*] `airflow.kubernetes.k8s_model.append_to_pod` is moved into `cncf-kube | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `append_to_pod` from `airflow.providers.cncf.kubernetes.k8s_model` instead. | -8 | K8SModel, - - append_to_pod, -9 | ) --------------------------------------------------------------------------------- + 7 + from airflow.kubernetes.k8s_model import ( + 8 + K8SModel, + 9 + ) +10 | from airflow.kubernetes.kube_client import ( + … 19 | ) 20 + from airflow.providers.cncf.kubernetes.k8s_model import append_to_pod -21 | | note: This is an unsafe fix and may change runtime behavior @@ -97,13 +97,14 @@ AIR302 [*] `airflow.kubernetes.kube_client._disable_verify_ssl` is moved into `c | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `_disable_verify_ssl` from `airflow.providers.cncf.kubernetes.kube_client` instead. | -11 | from airflow.kubernetes.kube_client import ( - - _disable_verify_ssl, -12 | _enable_tcp_keepalive, --------------------------------------------------------------------------------- +11 + from airflow.kubernetes.kube_client import ( +12 + _enable_tcp_keepalive, +13 + get_kube_client, +14 + ) +15 | from airflow.kubernetes.kubernetes_helper_functions import ( + … 19 | ) 20 + from airflow.providers.cncf.kubernetes.kube_client import _disable_verify_ssl -21 | | note: This is an unsafe fix and may change runtime behavior @@ -117,13 +118,14 @@ AIR302 [*] `airflow.kubernetes.kube_client._enable_tcp_keepalive` is moved into | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `_enable_tcp_keepalive` from `airflow.providers.cncf.kubernetes.kube_client` instead. | -12 | _disable_verify_ssl, - - _enable_tcp_keepalive, -13 | get_kube_client, --------------------------------------------------------------------------------- +11 + from airflow.kubernetes.kube_client import ( +12 + _disable_verify_ssl, +13 + get_kube_client, +14 + ) +15 | from airflow.kubernetes.kubernetes_helper_functions import ( + … 19 | ) 20 + from airflow.providers.cncf.kubernetes.kube_client import _enable_tcp_keepalive -21 | | note: This is an unsafe fix and may change runtime behavior @@ -139,13 +141,14 @@ AIR302 [*] `airflow.kubernetes.kube_client.get_kube_client` is moved into `cncf- | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `get_kube_client` from `airflow.providers.cncf.kubernetes.kube_client` instead. | -13 | _enable_tcp_keepalive, - - get_kube_client, -14 | ) --------------------------------------------------------------------------------- +11 + from airflow.kubernetes.kube_client import ( +12 + _disable_verify_ssl, +13 + _enable_tcp_keepalive, +14 + ) +15 | from airflow.kubernetes.kubernetes_helper_functions import ( + … 19 | ) 20 + from airflow.providers.cncf.kubernetes.kube_client import get_kube_client -21 | | note: This is an unsafe fix and may change runtime behavior @@ -161,14 +164,12 @@ AIR302 [*] `airflow.kubernetes.kubernetes_helper_functions.add_pod_suffix` is mo | help: Install `apache-airflow-providers-cncf-kubernetes>=10.0.0` and use `add_unique_suffix` from `airflow.providers.cncf.kubernetes.kubernetes_helper_functions` instead. | -20 | ) 21 + from airflow.providers.cncf.kubernetes.kubernetes_helper_functions import add_unique_suffix -22 | --------------------------------------------------------------------------------- +22 + +23 | ALL_NAMESPACES + … 32 | - - add_pod_suffix() -33 + add_unique_suffix() -34 | annotations_for_logging_task_metadata() +33 ~ add_unique_suffix() | AIR302 [*] `airflow.kubernetes.kubernetes_helper_functions.annotations_for_logging_task_metadata` is moved into `cncf-kubernetes` provider in Airflow 3.0; @@ -181,12 +182,11 @@ AIR302 [*] `airflow.kubernetes.kubernetes_helper_functions.annotations_for_loggi | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `annotations_for_logging_task_metadata` from `airflow.providers.cncf.kubernetes.kubernetes_helper_functions` instead. | -17 | add_pod_suffix, - - annotations_for_logging_task_metadata, -18 | create_pod_id, -19 | ) +16 + from airflow.kubernetes.kubernetes_helper_functions import ( +17 + add_pod_suffix, +18 + create_pod_id, +19 + ) 20 + from airflow.providers.cncf.kubernetes.kubernetes_helper_functions import annotations_for_logging_task_metadata -21 | | note: This is an unsafe fix and may change runtime behavior @@ -199,14 +199,12 @@ AIR302 [*] `airflow.kubernetes.kubernetes_helper_functions.create_pod_id` is mov | ^^^^^^^^^^^^^ help: Install `apache-airflow-providers-cncf-kubernetes>=10.0.0` and use `create_unique_id` from `airflow.providers.cncf.kubernetes.kubernetes_helper_functions` instead. | -20 | ) 21 + from airflow.providers.cncf.kubernetes.kubernetes_helper_functions import create_unique_id -22 | --------------------------------------------------------------------------------- +22 + +23 | ALL_NAMESPACES + … 34 | annotations_for_logging_task_metadata() - - create_pod_id() -35 + create_unique_id() -36 | +35 ~ create_unique_id() | AIR302 [*] `airflow.kubernetes.pod_generator.PodDefaults` is moved into `cncf-kubernetes` provider in Airflow 3.0; @@ -221,13 +219,17 @@ AIR302 [*] `airflow.kubernetes.pod_generator.PodDefaults` is moved into `cncf-ku | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `PodDefaults` from `airflow.providers.cncf.kubernetes.utils.xcom_sidecar` instead. | -37 | from airflow.kubernetes.pod_generator import ( - - PodDefaults, -38 | PodGenerator, --------------------------------------------------------------------------------- -46 | ) +37 + from airflow.kubernetes.pod_generator import ( +38 + PodGenerator, +39 + add_pod_suffix, +40 + datetime_to_label_safe_datestring, +41 + extend_object_field, +42 + label_safe_datestring_to_datetime, +43 + make_safe_label_value, +44 + merge_objects, +45 + rand_str, +46 + ) 47 + from airflow.providers.cncf.kubernetes.utils.xcom_sidecar import PodDefaults -48 | | note: This is an unsafe fix and may change runtime behavior @@ -242,13 +244,17 @@ AIR302 [*] `airflow.kubernetes.pod_generator.PodGenerator` is moved into `cncf-k | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `PodGenerator` from `airflow.providers.cncf.kubernetes.pod_generator` instead. | -38 | PodDefaults, - - PodGenerator, -39 | add_pod_suffix, --------------------------------------------------------------------------------- -46 | ) +37 + from airflow.kubernetes.pod_generator import ( +38 + PodDefaults, +39 + add_pod_suffix, +40 + datetime_to_label_safe_datestring, +41 + extend_object_field, +42 + label_safe_datestring_to_datetime, +43 + make_safe_label_value, +44 + merge_objects, +45 + rand_str, +46 + ) 47 + from airflow.providers.cncf.kubernetes.pod_generator import PodGenerator -48 | | note: This is an unsafe fix and may change runtime behavior @@ -264,14 +270,11 @@ AIR302 [*] `airflow.kubernetes.pod_generator.add_pod_suffix` is moved into `cncf | help: Install `apache-airflow-providers-cncf-kubernetes>=10.0.0` and use `add_unique_suffix` from `airflow.providers.cncf.kubernetes.kubernetes_helper_functions` instead. | -47 | ) 48 + from airflow.providers.cncf.kubernetes.kubernetes_helper_functions import add_unique_suffix -49 | +49 + 50 | PodDefaults() 51 | PodGenerator() - - add_pod_suffix() -52 + add_unique_suffix() -53 | datetime_to_label_safe_datestring() +52 ~ add_unique_suffix() | AIR302 [*] `airflow.kubernetes.pod_generator.datetime_to_label_safe_datestring` is moved into `cncf-kubernetes` provider in Airflow 3.0; @@ -286,13 +289,17 @@ AIR302 [*] `airflow.kubernetes.pod_generator.datetime_to_label_safe_datestring` | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `datetime_to_label_safe_datestring` from `airflow.providers.cncf.kubernetes.pod_generator` instead. | -40 | add_pod_suffix, - - datetime_to_label_safe_datestring, -41 | extend_object_field, --------------------------------------------------------------------------------- -46 | ) +37 + from airflow.kubernetes.pod_generator import ( +38 + PodDefaults, +39 + PodGenerator, +40 + add_pod_suffix, +41 + extend_object_field, +42 + label_safe_datestring_to_datetime, +43 + make_safe_label_value, +44 + merge_objects, +45 + rand_str, +46 + ) 47 + from airflow.providers.cncf.kubernetes.pod_generator import datetime_to_label_safe_datestring -48 | | note: This is an unsafe fix and may change runtime behavior @@ -308,13 +315,17 @@ AIR302 [*] `airflow.kubernetes.pod_generator.extend_object_field` is moved into | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `extend_object_field` from `airflow.providers.cncf.kubernetes.pod_generator` instead. | -41 | datetime_to_label_safe_datestring, - - extend_object_field, -42 | label_safe_datestring_to_datetime, --------------------------------------------------------------------------------- -46 | ) +37 + from airflow.kubernetes.pod_generator import ( +38 + PodDefaults, +39 + PodGenerator, +40 + add_pod_suffix, +41 + datetime_to_label_safe_datestring, +42 + label_safe_datestring_to_datetime, +43 + make_safe_label_value, +44 + merge_objects, +45 + rand_str, +46 + ) 47 + from airflow.providers.cncf.kubernetes.pod_generator import extend_object_field -48 | | note: This is an unsafe fix and may change runtime behavior @@ -330,14 +341,17 @@ AIR302 [*] `airflow.kubernetes.pod_generator.label_safe_datestring_to_datetime` | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `label_safe_datestring_to_datetime` from `airflow.providers.cncf.kubernetes.pod_generator` instead. | -42 | extend_object_field, - - label_safe_datestring_to_datetime, -43 | make_safe_label_value, -44 | merge_objects, -45 | rand_str, -46 | ) +37 + from airflow.kubernetes.pod_generator import ( +38 + PodDefaults, +39 + PodGenerator, +40 + add_pod_suffix, +41 + datetime_to_label_safe_datestring, +42 + extend_object_field, +43 + make_safe_label_value, +44 + merge_objects, +45 + rand_str, +46 + ) 47 + from airflow.providers.cncf.kubernetes.pod_generator import label_safe_datestring_to_datetime -48 | | note: This is an unsafe fix and may change runtime behavior @@ -353,13 +367,17 @@ AIR302 [*] `airflow.kubernetes.pod_generator.make_safe_label_value` is moved int | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `make_safe_label_value` from `airflow.providers.cncf.kubernetes.pod_generator` instead. | -43 | label_safe_datestring_to_datetime, - - make_safe_label_value, -44 | merge_objects, -45 | rand_str, -46 | ) +37 + from airflow.kubernetes.pod_generator import ( +38 + PodDefaults, +39 + PodGenerator, +40 + add_pod_suffix, +41 + datetime_to_label_safe_datestring, +42 + extend_object_field, +43 + label_safe_datestring_to_datetime, +44 + merge_objects, +45 + rand_str, +46 + ) 47 + from airflow.providers.cncf.kubernetes.pod_generator import make_safe_label_value -48 | | note: This is an unsafe fix and may change runtime behavior @@ -374,12 +392,17 @@ AIR302 [*] `airflow.kubernetes.pod_generator.merge_objects` is moved into `cncf- | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `merge_objects` from `airflow.providers.cncf.kubernetes.pod_generator` instead. | -44 | make_safe_label_value, - - merge_objects, -45 | rand_str, -46 | ) +37 + from airflow.kubernetes.pod_generator import ( +38 + PodDefaults, +39 + PodGenerator, +40 + add_pod_suffix, +41 + datetime_to_label_safe_datestring, +42 + extend_object_field, +43 + label_safe_datestring_to_datetime, +44 + make_safe_label_value, +45 + rand_str, +46 + ) 47 + from airflow.providers.cncf.kubernetes.pod_generator import merge_objects -48 | | note: This is an unsafe fix and may change runtime behavior @@ -395,11 +418,17 @@ AIR302 [*] `airflow.kubernetes.pod_generator.rand_str` is moved into `cncf-kuber | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `rand_str` from `airflow.providers.cncf.kubernetes.kubernetes_helper_functions` instead. | -45 | merge_objects, - - rand_str, -46 | ) +37 + from airflow.kubernetes.pod_generator import ( +38 + PodDefaults, +39 + PodGenerator, +40 + add_pod_suffix, +41 + datetime_to_label_safe_datestring, +42 + extend_object_field, +43 + label_safe_datestring_to_datetime, +44 + make_safe_label_value, +45 + merge_objects, +46 + ) 47 + from airflow.providers.cncf.kubernetes.kubernetes_helper_functions import rand_str -48 | | note: This is an unsafe fix and may change runtime behavior @@ -415,13 +444,14 @@ AIR302 [*] `airflow.kubernetes.pod_generator_deprecated.PodDefaults` is moved in | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `PodDefaults` from `airflow.providers.cncf.kubernetes.utils.xcom_sidecar` instead. | -59 | from airflow.kubernetes.pod_generator_deprecated import ( - - PodDefaults, -60 | PodGenerator, --------------------------------------------------------------------------------- +59 + from airflow.kubernetes.pod_generator_deprecated import ( +60 + PodGenerator, +61 + make_safe_label_value, +62 + ) +63 | from airflow.kubernetes.pod_launcher import ( + … 66 | ) 67 + from airflow.providers.cncf.kubernetes.utils.xcom_sidecar import PodDefaults -68 | | note: This is an unsafe fix and may change runtime behavior @@ -435,13 +465,14 @@ AIR302 [*] `airflow.kubernetes.pod_generator_deprecated.PodGenerator` is moved i | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `PodGenerator` from `airflow.providers.cncf.kubernetes.pod_generator` instead. | -60 | PodDefaults, - - PodGenerator, -61 | make_safe_label_value, --------------------------------------------------------------------------------- +59 + from airflow.kubernetes.pod_generator_deprecated import ( +60 + PodDefaults, +61 + make_safe_label_value, +62 + ) +63 | from airflow.kubernetes.pod_launcher import ( + … 66 | ) 67 + from airflow.providers.cncf.kubernetes.pod_generator import PodGenerator -68 | | note: This is an unsafe fix and may change runtime behavior @@ -457,13 +488,14 @@ AIR302 [*] `airflow.kubernetes.pod_generator_deprecated.make_safe_label_value` i | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `make_safe_label_value` from `airflow.providers.cncf.kubernetes.pod_generator` instead. | -61 | PodGenerator, - - make_safe_label_value, -62 | ) --------------------------------------------------------------------------------- +59 + from airflow.kubernetes.pod_generator_deprecated import ( +60 + PodDefaults, +61 + PodGenerator, +62 + ) +63 | from airflow.kubernetes.pod_launcher import ( + … 66 | ) 67 + from airflow.providers.cncf.kubernetes.pod_generator import make_safe_label_value -68 | | note: This is an unsafe fix and may change runtime behavior @@ -478,14 +510,12 @@ AIR302 [*] `airflow.kubernetes.pod_launcher.PodLauncher` is moved into `cncf-kub | help: Install `apache-airflow-providers-cncf-kubernetes>=3.0.0` and use `PodManager` from `airflow.providers.cncf.kubernetes.utils.pod_manager` instead. | -67 | ) 68 + from airflow.providers.cncf.kubernetes.utils.pod_manager import PodManager -69 | --------------------------------------------------------------------------------- +69 + +70 | PodDefaults() + … 73 | - - PodLauncher() -74 + PodManager() -75 | PodStatus() +74 ~ PodManager() | AIR302 [*] `airflow.kubernetes.pod_launcher.PodStatus` is moved into `cncf-kubernetes` provider in Airflow 3.0; @@ -499,14 +529,12 @@ AIR302 [*] `airflow.kubernetes.pod_launcher.PodStatus` is moved into `cncf-kuber | help: Install `apache-airflow-providers-cncf-kubernetes>=3.0.0` and use `PodPhase` from ` airflow.providers.cncf.kubernetes.utils.pod_manager` instead. | -67 | ) 68 + from airflow.providers.cncf.kubernetes.utils.pod_manager import PodPhase -69 | --------------------------------------------------------------------------------- +69 + +70 | PodDefaults() + … 74 | PodLauncher() - - PodStatus() -75 + PodPhase() -76 | +75 ~ PodPhase() | AIR302 [*] `airflow.kubernetes.pod_launcher_deprecated.PodDefaults` is moved into `cncf-kubernetes` provider in Airflow 3.0; @@ -521,13 +549,15 @@ AIR302 [*] `airflow.kubernetes.pod_launcher_deprecated.PodDefaults` is moved int | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `PodDefaults` from `airflow.providers.cncf.kubernetes.utils.xcom_sidecar` instead. | -76 | from airflow.kubernetes.pod_launcher_deprecated import ( - - PodDefaults, -77 | PodLauncher, --------------------------------------------------------------------------------- +76 + from airflow.kubernetes.pod_launcher_deprecated import ( +77 + PodLauncher, +78 + PodStatus, +79 + get_kube_client, +80 + ) +81 | from airflow.kubernetes.pod_runtime_info_env import PodRuntimeInfoEnv + … 87 | from airflow.kubernetes.volume_mount import VolumeMount 88 + from airflow.providers.cncf.kubernetes.utils.xcom_sidecar import PodDefaults -89 | | note: This is an unsafe fix and may change runtime behavior @@ -542,13 +572,10 @@ AIR302 [*] `airflow.kubernetes.pod_launcher_deprecated.PodLauncher` is moved int | help: Install `apache-airflow-providers-cncf-kubernetes>=3.0.0` and use `PodManager` from `airflow.providers.cncf.kubernetes.utils.pod_manager` instead. | -88 | from airflow.kubernetes.volume_mount import VolumeMount 89 + from airflow.providers.cncf.kubernetes.utils.pod_manager import PodManager -90 | +90 + 91 | PodDefaults() - - PodLauncher() -92 + PodManager() -93 | PodStatus() +92 ~ PodManager() | AIR302 [*] `airflow.kubernetes.pod_launcher_deprecated.PodStatus` is moved into `cncf-kubernetes` provider in Airflow 3.0; @@ -562,14 +589,11 @@ AIR302 [*] `airflow.kubernetes.pod_launcher_deprecated.PodStatus` is moved into | help: Install `apache-airflow-providers-cncf-kubernetes>=3.0.0` and use `PodPhase` from ` airflow.providers.cncf.kubernetes.utils.pod_manager` instead. | -88 | from airflow.kubernetes.volume_mount import VolumeMount 89 + from airflow.providers.cncf.kubernetes.utils.pod_manager import PodPhase -90 | +90 + 91 | PodDefaults() 92 | PodLauncher() - - PodStatus() -93 + PodPhase() -94 | get_kube_client() +93 ~ PodPhase() | AIR302 [*] `airflow.kubernetes.pod_launcher_deprecated.get_kube_client` is moved into `cncf-kubernetes` provider in Airflow 3.0; @@ -584,13 +608,15 @@ AIR302 [*] `airflow.kubernetes.pod_launcher_deprecated.get_kube_client` is moved | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `get_kube_client` from `airflow.providers.cncf.kubernetes.kube_client` instead. | -79 | PodStatus, - - get_kube_client, -80 | ) --------------------------------------------------------------------------------- +76 + from airflow.kubernetes.pod_launcher_deprecated import ( +77 + PodDefaults, +78 + PodLauncher, +79 + PodStatus, +80 + ) +81 | from airflow.kubernetes.pod_runtime_info_env import PodRuntimeInfoEnv + … 87 | from airflow.kubernetes.volume_mount import VolumeMount 88 + from airflow.providers.cncf.kubernetes.kube_client import get_kube_client -89 | | note: This is an unsafe fix and may change runtime behavior @@ -606,14 +632,12 @@ AIR302 [*] `airflow.kubernetes.pod_runtime_info_env.PodRuntimeInfoEnv` is moved | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `V1EnvVar` from `kubernetes.client.models` instead. | -88 | from airflow.kubernetes.volume_mount import VolumeMount 89 + from kubernetes.client.models import V1EnvVar -90 | --------------------------------------------------------------------------------- +90 + +91 | PodDefaults() + … 95 | - - PodRuntimeInfoEnv() -96 + V1EnvVar() -97 | K8SModel() +96 ~ V1EnvVar() | AIR302 [*] `airflow.kubernetes.secret.K8SModel` is moved into `cncf-kubernetes` provider in Airflow 3.0; @@ -627,14 +651,12 @@ AIR302 [*] `airflow.kubernetes.secret.K8SModel` is moved into `cncf-kubernetes` | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `K8SModel` from `airflow.providers.cncf.kubernetes.k8s_model` instead. | -83 | from airflow.kubernetes.secret import ( - - K8SModel, -84 | Secret, -85 | ) +83 + from airflow.kubernetes.secret import ( +84 + Secret, +85 + ) 86 | from airflow.kubernetes.volume import Volume 87 | from airflow.kubernetes.volume_mount import VolumeMount 88 + from airflow.providers.cncf.kubernetes.k8s_model import K8SModel -89 | | note: This is an unsafe fix and may change runtime behavior @@ -650,13 +672,12 @@ AIR302 [*] `airflow.kubernetes.secret.Secret` is moved into `cncf-kubernetes` pr | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `Secret` from `airflow.providers.cncf.kubernetes.secret` instead. | -84 | K8SModel, - - Secret, -85 | ) +83 + from airflow.kubernetes.secret import ( +84 + K8SModel, +85 + ) 86 | from airflow.kubernetes.volume import Volume 87 | from airflow.kubernetes.volume_mount import VolumeMount 88 + from airflow.providers.cncf.kubernetes.secret import Secret -89 | | note: This is an unsafe fix and may change runtime behavior @@ -670,16 +691,14 @@ AIR302 [*] `airflow.kubernetes.volume.Volume` is moved into `cncf-kubernetes` pr 99 | VolumeMount() | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `V1Volume` from `kubernetes.client.models` instead. - | -88 | from airflow.kubernetes.volume_mount import VolumeMount -89 + from kubernetes.client.models import V1Volume -90 | --------------------------------------------------------------------------------- -98 | Secret() - - Volume() -99 + V1Volume() -100 | VolumeMount() - | + | +89 + from kubernetes.client.models import V1Volume +90 + +91 | PodDefaults() + … +98 | Secret() +99 ~ V1Volume() + | AIR302 [*] `airflow.kubernetes.volume_mount.VolumeMount` is moved into `cncf-kubernetes` provider in Airflow 3.0; --> AIR302_kubernetes.py:99:1 @@ -693,14 +712,12 @@ AIR302 [*] `airflow.kubernetes.volume_mount.VolumeMount` is moved into `cncf-kub | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `V1VolumeMount` from `kubernetes.client.models` instead. | -88 | from airflow.kubernetes.volume_mount import VolumeMount -89 + from kubernetes.client.models import V1VolumeMount -90 | --------------------------------------------------------------------------------- -99 | Volume() - - VolumeMount() -100 + V1VolumeMount() -101 | + 89 + from kubernetes.client.models import V1VolumeMount + 90 + + 91 | PodDefaults() + … + 99 | Volume() +100 ~ V1VolumeMount() | AIR302 [*] `airflow.kubernetes.kubernetes_helper_functions.annotations_to_key` is moved into `cncf-kubernetes` provider in Airflow 3.0; @@ -715,13 +732,11 @@ AIR302 [*] `airflow.kubernetes.kubernetes_helper_functions.annotations_to_key` i | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `annotations_to_key` from `airflow.providers.cncf.kubernetes.kubernetes_helper_functions` instead. | -101 | from airflow.kubernetes.kubernetes_helper_functions import ( - - annotations_to_key, -102 | get_logs_task_metadata, -103 | rand_str, -104 | ) +101 + from airflow.kubernetes.kubernetes_helper_functions import ( +102 + get_logs_task_metadata, +103 + rand_str, +104 + ) 105 + from airflow.providers.cncf.kubernetes.kubernetes_helper_functions import annotations_to_key -106 | | note: This is an unsafe fix and may change runtime behavior @@ -735,12 +750,11 @@ AIR302 [*] `airflow.kubernetes.kubernetes_helper_functions.get_logs_task_metadat | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `get_logs_task_metadata` from `airflow.providers.cncf.kubernetes.kubernetes_helper_functions` instead. | -102 | annotations_to_key, - - get_logs_task_metadata, -103 | rand_str, -104 | ) +101 + from airflow.kubernetes.kubernetes_helper_functions import ( +102 + annotations_to_key, +103 + rand_str, +104 + ) 105 + from airflow.providers.cncf.kubernetes.kubernetes_helper_functions import get_logs_task_metadata -106 | | note: This is an unsafe fix and may change runtime behavior @@ -756,11 +770,11 @@ AIR302 [*] `airflow.kubernetes.kubernetes_helper_functions.rand_str` is moved in | help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `rand_str` from `airflow.providers.cncf.kubernetes.kubernetes_helper_functions` instead. | -103 | get_logs_task_metadata, - - rand_str, -104 | ) +101 + from airflow.kubernetes.kubernetes_helper_functions import ( +102 + annotations_to_key, +103 + get_logs_task_metadata, +104 + ) 105 + from airflow.providers.cncf.kubernetes.kubernetes_helper_functions import rand_str -106 | | note: This is an unsafe fix and may change runtime behavior @@ -773,8 +787,7 @@ AIR302 [*] `airflow.kubernetes.pod_generator.PodGeneratorDeprecated` is moved in | ^^^^^^^^^^^^^^^^^^^^^^ help: Install `apache-airflow-providers-cncf-kubernetes>=7.4.0` and use `PodGenerator` from `airflow.providers.cncf.kubernetes.pod_generator` instead. | -111 | from airflow.kubernetes.pod_generator import PodGeneratorDeprecated +111 ~ from airflow.kubernetes.pod_generator import PodGeneratorDeprecated 112 + from airflow.providers.cncf.kubernetes.pod_generator import PodGenerator -113 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_mysql.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_mysql.py.snap index 0e416009066fa..45864ae4f1fdd 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_mysql.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_mysql.py.snap @@ -13,14 +13,11 @@ AIR302 [*] `airflow.hooks.mysql_hook.MySqlHook` is moved into `mysql` provider i | help: Install `apache-airflow-providers-mysql>=1.0.0` and use `MySqlHook` from `airflow.providers.mysql.hooks.mysql` instead. | -2 | - - from airflow.hooks.mysql_hook import MySqlHook -3 | from airflow.operators.presto_to_mysql import ( -4 | PrestoToMySqlOperator, -5 | PrestoToMySqlTransfer, -6 | ) -7 + from airflow.providers.mysql.hooks.mysql import MySqlHook -8 | +3 + +4 | from airflow.operators.presto_to_mysql import ( +… +7 | ) +8 + from airflow.providers.mysql.hooks.mysql import MySqlHook | note: This is an unsafe fix and may change runtime behavior @@ -34,12 +31,10 @@ AIR302 [*] `airflow.operators.presto_to_mysql.PrestoToMySqlOperator` is moved in | help: Install `apache-airflow-providers-mysql>=1.0.0` and use `PrestoToMySqlOperator` from `airflow.providers.mysql.transfers.presto_to_mysql` instead. | -4 | from airflow.operators.presto_to_mysql import ( - - PrestoToMySqlOperator, -5 | PrestoToMySqlTransfer, -6 | ) +4 + from airflow.operators.presto_to_mysql import ( +5 + PrestoToMySqlTransfer, +6 + ) 7 + from airflow.providers.mysql.transfers.presto_to_mysql import PrestoToMySqlOperator -8 | | note: This is an unsafe fix and may change runtime behavior @@ -52,11 +47,9 @@ AIR302 [*] `airflow.operators.presto_to_mysql.PrestoToMySqlTransfer` is moved in | ^^^^^^^^^^^^^^^^^^^^^ help: Install `apache-airflow-providers-mysql>=1.0.0` and use `PrestoToMySqlOperator` from `airflow.providers.mysql.transfers.presto_to_mysql` instead. | -4 | from airflow.operators.presto_to_mysql import ( - - PrestoToMySqlOperator, -5 | PrestoToMySqlTransfer, -6 | ) +4 + from airflow.operators.presto_to_mysql import ( +5 + PrestoToMySqlTransfer, +6 + ) 7 + from airflow.providers.mysql.transfers.presto_to_mysql import PrestoToMySqlOperator -8 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_oracle.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_oracle.py.snap index 27249b48d95af..9e90c5d7e19da 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_oracle.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_oracle.py.snap @@ -10,9 +10,7 @@ AIR302 [*] `airflow.hooks.oracle_hook.OracleHook` is moved into `oracle` provide | ^^^^^^^^^^ help: Install `apache-airflow-providers-oracle>=1.0.0` and use `OracleHook` from `airflow.providers.oracle.hooks.oracle` instead. | -2 | - - from airflow.hooks.oracle_hook import OracleHook -3 + from airflow.providers.oracle.hooks.oracle import OracleHook -4 | +3 + +4 + from airflow.providers.oracle.hooks.oracle import OracleHook | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_papermill.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_papermill.py.snap index 6afd5f958b09d..a252eb1e884ea 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_papermill.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_papermill.py.snap @@ -10,9 +10,7 @@ AIR302 [*] `airflow.operators.papermill_operator.PapermillOperator` is moved int | ^^^^^^^^^^^^^^^^^ help: Install `apache-airflow-providers-papermill>=1.0.0` and use `PapermillOperator` from `airflow.providers.papermill.operators.papermill` instead. | -2 | - - from airflow.operators.papermill_operator import PapermillOperator -3 + from airflow.providers.papermill.operators.papermill import PapermillOperator -4 | +3 + +4 + from airflow.providers.papermill.operators.papermill import PapermillOperator | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_pig.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_pig.py.snap index d69d3f9223229..d6d1f32cf4d82 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_pig.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_pig.py.snap @@ -12,11 +12,9 @@ AIR302 [*] `airflow.hooks.pig_hook.PigCliHook` is moved into `apache-pig` provid | help: Install `apache-airflow-providers-apache-pig>=1.0.0` and use `PigCliHook` from `airflow.providers.apache.pig.hooks.pig` instead. | -2 | - - from airflow.hooks.pig_hook import PigCliHook -3 | from airflow.operators.pig_operator import PigOperator -4 + from airflow.providers.apache.pig.hooks.pig import PigCliHook -5 | +3 + +4 | from airflow.operators.pig_operator import PigOperator +5 + from airflow.providers.apache.pig.hooks.pig import PigCliHook | note: This is an unsafe fix and may change runtime behavior @@ -28,9 +26,7 @@ AIR302 [*] `airflow.operators.pig_operator.PigOperator` is moved into `apache-pi | ^^^^^^^^^^^ help: Install `apache-airflow-providers-apache-pig>=1.0.0` and use `PigOperator` from `airflow.providers.apache.pig.operators.pig` instead. | -3 | from airflow.hooks.pig_hook import PigCliHook - - from airflow.operators.pig_operator import PigOperator -4 + from airflow.providers.apache.pig.operators.pig import PigOperator -5 | +4 + +5 + from airflow.providers.apache.pig.operators.pig import PigOperator | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_postgres.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_postgres.py.snap index 0a31b1f54176b..56c6deab21789 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_postgres.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_postgres.py.snap @@ -12,10 +12,8 @@ AIR302 [*] `airflow.hooks.postgres_hook.PostgresHook` is moved into `postgres` p | help: Install `apache-airflow-providers-postgres>=1.0.0` and use `PostgresHook` from `airflow.providers.postgres.hooks.postgres` instead. | -2 | - - from airflow.hooks.postgres_hook import PostgresHook -3 | from airflow.operators.postgres_operator import Mapping -4 + from airflow.providers.postgres.hooks.postgres import PostgresHook -5 | +3 + +4 | from airflow.operators.postgres_operator import Mapping +5 + from airflow.providers.postgres.hooks.postgres import PostgresHook | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_presto.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_presto.py.snap index 15790d11dd8e1..43097f1f316a8 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_presto.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_presto.py.snap @@ -10,9 +10,7 @@ AIR302 [*] `airflow.hooks.presto_hook.PrestoHook` is moved into `presto` provide | ^^^^^^^^^^ help: Install `apache-airflow-providers-presto>=1.0.0` and use `PrestoHook` from `airflow.providers.presto.hooks.presto` instead. | -2 | - - from airflow.hooks.presto_hook import PrestoHook -3 + from airflow.providers.presto.hooks.presto import PrestoHook -4 | +3 + +4 + from airflow.providers.presto.hooks.presto import PrestoHook | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_samba.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_samba.py.snap index 57326616fc1eb..ec56989352ac5 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_samba.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_samba.py.snap @@ -10,9 +10,7 @@ AIR302 [*] `airflow.hooks.samba_hook.SambaHook` is moved into `samba` provider i | ^^^^^^^^^ help: Install `apache-airflow-providers-samba>=1.0.0` and use `SambaHook` from `airflow.providers.samba.hooks.samba` instead. | -2 | - - from airflow.hooks.samba_hook import SambaHook -3 + from airflow.providers.samba.hooks.samba import SambaHook -4 | +3 + +4 + from airflow.providers.samba.hooks.samba import SambaHook | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_slack.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_slack.py.snap index 8ffef8eb4b8dd..a7df818b76cbc 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_slack.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_slack.py.snap @@ -13,11 +13,9 @@ AIR302 [*] `airflow.hooks.slack_hook.SlackHook` is moved into `slack` provider i | help: Install `apache-airflow-providers-slack>=1.0.0` and use `SlackHook` from `airflow.providers.slack.hooks.slack` instead. | -2 | - - from airflow.hooks.slack_hook import SlackHook -3 | from airflow.operators.slack_operator import SlackAPIOperator, SlackAPIPostOperator -4 + from airflow.providers.slack.hooks.slack import SlackHook -5 | +3 + +4 | from airflow.operators.slack_operator import SlackAPIOperator, SlackAPIPostOperator +5 + from airflow.providers.slack.hooks.slack import SlackHook | note: This is an unsafe fix and may change runtime behavior @@ -31,11 +29,8 @@ AIR302 [*] `airflow.operators.slack_operator.SlackAPIOperator` is moved into `sl | help: Install `apache-airflow-providers-slack>=1.0.0` and use `SlackAPIOperator` from `airflow.providers.slack.operators.slack` instead. | -3 | from airflow.hooks.slack_hook import SlackHook - - from airflow.operators.slack_operator import SlackAPIOperator, SlackAPIPostOperator 4 + from airflow.operators.slack_operator import SlackAPIPostOperator 5 + from airflow.providers.slack.operators.slack import SlackAPIOperator -6 | | note: This is an unsafe fix and may change runtime behavior @@ -48,10 +43,7 @@ AIR302 [*] `airflow.operators.slack_operator.SlackAPIPostOperator` is moved into | ^^^^^^^^^^^^^^^^^^^^ help: Install `apache-airflow-providers-slack>=1.0.0` and use `SlackAPIPostOperator` from `airflow.providers.slack.operators.slack` instead. | -3 | from airflow.hooks.slack_hook import SlackHook - - from airflow.operators.slack_operator import SlackAPIOperator, SlackAPIPostOperator 4 + from airflow.operators.slack_operator import SlackAPIOperator 5 + from airflow.providers.slack.operators.slack import SlackAPIPostOperator -6 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_smtp.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_smtp.py.snap index dbb6eb29f67ce..ff54bb870727d 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_smtp.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_smtp.py.snap @@ -13,10 +13,8 @@ AIR302 [*] `airflow.operators.email_operator.EmailOperator` is moved into `smtp` | help: Install `apache-airflow-providers-smtp>=1.0.0` and use `EmailOperator` from `airflow.providers.smtp.operators.smtp` instead. | -2 | - - from airflow.operators.email_operator import EmailOperator -3 + from airflow.providers.smtp.operators.smtp import EmailOperator -4 | +3 + +4 + from airflow.providers.smtp.operators.smtp import EmailOperator | note: This is an unsafe fix and may change runtime behavior @@ -29,9 +27,7 @@ AIR302 [*] `airflow.operators.email.EmailOperator` is moved into `smtp` provider | ^^^^^^^^^^^^^ help: Install `apache-airflow-providers-smtp>=1.0.0` and use `EmailOperator` from `airflow.providers.smtp.operators.smtp` instead. | -6 | - - from airflow.operators.email import EmailOperator -7 + from airflow.providers.smtp.operators.smtp import EmailOperator -8 | +7 + +8 + from airflow.providers.smtp.operators.smtp import EmailOperator | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_sqlite.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_sqlite.py.snap index 9d054905dcd66..a847057450592 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_sqlite.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_sqlite.py.snap @@ -10,9 +10,7 @@ AIR302 [*] `airflow.hooks.sqlite_hook.SqliteHook` is moved into `sqlite` provide | ^^^^^^^^^^ help: Install `apache-airflow-providers-sqlite>=1.0.0` and use `SqliteHook` from `airflow.providers.sqlite.hooks.sqlite` instead. | -2 | - - from airflow.hooks.sqlite_hook import SqliteHook -3 + from airflow.providers.sqlite.hooks.sqlite import SqliteHook -4 | +3 + +4 + from airflow.providers.sqlite.hooks.sqlite import SqliteHook | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_standard.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_standard.py.snap index 6490009535ef4..0e67929261482 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_standard.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_standard.py.snap @@ -13,13 +13,11 @@ AIR302 [*] `airflow.operators.bash_operator.BashOperator` is moved into `standar | help: Install `apache-airflow-providers-standard>=0.0.1` and use `BashOperator` from `airflow.providers.standard.operators.bash` instead. | -2 | - - from airflow.operators.bash_operator import BashOperator -3 | from airflow.operators.dagrun_operator import ( --------------------------------------------------------------------------------- -17 | ) -18 + from airflow.providers.standard.operators.bash import BashOperator -19 | + 3 + + 4 | from airflow.operators.dagrun_operator import ( + … +18 | ) +19 + from airflow.providers.standard.operators.bash import BashOperator | note: This is an unsafe fix and may change runtime behavior @@ -34,13 +32,13 @@ AIR302 [*] `airflow.operators.dagrun_operator.TriggerDagRunLink` is moved into ` | help: Install `apache-airflow-providers-standard>=0.0.2` and use `TriggerDagRunLink` from `airflow.providers.standard.operators.trigger_dagrun` instead. | -4 | from airflow.operators.dagrun_operator import ( - - TriggerDagRunLink, -5 | TriggerDagRunOperator, --------------------------------------------------------------------------------- + 4 + from airflow.operators.dagrun_operator import ( + 5 + TriggerDagRunOperator, + 6 + ) + 7 | from airflow.operators.latest_only_operator import LatestOnlyOperator + … 17 | ) 18 + from airflow.providers.standard.operators.trigger_dagrun import TriggerDagRunLink -19 | | note: This is an unsafe fix and may change runtime behavior @@ -55,13 +53,13 @@ AIR302 [*] `airflow.operators.dagrun_operator.TriggerDagRunOperator` is moved in | help: Install `apache-airflow-providers-standard>=0.0.2` and use `TriggerDagRunOperator` from `airflow.providers.standard.operators.trigger_dagrun` instead. | -5 | TriggerDagRunLink, - - TriggerDagRunOperator, -6 | ) --------------------------------------------------------------------------------- + 4 + from airflow.operators.dagrun_operator import ( + 5 + TriggerDagRunLink, + 6 + ) + 7 | from airflow.operators.latest_only_operator import LatestOnlyOperator + … 17 | ) 18 + from airflow.providers.standard.operators.trigger_dagrun import TriggerDagRunOperator -19 | | note: This is an unsafe fix and may change runtime behavior @@ -77,13 +75,11 @@ AIR302 [*] `airflow.operators.latest_only_operator.LatestOnlyOperator` is moved | help: Install `apache-airflow-providers-standard>=0.0.3` and use `LatestOnlyOperator` from `airflow.providers.standard.operators.latest_only` instead. | -7 | ) - - from airflow.operators.latest_only_operator import LatestOnlyOperator -8 | from airflow.operators.python_operator import ( --------------------------------------------------------------------------------- -17 | ) -18 + from airflow.providers.standard.operators.latest_only import LatestOnlyOperator -19 | + 8 + + 9 | from airflow.operators.python_operator import ( + … +18 | ) +19 + from airflow.providers.standard.operators.latest_only import LatestOnlyOperator | note: This is an unsafe fix and may change runtime behavior @@ -99,13 +95,15 @@ AIR302 [*] `airflow.operators.python_operator.BranchPythonOperator` is moved int | help: Install `apache-airflow-providers-standard>=0.0.1` and use `BranchPythonOperator` from `airflow.providers.standard.operators.python` instead. | -9 | from airflow.operators.python_operator import ( - - BranchPythonOperator, -10 | PythonOperator, --------------------------------------------------------------------------------- + 9 + from airflow.operators.python_operator import ( +10 + PythonOperator, +11 + PythonVirtualenvOperator, +12 + ShortCircuitOperator, +13 + ) +14 | from airflow.sensors.external_task_sensor import ( + … 17 | ) 18 + from airflow.providers.standard.operators.python import BranchPythonOperator -19 | | note: This is an unsafe fix and may change runtime behavior @@ -120,13 +118,15 @@ AIR302 [*] `airflow.operators.python_operator.PythonOperator` is moved into `sta | help: Install `apache-airflow-providers-standard>=0.0.1` and use `PythonOperator` from `airflow.providers.standard.operators.python` instead. | -10 | BranchPythonOperator, - - PythonOperator, -11 | PythonVirtualenvOperator, --------------------------------------------------------------------------------- + 9 + from airflow.operators.python_operator import ( +10 + BranchPythonOperator, +11 + PythonVirtualenvOperator, +12 + ShortCircuitOperator, +13 + ) +14 | from airflow.sensors.external_task_sensor import ( + … 17 | ) 18 + from airflow.providers.standard.operators.python import PythonOperator -19 | | note: This is an unsafe fix and may change runtime behavior @@ -141,13 +141,15 @@ AIR302 [*] `airflow.operators.python_operator.PythonVirtualenvOperator` is moved | help: Install `apache-airflow-providers-standard>=0.0.1` and use `PythonVirtualenvOperator` from `airflow.providers.standard.operators.python` instead. | -11 | PythonOperator, - - PythonVirtualenvOperator, -12 | ShortCircuitOperator, --------------------------------------------------------------------------------- + 9 + from airflow.operators.python_operator import ( +10 + BranchPythonOperator, +11 + PythonOperator, +12 + ShortCircuitOperator, +13 + ) +14 | from airflow.sensors.external_task_sensor import ( + … 17 | ) 18 + from airflow.providers.standard.operators.python import PythonVirtualenvOperator -19 | | note: This is an unsafe fix and may change runtime behavior @@ -163,13 +165,15 @@ AIR302 [*] `airflow.operators.python_operator.ShortCircuitOperator` is moved int | help: Install `apache-airflow-providers-standard>=0.0.1` and use `ShortCircuitOperator` from `airflow.providers.standard.operators.python` instead. | -12 | PythonVirtualenvOperator, - - ShortCircuitOperator, -13 | ) --------------------------------------------------------------------------------- + 9 + from airflow.operators.python_operator import ( +10 + BranchPythonOperator, +11 + PythonOperator, +12 + PythonVirtualenvOperator, +13 + ) +14 | from airflow.sensors.external_task_sensor import ( + … 17 | ) 18 + from airflow.providers.standard.operators.python import ShortCircuitOperator -19 | | note: This is an unsafe fix and may change runtime behavior @@ -184,12 +188,10 @@ AIR302 [*] `airflow.sensors.external_task_sensor.ExternalTaskMarker` is moved in | help: Install `apache-airflow-providers-standard>=0.0.3` and use `ExternalTaskMarker` from `airflow.providers.standard.sensors.external_task` instead. | -15 | from airflow.sensors.external_task_sensor import ( - - ExternalTaskMarker, -16 | ExternalTaskSensor, -17 | ) +15 + from airflow.sensors.external_task_sensor import ( +16 + ExternalTaskSensor, +17 + ) 18 + from airflow.providers.standard.sensors.external_task import ExternalTaskMarker -19 | | note: This is an unsafe fix and may change runtime behavior @@ -201,11 +203,10 @@ AIR302 [*] `airflow.sensors.external_task_sensor.ExternalTaskSensor` is moved in | ^^^^^^^^^^^^^^^^^^ help: Install `apache-airflow-providers-standard>=0.0.3` and use `ExternalTaskSensor` from `airflow.providers.standard.sensors.external_task` instead. | -16 | ExternalTaskMarker, - - ExternalTaskSensor, -17 | ) +15 + from airflow.sensors.external_task_sensor import ( +16 + ExternalTaskMarker, +17 + ) 18 + from airflow.providers.standard.sensors.external_task import ExternalTaskSensor -19 | | note: This is an unsafe fix and may change runtime behavior @@ -221,10 +222,8 @@ AIR302 [*] `airflow.hooks.subprocess.SubprocessResult` is moved into `standard` | help: Install `apache-airflow-providers-standard>=0.0.3` and use `SubprocessResult` from `airflow.providers.standard.hooks.subprocess` instead. | -35 | - - from airflow.hooks.subprocess import SubprocessResult -36 + from airflow.providers.standard.hooks.subprocess import SubprocessResult -37 | +36 + +37 + from airflow.providers.standard.hooks.subprocess import SubprocessResult | note: This is an unsafe fix and may change runtime behavior @@ -240,10 +239,8 @@ AIR302 [*] `airflow.hooks.subprocess.working_directory` is moved into `standard` | help: Install `apache-airflow-providers-standard>=0.0.3` and use `working_directory` from `airflow.providers.standard.hooks.subprocess` instead. | -39 | - - from airflow.hooks.subprocess import working_directory -40 + from airflow.providers.standard.hooks.subprocess import working_directory -41 | +40 + +41 + from airflow.providers.standard.hooks.subprocess import working_directory | note: This is an unsafe fix and may change runtime behavior @@ -259,10 +256,8 @@ AIR302 [*] `airflow.operators.datetime.target_times_as_dates` is moved into `sta | help: Install `apache-airflow-providers-standard>=0.0.1` and use `target_times_as_dates` from `airflow.providers.standard.operators.datetime` instead. | -43 | - - from airflow.operators.datetime import target_times_as_dates -44 + from airflow.providers.standard.operators.datetime import target_times_as_dates -45 | +44 + +45 + from airflow.providers.standard.operators.datetime import target_times_as_dates | note: This is an unsafe fix and may change runtime behavior @@ -278,10 +273,8 @@ AIR302 [*] `airflow.operators.trigger_dagrun.TriggerDagRunLink` is moved into `s | help: Install `apache-airflow-providers-standard>=0.0.2` and use `TriggerDagRunLink` from `airflow.providers.standard.operators.trigger_dagrun` instead. | -47 | - - from airflow.operators.trigger_dagrun import TriggerDagRunLink -48 + from airflow.providers.standard.operators.trigger_dagrun import TriggerDagRunLink -49 | +48 + +49 + from airflow.providers.standard.operators.trigger_dagrun import TriggerDagRunLink | note: This is an unsafe fix and may change runtime behavior @@ -297,12 +290,9 @@ AIR302 [*] `airflow.sensors.external_task.ExternalTaskSensorLink` is moved into | help: Install `apache-airflow-providers-standard>=0.0.3` and use `ExternalDagLink` from `airflow.providers.standard.sensors.external_task` instead. | -52 | from airflow.sensors.external_task import ExternalTaskSensorLink 53 + from airflow.providers.standard.sensors.external_task import ExternalDagLink -54 | - - ExternalTaskSensorLink() -55 + ExternalDagLink() -56 | +54 + +55 ~ ExternalDagLink() | AIR302 [*] `airflow.sensors.time_delta.WaitSensor` is moved into `standard` provider in Airflow 3.0; @@ -317,10 +307,8 @@ AIR302 [*] `airflow.sensors.time_delta.WaitSensor` is moved into `standard` prov | help: Install `apache-airflow-providers-standard>=0.0.1` and use `WaitSensor` from `airflow.providers.standard.sensors.time_delta` instead. | -55 | - - from airflow.sensors.time_delta import WaitSensor -56 + from airflow.providers.standard.sensors.time_delta import WaitSensor -57 | +56 + +57 + from airflow.providers.standard.sensors.time_delta import WaitSensor | note: This is an unsafe fix and may change runtime behavior @@ -336,12 +324,9 @@ AIR302 [*] `airflow.operators.dummy.DummyOperator` is moved into `standard` prov | help: Install `apache-airflow-providers-standard>=0.0.2` and use `EmptyOperator` from `airflow.providers.standard.operators.empty` instead. | -60 | from airflow.operators.dummy import DummyOperator 61 + from airflow.providers.standard.operators.empty import EmptyOperator -62 | - - DummyOperator() -63 + EmptyOperator() -64 | +62 + +63 ~ EmptyOperator() | AIR302 [*] `airflow.operators.dummy.EmptyOperator` is moved into `standard` provider in Airflow 3.0; @@ -356,10 +341,8 @@ AIR302 [*] `airflow.operators.dummy.EmptyOperator` is moved into `standard` prov | help: Install `apache-airflow-providers-standard>=0.0.2` and use `EmptyOperator` from `airflow.providers.standard.operators.empty` instead. | -63 | - - from airflow.operators.dummy import EmptyOperator -64 + from airflow.providers.standard.operators.empty import EmptyOperator -65 | +64 + +65 + from airflow.providers.standard.operators.empty import EmptyOperator | note: This is an unsafe fix and may change runtime behavior @@ -375,9 +358,8 @@ AIR302 [*] `airflow.operators.dummy_operator.DummyOperator` is moved into `stand | help: Install `apache-airflow-providers-standard>=0.0.2` and use `EmptyOperator` from `airflow.providers.standard.operators.empty` instead. | -68 | from airflow.operators.dummy_operator import DummyOperator +68 ~ from airflow.operators.dummy_operator import DummyOperator 69 + from airflow.providers.standard.operators.empty import EmptyOperator -70 | | note: This is an unsafe fix and may change runtime behavior @@ -393,10 +375,8 @@ AIR302 [*] `airflow.operators.dummy_operator.EmptyOperator` is moved into `stand | help: Install `apache-airflow-providers-standard>=0.0.2` and use `EmptyOperator` from `airflow.providers.standard.operators.empty` instead. | -71 | - - from airflow.operators.dummy_operator import EmptyOperator -72 + from airflow.providers.standard.operators.empty import EmptyOperator -73 | +72 + +73 + from airflow.providers.standard.operators.empty import EmptyOperator | note: This is an unsafe fix and may change runtime behavior @@ -409,9 +389,7 @@ AIR302 [*] `airflow.sensors.external_task_sensor.ExternalTaskSensorLink` is move | ^^^^^^^^^^^^^^^^^^^^^^ help: Install `apache-airflow-providers-standard>=0.0.3` and use `ExternalDagLink` from `airflow.providers.standard.sensors.external_task` instead. | -76 | from airflow.sensors.external_task_sensor import ExternalTaskSensorLink 77 + from airflow.providers.standard.sensors.external_task import ExternalDagLink -78 | - - ExternalTaskSensorLink() -79 + ExternalDagLink() +78 + +79 ~ ExternalDagLink() | diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_zendesk.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_zendesk.py.snap index ebabfa0efbed2..7d9e7a23cd647 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_zendesk.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR302_AIR302_zendesk.py.snap @@ -10,9 +10,7 @@ AIR302 [*] `airflow.hooks.zendesk_hook.ZendeskHook` is moved into `zendesk` prov | ^^^^^^^^^^^ help: Install `apache-airflow-providers-zendesk>=1.0.0` and use `ZendeskHook` from `airflow.providers.zendesk.hooks.zendesk` instead. | -2 | - - from airflow.hooks.zendesk_hook import ZendeskHook -3 + from airflow.providers.zendesk.hooks.zendesk import ZendeskHook -4 | +3 + +4 + from airflow.providers.zendesk.hooks.zendesk import ZendeskHook | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR311_AIR311_args.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR311_AIR311_args.py.snap index 970495b1c08a5..100778b5d1ca5 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR311_AIR311_args.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR311_AIR311_args.py.snap @@ -8,12 +8,9 @@ AIR311 [*] `airflow.DAG` is removed in Airflow 3.0; It still works in Airflow 3. | ^^^ help: `DAG` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -4 | - - from airflow import DAG, dag 5 + from airflow import dag 6 | from airflow.operators.datetime import BranchDateTimeOperator 7 + from airflow.sdk import DAG -8 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR311_AIR311_names.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR311_AIR311_names.py.snap index fc73e40a2b2bd..5ed5faa080802 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR311_AIR311_names.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR311_AIR311_names.py.snap @@ -12,13 +12,10 @@ AIR311 [*] `airflow.Dataset` is removed in Airflow 3.0; It still works in Airflo | help: `Asset` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -17 | ) 18 + from airflow.sdk import Asset -19 | +19 + 20 | # airflow - - DatasetFromRoot() -21 + Asset() -22 | +21 ~ Asset() | AIR311 [*] `airflow.datasets.Dataset` is removed in Airflow 3.0; It still works in Airflow 3.0 but is expected to be removed in a future version. @@ -32,14 +29,12 @@ AIR311 [*] `airflow.datasets.Dataset` is removed in Airflow 3.0; It still works | help: `Asset` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -17 | ) 18 + from airflow.sdk import Asset -19 | --------------------------------------------------------------------------------- +19 + +20 | # airflow + … 23 | # airflow.datasets - - Dataset() -24 + Asset() -25 | DatasetAlias() +24 ~ Asset() | AIR311 [*] `airflow.datasets.DatasetAlias` is removed in Airflow 3.0; It still works in Airflow 3.0 but is expected to be removed in a future version. @@ -54,14 +49,12 @@ AIR311 [*] `airflow.datasets.DatasetAlias` is removed in Airflow 3.0; It still w | help: `AssetAlias` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -17 | ) 18 + from airflow.sdk import AssetAlias -19 | --------------------------------------------------------------------------------- +19 + +20 | # airflow + … 24 | Dataset() - - DatasetAlias() -25 + AssetAlias() -26 | DatasetAll() +25 ~ AssetAlias() | AIR311 [*] `airflow.datasets.DatasetAll` is removed in Airflow 3.0; It still works in Airflow 3.0 but is expected to be removed in a future version. @@ -76,14 +69,12 @@ AIR311 [*] `airflow.datasets.DatasetAll` is removed in Airflow 3.0; It still wor | help: `AssetAll` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -17 | ) 18 + from airflow.sdk import AssetAll -19 | --------------------------------------------------------------------------------- +19 + +20 | # airflow + … 25 | DatasetAlias() - - DatasetAll() -26 + AssetAll() -27 | DatasetAny() +26 ~ AssetAll() | AIR311 [*] `airflow.datasets.DatasetAny` is removed in Airflow 3.0; It still works in Airflow 3.0 but is expected to be removed in a future version. @@ -98,14 +89,12 @@ AIR311 [*] `airflow.datasets.DatasetAny` is removed in Airflow 3.0; It still wor | help: `AssetAny` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -17 | ) 18 + from airflow.sdk import AssetAny -19 | --------------------------------------------------------------------------------- +19 + +20 | # airflow + … 26 | DatasetAll() - - DatasetAny() -27 + AssetAny() -28 | Metadata() +27 ~ AssetAny() | AIR311 [*] `airflow.datasets.metadata.Metadata` is removed in Airflow 3.0; It still works in Airflow 3.0 but is expected to be removed in a future version. @@ -119,13 +108,11 @@ AIR311 [*] `airflow.datasets.metadata.Metadata` is removed in Airflow 3.0; It st | help: `Metadata` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -10 | ) - - from airflow.datasets.metadata import Metadata -11 | from airflow.decorators import ( --------------------------------------------------------------------------------- -16 | ) -17 + from airflow.sdk import Metadata -18 | +11 + +12 | from airflow.decorators import ( + … +17 | ) +18 + from airflow.sdk import Metadata | note: This is an unsafe fix and may change runtime behavior @@ -141,14 +128,12 @@ AIR311 [*] `airflow.datasets.expand_alias_to_datasets` is removed in Airflow 3.0 | help: Use `expand_alias_to_assets` from `airflow.models.asset` instead. | -17 | ) 18 + from airflow.models.asset import expand_alias_to_assets -19 | --------------------------------------------------------------------------------- +19 + +20 | # airflow + … 28 | Metadata() - - expand_alias_to_datasets() -29 + expand_alias_to_assets() -30 | +29 ~ expand_alias_to_assets() | AIR311 [*] `airflow.decorators.dag` is removed in Airflow 3.0; It still works in Airflow 3.0 but is expected to be removed in a future version. @@ -162,14 +147,12 @@ AIR311 [*] `airflow.decorators.dag` is removed in Airflow 3.0; It still works in | help: `dag` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -12 | from airflow.decorators import ( - - dag, -13 | setup, -14 | task, -15 | task_group, -16 | ) +12 + from airflow.decorators import ( +13 + setup, +14 + task, +15 + task_group, +16 + ) 17 + from airflow.sdk import dag -18 | | note: This is an unsafe fix and may change runtime behavior @@ -185,12 +168,12 @@ AIR311 [*] `airflow.decorators.task` is removed in Airflow 3.0; It still works i | help: `task` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -14 | setup, - - task, -15 | task_group, -16 | ) +12 + from airflow.decorators import ( +13 + dag, +14 + setup, +15 + task_group, +16 + ) 17 + from airflow.sdk import task -18 | | note: This is an unsafe fix and may change runtime behavior @@ -206,11 +189,12 @@ AIR311 [*] `airflow.decorators.task_group` is removed in Airflow 3.0; It still w | help: `task_group` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -15 | task, - - task_group, -16 | ) +12 + from airflow.decorators import ( +13 + dag, +14 + setup, +15 + task, +16 + ) 17 + from airflow.sdk import task_group -18 | | note: This is an unsafe fix and may change runtime behavior @@ -226,13 +210,12 @@ AIR311 [*] `airflow.decorators.setup` is removed in Airflow 3.0; It still works | help: `setup` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -13 | dag, - - setup, -14 | task, -15 | task_group, -16 | ) +12 + from airflow.decorators import ( +13 + dag, +14 + task, +15 + task_group, +16 + ) 17 + from airflow.sdk import setup -18 | | note: This is an unsafe fix and may change runtime behavior @@ -247,13 +230,11 @@ AIR311 [*] `airflow.decorators.teardown` is removed in Airflow 3.0; It still wor | help: `teardown` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -34 | setup() - - from airflow.decorators import teardown -35 | from airflow.io.path import ObjectStoragePath --------------------------------------------------------------------------------- -44 | from airflow.models.dag import DAG as DAGFromDag -45 + from airflow.sdk import teardown -46 | +35 + +36 | from airflow.io.path import ObjectStoragePath + … +45 | from airflow.models.dag import DAG as DAGFromDag +46 + from airflow.sdk import teardown | note: This is an unsafe fix and may change runtime behavior @@ -267,13 +248,11 @@ AIR311 [*] `airflow.io.path.ObjectStoragePath` is removed in Airflow 3.0; It sti | help: `ObjectStoragePath` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -35 | from airflow.decorators import teardown - - from airflow.io.path import ObjectStoragePath -36 | from airflow.io.store import attach --------------------------------------------------------------------------------- -44 | from airflow.models.dag import DAG as DAGFromDag -45 + from airflow.sdk import ObjectStoragePath -46 | +36 + +37 | from airflow.io.store import attach + … +45 | from airflow.models.dag import DAG as DAGFromDag +46 + from airflow.sdk import ObjectStoragePath | note: This is an unsafe fix and may change runtime behavior @@ -289,13 +268,11 @@ AIR311 [*] `airflow.io.store.attach` is removed in Airflow 3.0; It still works i | help: `attach` has been moved to `airflow.sdk.io` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -36 | from airflow.io.path import ObjectStoragePath - - from airflow.io.store import attach -37 | from airflow.models import DAG as DAGFromModel --------------------------------------------------------------------------------- -44 | from airflow.models.dag import DAG as DAGFromDag -45 + from airflow.sdk.io import attach -46 | +37 + +38 | from airflow.models import DAG as DAGFromModel + … +45 | from airflow.models.dag import DAG as DAGFromDag +46 + from airflow.sdk.io import attach | note: This is an unsafe fix and may change runtime behavior @@ -310,13 +287,13 @@ AIR311 [*] `airflow.models.Connection` is removed in Airflow 3.0; It still works | help: `Connection` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -39 | from airflow.models import ( - - Connection, -40 | Variable, --------------------------------------------------------------------------------- +39 + from airflow.models import ( +40 + Variable, +41 + ) +42 | from airflow.models.baseoperator import chain, chain_linear, cross_downstream +43 | from airflow.models.baseoperatorlink import BaseOperatorLink 44 | from airflow.models.dag import DAG as DAGFromDag 45 + from airflow.sdk import Connection -46 | | note: This is an unsafe fix and may change runtime behavior @@ -331,14 +308,12 @@ AIR311 [*] `airflow.models.DAG` is removed in Airflow 3.0; It still works in Air | help: `DAG` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -45 | from airflow.models.dag import DAG as DAGFromDag 46 + from airflow.sdk import DAG -47 | --------------------------------------------------------------------------------- +47 + +48 | # airflow.decorators + … 56 | Connection() - - DAGFromModel() -57 + DAG() -58 | Variable() +57 ~ DAG() | AIR311 [*] `airflow.models.Variable` is removed in Airflow 3.0; It still works in Airflow 3.0 but is expected to be removed in a future version. @@ -353,14 +328,13 @@ AIR311 [*] `airflow.models.Variable` is removed in Airflow 3.0; It still works i | help: `Variable` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -40 | Connection, - - Variable, -41 | ) +39 + from airflow.models import ( +40 + Connection, +41 + ) 42 | from airflow.models.baseoperator import chain, chain_linear, cross_downstream 43 | from airflow.models.baseoperatorlink import BaseOperatorLink 44 | from airflow.models.dag import DAG as DAGFromDag 45 + from airflow.sdk import Variable -46 | | note: This is an unsafe fix and may change runtime behavior @@ -375,13 +349,10 @@ AIR311 [*] `airflow.models.baseoperator.chain` is removed in Airflow 3.0; It sti | help: `chain` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -42 | ) - - from airflow.models.baseoperator import chain, chain_linear, cross_downstream 43 + from airflow.models.baseoperator import chain_linear, cross_downstream 44 | from airflow.models.baseoperatorlink import BaseOperatorLink 45 | from airflow.models.dag import DAG as DAGFromDag 46 + from airflow.sdk import chain -47 | | note: This is an unsafe fix and may change runtime behavior @@ -396,13 +367,10 @@ AIR311 [*] `airflow.models.baseoperator.chain_linear` is removed in Airflow 3.0; | help: `chain_linear` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -42 | ) - - from airflow.models.baseoperator import chain, chain_linear, cross_downstream 43 + from airflow.models.baseoperator import chain, cross_downstream 44 | from airflow.models.baseoperatorlink import BaseOperatorLink 45 | from airflow.models.dag import DAG as DAGFromDag 46 + from airflow.sdk import chain_linear -47 | | note: This is an unsafe fix and may change runtime behavior @@ -418,13 +386,10 @@ AIR311 [*] `airflow.models.baseoperator.cross_downstream` is removed in Airflow | help: `cross_downstream` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -42 | ) - - from airflow.models.baseoperator import chain, chain_linear, cross_downstream 43 + from airflow.models.baseoperator import chain, chain_linear 44 | from airflow.models.baseoperatorlink import BaseOperatorLink 45 | from airflow.models.dag import DAG as DAGFromDag 46 + from airflow.sdk import cross_downstream -47 | | note: This is an unsafe fix and may change runtime behavior @@ -439,11 +404,9 @@ AIR311 [*] `airflow.models.baseoperatorlink.BaseOperatorLink` is removed in Airf | help: `BaseOperatorLink` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -43 | from airflow.models.baseoperator import chain, chain_linear, cross_downstream - - from airflow.models.baseoperatorlink import BaseOperatorLink -44 | from airflow.models.dag import DAG as DAGFromDag -45 + from airflow.sdk import BaseOperatorLink -46 | +44 + +45 | from airflow.models.dag import DAG as DAGFromDag +46 + from airflow.sdk import BaseOperatorLink | note: This is an unsafe fix and may change runtime behavior @@ -458,14 +421,12 @@ AIR311 [*] `airflow.models.dag.DAG` is removed in Airflow 3.0; It still works in | help: `DAG` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -45 | from airflow.models.dag import DAG as DAGFromDag 46 + from airflow.sdk import DAG -47 | --------------------------------------------------------------------------------- +47 + +48 | # airflow.decorators + … 68 | # airflow.models.dag - - DAGFromDag() -69 + DAG() -70 | from airflow.timetables.datasets import DatasetOrTimeSchedule +69 ~ DAG() | AIR311 [*] `airflow.timetables.datasets.DatasetOrTimeSchedule` is removed in Airflow 3.0; It still works in Airflow 3.0 but is expected to be removed in a future version. @@ -479,13 +440,10 @@ AIR311 [*] `airflow.timetables.datasets.DatasetOrTimeSchedule` is removed in Air | help: Use `AssetOrTimeSchedule` from `airflow.timetables.assets` instead. | -70 | from airflow.utils.dag_parsing_context import get_parsing_context 71 + from airflow.timetables.assets import AssetOrTimeSchedule -72 | +72 + 73 | # airflow.timetables.datasets - - DatasetOrTimeSchedule(datasets=[]) -74 + AssetOrTimeSchedule(datasets=[]) -75 | +74 ~ AssetOrTimeSchedule(datasets=[]) | AIR311 [*] `datasets` is removed in Airflow 3.0; It still works in Airflow 3.0 but is expected to be removed in a future version. @@ -499,10 +457,8 @@ AIR311 [*] `datasets` is removed in Airflow 3.0; It still works in Airflow 3.0 b | help: Use `assets` instead | -72 | # airflow.timetables.datasets - - DatasetOrTimeSchedule(datasets=[]) +73 - DatasetOrTimeSchedule(datasets=[]) 73 + DatasetOrTimeSchedule(assets=[]) -74 | | AIR311 [*] `airflow.utils.dag_parsing_context.get_parsing_context` is removed in Airflow 3.0; It still works in Airflow 3.0 but is expected to be removed in a future version. @@ -516,10 +472,8 @@ AIR311 [*] `airflow.utils.dag_parsing_context.get_parsing_context` is removed in | help: `get_parsing_context` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -69 | from airflow.timetables.datasets import DatasetOrTimeSchedule - - from airflow.utils.dag_parsing_context import get_parsing_context -70 + from airflow.sdk import get_parsing_context -71 | +70 + +71 + from airflow.sdk import get_parsing_context | note: This is an unsafe fix and may change runtime behavior @@ -534,13 +488,13 @@ AIR311 [*] `airflow.decorators.base.DecoratedMappedOperator` is removed in Airfl | help: `DecoratedMappedOperator` has been moved to `airflow.sdk.bases.decorator` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -78 | from airflow.decorators.base import ( - - DecoratedMappedOperator, -79 | DecoratedOperator, --------------------------------------------------------------------------------- -83 | ) +78 + from airflow.decorators.base import ( +79 + DecoratedOperator, +80 + TaskDecorator, +81 + get_unique_task_id, +82 + task_decorator_factory, +83 + ) 84 + from airflow.sdk.bases.decorator import DecoratedMappedOperator -85 | | note: This is an unsafe fix and may change runtime behavior @@ -556,14 +510,13 @@ AIR311 [*] `airflow.decorators.base.DecoratedOperator` is removed in Airflow 3.0 | help: `DecoratedOperator` has been moved to `airflow.sdk.bases.decorator` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -79 | DecoratedMappedOperator, - - DecoratedOperator, -80 | TaskDecorator, -81 | get_unique_task_id, -82 | task_decorator_factory, -83 | ) +78 + from airflow.decorators.base import ( +79 + DecoratedMappedOperator, +80 + TaskDecorator, +81 + get_unique_task_id, +82 + task_decorator_factory, +83 + ) 84 + from airflow.sdk.bases.decorator import DecoratedOperator -85 | | note: This is an unsafe fix and may change runtime behavior @@ -579,13 +532,13 @@ AIR311 [*] `airflow.decorators.base.TaskDecorator` is removed in Airflow 3.0; It | help: `TaskDecorator` has been moved to `airflow.sdk.bases.decorator` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -80 | DecoratedOperator, - - TaskDecorator, -81 | get_unique_task_id, -82 | task_decorator_factory, -83 | ) +78 + from airflow.decorators.base import ( +79 + DecoratedMappedOperator, +80 + DecoratedOperator, +81 + get_unique_task_id, +82 + task_decorator_factory, +83 + ) 84 + from airflow.sdk.bases.decorator import TaskDecorator -85 | | note: This is an unsafe fix and may change runtime behavior @@ -600,12 +553,13 @@ AIR311 [*] `airflow.decorators.base.get_unique_task_id` is removed in Airflow 3. | help: `get_unique_task_id` has been moved to `airflow.sdk.bases.decorator` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -81 | TaskDecorator, - - get_unique_task_id, -82 | task_decorator_factory, -83 | ) +78 + from airflow.decorators.base import ( +79 + DecoratedMappedOperator, +80 + DecoratedOperator, +81 + TaskDecorator, +82 + task_decorator_factory, +83 + ) 84 + from airflow.sdk.bases.decorator import get_unique_task_id -85 | | note: This is an unsafe fix and may change runtime behavior @@ -618,11 +572,13 @@ AIR311 [*] `airflow.decorators.base.task_decorator_factory` is removed in Airflo | ^^^^^^^^^^^^^^^^^^^^^^ help: `task_decorator_factory` has been moved to `airflow.sdk.bases.decorator` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -82 | get_unique_task_id, - - task_decorator_factory, -83 | ) +78 + from airflow.decorators.base import ( +79 + DecoratedMappedOperator, +80 + DecoratedOperator, +81 + TaskDecorator, +82 + get_unique_task_id, +83 + ) 84 + from airflow.sdk.bases.decorator import task_decorator_factory -85 | | note: This is an unsafe fix and may change runtime behavior @@ -637,11 +593,8 @@ AIR311 [*] `airflow.models.Param` is removed in Airflow 3.0; It still works in A | help: `Param` has been moved to `airflow.sdk.definitions.param` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -93 | - - from airflow.models import DagParam, Param, ParamsDict 94 + from airflow.models import DagParam, ParamsDict 95 + from airflow.sdk.definitions.param import Param -96 | | note: This is an unsafe fix and may change runtime behavior @@ -656,11 +609,8 @@ AIR311 [*] `airflow.models.DagParam` is removed in Airflow 3.0; It still works i | help: `DagParam` has been moved to `airflow.sdk.definitions.param` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -93 | - - from airflow.models import DagParam, Param, ParamsDict 94 + from airflow.models import Param, ParamsDict 95 + from airflow.sdk.definitions.param import DagParam -96 | | note: This is an unsafe fix and may change runtime behavior @@ -673,11 +623,8 @@ AIR311 [*] `airflow.models.ParamsDict` is removed in Airflow 3.0; It still works | ^^^^^^^^^^ help: `ParamsDict` has been moved to `airflow.sdk.definitions.param` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -93 | - - from airflow.models import DagParam, Param, ParamsDict 94 + from airflow.models import DagParam, Param 95 + from airflow.sdk.definitions.param import ParamsDict -96 | | note: This is an unsafe fix and may change runtime behavior @@ -692,11 +639,8 @@ AIR311 [*] `airflow.models.param.Param` is removed in Airflow 3.0; It still work | help: `Param` has been moved to `airflow.sdk.definitions.param` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -101 | - - from airflow.models.param import DagParam, Param, ParamsDict 102 + from airflow.models.param import DagParam, ParamsDict 103 + from airflow.sdk.definitions.param import Param -104 | | note: This is an unsafe fix and may change runtime behavior @@ -711,11 +655,8 @@ AIR311 [*] `airflow.models.param.DagParam` is removed in Airflow 3.0; It still w | help: `DagParam` has been moved to `airflow.sdk.definitions.param` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -101 | - - from airflow.models.param import DagParam, Param, ParamsDict 102 + from airflow.models.param import Param, ParamsDict 103 + from airflow.sdk.definitions.param import DagParam -104 | | note: This is an unsafe fix and may change runtime behavior @@ -728,11 +669,8 @@ AIR311 [*] `airflow.models.param.ParamsDict` is removed in Airflow 3.0; It still | ^^^^^^^^^^ help: `ParamsDict` has been moved to `airflow.sdk.definitions.param` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -101 | - - from airflow.models.param import DagParam, Param, ParamsDict 102 + from airflow.models.param import DagParam, Param 103 + from airflow.sdk.definitions.param import ParamsDict -104 | | note: This is an unsafe fix and may change runtime behavior @@ -747,13 +685,11 @@ AIR311 [*] `airflow.sensors.base.BaseSensorOperator` is removed in Airflow 3.0; | help: `BaseSensorOperator` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -110 | from airflow.sensors.base import ( - - BaseSensorOperator, -111 | PokeReturnValue, -112 | poke_mode_only, -113 | ) +110 + from airflow.sensors.base import ( +111 + PokeReturnValue, +112 + poke_mode_only, +113 + ) 114 + from airflow.sdk import BaseSensorOperator -115 | | note: This is an unsafe fix and may change runtime behavior @@ -768,12 +704,11 @@ AIR311 [*] `airflow.sensors.base.PokeReturnValue` is removed in Airflow 3.0; It | help: `PokeReturnValue` has been moved to `airflow.sdk` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -111 | BaseSensorOperator, - - PokeReturnValue, -112 | poke_mode_only, -113 | ) +110 + from airflow.sensors.base import ( +111 + BaseSensorOperator, +112 + poke_mode_only, +113 + ) 114 + from airflow.sdk import PokeReturnValue -115 | | note: This is an unsafe fix and may change runtime behavior @@ -786,10 +721,10 @@ AIR311 [*] `airflow.sensors.base.poke_mode_only` is removed in Airflow 3.0; It s | ^^^^^^^^^^^^^^ help: `poke_mode_only` has been moved to `airflow.sdk.bases.sensor` since Airflow 3.0 (with apache-airflow-task-sdk>=1.0.0). | -112 | PokeReturnValue, - - poke_mode_only, -113 | ) +110 + from airflow.sensors.base import ( +111 + BaseSensorOperator, +112 + PokeReturnValue, +113 + ) 114 + from airflow.sdk.bases.sensor import poke_mode_only -115 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR312_AIR312.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR312_AIR312.py.snap index 2fefab2699daf..3c7b6c0ff48b3 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR312_AIR312.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR312_AIR312.py.snap @@ -13,13 +13,11 @@ AIR312 [*] `airflow.hooks.filesystem.FSHook` is deprecated and moved into `stand | help: Install `apache-airflow-providers-standard>=0.0.1` and use `FSHook` from `airflow.providers.standard.hooks.filesystem` instead. | -2 | - - from airflow.hooks.filesystem import FSHook -3 | from airflow.hooks.package_index import PackageIndexHook --------------------------------------------------------------------------------- -10 | from airflow.operators.weekday import BranchDayOfWeekOperator -11 + from airflow.providers.standard.hooks.filesystem import FSHook -12 | + 3 + + 4 | from airflow.hooks.package_index import PackageIndexHook + … +11 | from airflow.operators.weekday import BranchDayOfWeekOperator +12 + from airflow.providers.standard.hooks.filesystem import FSHook | note: This is an unsafe fix and may change runtime behavior @@ -33,13 +31,11 @@ AIR312 [*] `airflow.hooks.package_index.PackageIndexHook` is deprecated and move | help: Install `apache-airflow-providers-standard>=0.0.1` and use `PackageIndexHook` from `airflow.providers.standard.hooks.package_index` instead. | -3 | from airflow.hooks.filesystem import FSHook - - from airflow.hooks.package_index import PackageIndexHook -4 | from airflow.hooks.subprocess import SubprocessHook --------------------------------------------------------------------------------- -10 | from airflow.operators.weekday import BranchDayOfWeekOperator -11 + from airflow.providers.standard.hooks.package_index import PackageIndexHook -12 | + 4 + + 5 | from airflow.hooks.subprocess import SubprocessHook + … +11 | from airflow.operators.weekday import BranchDayOfWeekOperator +12 + from airflow.providers.standard.hooks.package_index import PackageIndexHook | note: This is an unsafe fix and may change runtime behavior @@ -55,13 +51,11 @@ AIR312 [*] `airflow.hooks.subprocess.SubprocessHook` is deprecated and moved int | help: Install `apache-airflow-providers-standard>=0.0.3` and use `SubprocessHook` from `airflow.providers.standard.hooks.subprocess` instead. | -4 | from airflow.hooks.package_index import PackageIndexHook - - from airflow.hooks.subprocess import SubprocessHook -5 | from airflow.operators.bash import BashOperator --------------------------------------------------------------------------------- -10 | from airflow.operators.weekday import BranchDayOfWeekOperator -11 + from airflow.providers.standard.hooks.subprocess import SubprocessHook -12 | + 5 + + 6 | from airflow.operators.bash import BashOperator + … +11 | from airflow.operators.weekday import BranchDayOfWeekOperator +12 + from airflow.providers.standard.hooks.subprocess import SubprocessHook | note: This is an unsafe fix and may change runtime behavior @@ -77,13 +71,11 @@ AIR312 [*] `airflow.operators.bash.BashOperator` is deprecated and moved into `s | help: Install `apache-airflow-providers-standard>=0.0.1` and use `BashOperator` from `airflow.providers.standard.operators.bash` instead. | -5 | from airflow.hooks.subprocess import SubprocessHook - - from airflow.operators.bash import BashOperator -6 | from airflow.operators.datetime import BranchDateTimeOperator --------------------------------------------------------------------------------- -10 | from airflow.operators.weekday import BranchDayOfWeekOperator -11 + from airflow.providers.standard.operators.bash import BashOperator -12 | + 6 + + 7 | from airflow.operators.datetime import BranchDateTimeOperator + … +11 | from airflow.operators.weekday import BranchDayOfWeekOperator +12 + from airflow.providers.standard.operators.bash import BashOperator | note: This is an unsafe fix and may change runtime behavior @@ -98,14 +90,11 @@ AIR312 [*] `airflow.operators.datetime.BranchDateTimeOperator` is deprecated and | help: Install `apache-airflow-providers-standard>=0.0.1` and use `BranchDateTimeOperator` from `airflow.providers.standard.operators.datetime` instead. | -6 | from airflow.operators.bash import BashOperator - - from airflow.operators.datetime import BranchDateTimeOperator -7 | from airflow.operators.empty import EmptyOperator -8 | from airflow.operators.latest_only import LatestOnlyOperator -9 | from airflow.operators.trigger_dagrun import TriggerDagRunOperator -10 | from airflow.operators.weekday import BranchDayOfWeekOperator -11 + from airflow.providers.standard.operators.datetime import BranchDateTimeOperator -12 | + 7 + + 8 | from airflow.operators.empty import EmptyOperator + … +11 | from airflow.operators.weekday import BranchDayOfWeekOperator +12 + from airflow.providers.standard.operators.datetime import BranchDateTimeOperator | note: This is an unsafe fix and may change runtime behavior @@ -120,11 +109,9 @@ AIR312 [*] `airflow.operators.trigger_dagrun.TriggerDagRunOperator` is deprecate | help: Install `apache-airflow-providers-standard>=0.0.2` and use `TriggerDagRunOperator` from `airflow.providers.standard.operators.trigger_dagrun` instead. | -9 | from airflow.operators.latest_only import LatestOnlyOperator - - from airflow.operators.trigger_dagrun import TriggerDagRunOperator -10 | from airflow.operators.weekday import BranchDayOfWeekOperator -11 + from airflow.providers.standard.operators.trigger_dagrun import TriggerDagRunOperator -12 | +10 + +11 | from airflow.operators.weekday import BranchDayOfWeekOperator +12 + from airflow.providers.standard.operators.trigger_dagrun import TriggerDagRunOperator | note: This is an unsafe fix and may change runtime behavior @@ -140,13 +127,11 @@ AIR312 [*] `airflow.operators.empty.EmptyOperator` is deprecated and moved into | help: Install `apache-airflow-providers-standard>=0.0.2` and use `EmptyOperator` from `airflow.providers.standard.operators.empty` instead. | -7 | from airflow.operators.datetime import BranchDateTimeOperator - - from airflow.operators.empty import EmptyOperator -8 | from airflow.operators.latest_only import LatestOnlyOperator -9 | from airflow.operators.trigger_dagrun import TriggerDagRunOperator -10 | from airflow.operators.weekday import BranchDayOfWeekOperator -11 + from airflow.providers.standard.operators.empty import EmptyOperator -12 | + 8 + + 9 | from airflow.operators.latest_only import LatestOnlyOperator +10 | from airflow.operators.trigger_dagrun import TriggerDagRunOperator +11 | from airflow.operators.weekday import BranchDayOfWeekOperator +12 + from airflow.providers.standard.operators.empty import EmptyOperator | note: This is an unsafe fix and may change runtime behavior @@ -161,12 +146,10 @@ AIR312 [*] `airflow.operators.latest_only.LatestOnlyOperator` is deprecated and | help: Install `apache-airflow-providers-standard>=0.0.3` and use `LatestOnlyOperator` from `airflow.providers.standard.operators.latest_only` instead. | -8 | from airflow.operators.empty import EmptyOperator - - from airflow.operators.latest_only import LatestOnlyOperator -9 | from airflow.operators.trigger_dagrun import TriggerDagRunOperator -10 | from airflow.operators.weekday import BranchDayOfWeekOperator -11 + from airflow.providers.standard.operators.latest_only import LatestOnlyOperator -12 | + 9 + +10 | from airflow.operators.trigger_dagrun import TriggerDagRunOperator +11 | from airflow.operators.weekday import BranchDayOfWeekOperator +12 + from airflow.providers.standard.operators.latest_only import LatestOnlyOperator | note: This is an unsafe fix and may change runtime behavior @@ -181,10 +164,8 @@ AIR312 [*] `airflow.operators.weekday.BranchDayOfWeekOperator` is deprecated and | help: Install `apache-airflow-providers-standard>=0.0.1` and use `BranchDayOfWeekOperator` from `airflow.providers.standard.operators.weekday` instead. | -10 | from airflow.operators.trigger_dagrun import TriggerDagRunOperator - - from airflow.operators.weekday import BranchDayOfWeekOperator -11 + from airflow.providers.standard.operators.weekday import BranchDayOfWeekOperator -12 | +11 + +12 + from airflow.providers.standard.operators.weekday import BranchDayOfWeekOperator | note: This is an unsafe fix and may change runtime behavior @@ -200,13 +181,14 @@ AIR312 [*] `airflow.operators.python.BranchPythonOperator` is deprecated and mov | help: Install `apache-airflow-providers-standard>=0.0.1` and use `BranchPythonOperator` from `airflow.providers.standard.operators.python` instead. | -25 | from airflow.operators.python import ( - - BranchPythonOperator, -26 | PythonOperator, --------------------------------------------------------------------------------- +25 + from airflow.operators.python import ( +26 + PythonOperator, +27 + PythonVirtualenvOperator, +28 + ShortCircuitOperator, +29 + ) +30 | from airflow.sensors.bash import BashSensor 31 | from airflow.sensors.date_time import DateTimeSensor 32 + from airflow.providers.standard.operators.python import BranchPythonOperator -33 | | note: This is an unsafe fix and may change runtime behavior @@ -221,13 +203,14 @@ AIR312 [*] `airflow.operators.python.PythonOperator` is deprecated and moved int | help: Install `apache-airflow-providers-standard>=0.0.1` and use `PythonOperator` from `airflow.providers.standard.operators.python` instead. | -26 | BranchPythonOperator, - - PythonOperator, -27 | PythonVirtualenvOperator, --------------------------------------------------------------------------------- +25 + from airflow.operators.python import ( +26 + BranchPythonOperator, +27 + PythonVirtualenvOperator, +28 + ShortCircuitOperator, +29 + ) +30 | from airflow.sensors.bash import BashSensor 31 | from airflow.sensors.date_time import DateTimeSensor 32 + from airflow.providers.standard.operators.python import PythonOperator -33 | | note: This is an unsafe fix and may change runtime behavior @@ -242,14 +225,14 @@ AIR312 [*] `airflow.operators.python.PythonVirtualenvOperator` is deprecated and | help: Install `apache-airflow-providers-standard>=0.0.1` and use `PythonVirtualenvOperator` from `airflow.providers.standard.operators.python` instead. | -27 | PythonOperator, - - PythonVirtualenvOperator, -28 | ShortCircuitOperator, -29 | ) +25 + from airflow.operators.python import ( +26 + BranchPythonOperator, +27 + PythonOperator, +28 + ShortCircuitOperator, +29 + ) 30 | from airflow.sensors.bash import BashSensor 31 | from airflow.sensors.date_time import DateTimeSensor 32 + from airflow.providers.standard.operators.python import PythonVirtualenvOperator -33 | | note: This is an unsafe fix and may change runtime behavior @@ -265,13 +248,14 @@ AIR312 [*] `airflow.operators.python.ShortCircuitOperator` is deprecated and mov | help: Install `apache-airflow-providers-standard>=0.0.1` and use `ShortCircuitOperator` from `airflow.providers.standard.operators.python` instead. | -28 | PythonVirtualenvOperator, - - ShortCircuitOperator, -29 | ) +25 + from airflow.operators.python import ( +26 + BranchPythonOperator, +27 + PythonOperator, +28 + PythonVirtualenvOperator, +29 + ) 30 | from airflow.sensors.bash import BashSensor 31 | from airflow.sensors.date_time import DateTimeSensor 32 + from airflow.providers.standard.operators.python import ShortCircuitOperator -33 | | note: This is an unsafe fix and may change runtime behavior @@ -287,11 +271,9 @@ AIR312 [*] `airflow.sensors.bash.BashSensor` is deprecated and moved into `stand | help: Install `apache-airflow-providers-standard>=0.0.1` and use `BashSensor` from `airflow.providers.standard.sensor.bash` instead. | -30 | ) - - from airflow.sensors.bash import BashSensor -31 | from airflow.sensors.date_time import DateTimeSensor -32 + from airflow.providers.standard.sensor.bash import BashSensor -33 | +31 + +32 | from airflow.sensors.date_time import DateTimeSensor +33 + from airflow.providers.standard.sensor.bash import BashSensor | note: This is an unsafe fix and may change runtime behavior @@ -306,10 +288,8 @@ AIR312 [*] `airflow.sensors.date_time.DateTimeSensor` is deprecated and moved in | help: Install `apache-airflow-providers-standard>=0.0.1` and use `DateTimeSensor` from `airflow.providers.standard.sensors.date_time` instead. | -31 | from airflow.sensors.bash import BashSensor - - from airflow.sensors.date_time import DateTimeSensor -32 + from airflow.providers.standard.sensors.date_time import DateTimeSensor -33 | +32 + +33 + from airflow.providers.standard.sensors.date_time import DateTimeSensor | note: This is an unsafe fix and may change runtime behavior @@ -325,13 +305,15 @@ AIR312 [*] `airflow.operators.python.BranchPythonOperator` is deprecated and mov | help: Install `apache-airflow-providers-standard>=0.0.1` and use `BranchPythonOperator` from `airflow.providers.standard.operators.python` instead. | -25 | from airflow.operators.python import ( - - BranchPythonOperator, -26 | PythonOperator, --------------------------------------------------------------------------------- +25 + from airflow.operators.python import ( +26 + PythonOperator, +27 + PythonVirtualenvOperator, +28 + ShortCircuitOperator, +29 + ) +30 | from airflow.sensors.bash import BashSensor + … 46 | from airflow.sensors.python import PythonSensor 47 + from airflow.providers.standard.operators.python import BranchPythonOperator -48 | | note: This is an unsafe fix and may change runtime behavior @@ -346,13 +328,15 @@ AIR312 [*] `airflow.operators.python.PythonOperator` is deprecated and moved int | help: Install `apache-airflow-providers-standard>=0.0.1` and use `PythonOperator` from `airflow.providers.standard.operators.python` instead. | -26 | BranchPythonOperator, - - PythonOperator, -27 | PythonVirtualenvOperator, --------------------------------------------------------------------------------- +25 + from airflow.operators.python import ( +26 + BranchPythonOperator, +27 + PythonVirtualenvOperator, +28 + ShortCircuitOperator, +29 + ) +30 | from airflow.sensors.bash import BashSensor + … 46 | from airflow.sensors.python import PythonSensor 47 + from airflow.providers.standard.operators.python import PythonOperator -48 | | note: This is an unsafe fix and may change runtime behavior @@ -368,13 +352,15 @@ AIR312 [*] `airflow.operators.python.PythonVirtualenvOperator` is deprecated and | help: Install `apache-airflow-providers-standard>=0.0.1` and use `PythonVirtualenvOperator` from `airflow.providers.standard.operators.python` instead. | -27 | PythonOperator, - - PythonVirtualenvOperator, -28 | ShortCircuitOperator, --------------------------------------------------------------------------------- +25 + from airflow.operators.python import ( +26 + BranchPythonOperator, +27 + PythonOperator, +28 + ShortCircuitOperator, +29 + ) +30 | from airflow.sensors.bash import BashSensor + … 46 | from airflow.sensors.python import PythonSensor 47 + from airflow.providers.standard.operators.python import PythonVirtualenvOperator -48 | | note: This is an unsafe fix and may change runtime behavior @@ -390,13 +376,15 @@ AIR312 [*] `airflow.operators.python.ShortCircuitOperator` is deprecated and mov | help: Install `apache-airflow-providers-standard>=0.0.1` and use `ShortCircuitOperator` from `airflow.providers.standard.operators.python` instead. | -28 | PythonVirtualenvOperator, - - ShortCircuitOperator, -29 | ) --------------------------------------------------------------------------------- +25 + from airflow.operators.python import ( +26 + BranchPythonOperator, +27 + PythonOperator, +28 + PythonVirtualenvOperator, +29 + ) +30 | from airflow.sensors.bash import BashSensor + … 46 | from airflow.sensors.python import PythonSensor 47 + from airflow.providers.standard.operators.python import ShortCircuitOperator -48 | | note: This is an unsafe fix and may change runtime behavior @@ -412,13 +400,11 @@ AIR312 [*] `airflow.sensors.date_time.DateTimeSensorAsync` is deprecated and mov | help: Install `apache-airflow-providers-standard>=0.0.1` and use `DateTimeSensorAsync` from `airflow.providers.standard.sensors.date_time` instead. | -40 | DateTimeSensor() - - from airflow.sensors.date_time import DateTimeSensorAsync -41 | from airflow.sensors.external_task import ( --------------------------------------------------------------------------------- -46 | from airflow.sensors.python import PythonSensor -47 + from airflow.providers.standard.sensors.date_time import DateTimeSensorAsync -48 | +41 + +42 | from airflow.sensors.external_task import ( + … +47 | from airflow.sensors.python import PythonSensor +48 + from airflow.providers.standard.sensors.date_time import DateTimeSensorAsync | note: This is an unsafe fix and may change runtime behavior @@ -434,14 +420,12 @@ AIR312 [*] `airflow.sensors.external_task.ExternalTaskMarker` is deprecated and | help: Install `apache-airflow-providers-standard>=0.0.3` and use `ExternalTaskMarker` from `airflow.providers.standard.sensors.external_task` instead. | -42 | from airflow.sensors.external_task import ( - - ExternalTaskMarker, -43 | ExternalTaskSensor, -44 | ) +42 + from airflow.sensors.external_task import ( +43 + ExternalTaskSensor, +44 + ) 45 | from airflow.sensors.filesystem import FileSensor 46 | from airflow.sensors.python import PythonSensor 47 + from airflow.providers.standard.sensors.external_task import ExternalTaskMarker -48 | | note: This is an unsafe fix and may change runtime behavior @@ -457,13 +441,12 @@ AIR312 [*] `airflow.sensors.external_task.ExternalTaskSensor` is deprecated and | help: Install `apache-airflow-providers-standard>=0.0.3` and use `ExternalTaskSensor` from `airflow.providers.standard.sensors.external_task` instead. | -43 | ExternalTaskMarker, - - ExternalTaskSensor, -44 | ) +42 + from airflow.sensors.external_task import ( +43 + ExternalTaskMarker, +44 + ) 45 | from airflow.sensors.filesystem import FileSensor 46 | from airflow.sensors.python import PythonSensor 47 + from airflow.providers.standard.sensors.external_task import ExternalTaskSensor -48 | | note: This is an unsafe fix and may change runtime behavior @@ -478,11 +461,9 @@ AIR312 [*] `airflow.sensors.filesystem.FileSensor` is deprecated and moved into | help: Install `apache-airflow-providers-standard>=0.0.2` and use `FileSensor` from `airflow.providers.standard.sensors.filesystem` instead. | -45 | ) - - from airflow.sensors.filesystem import FileSensor -46 | from airflow.sensors.python import PythonSensor -47 + from airflow.providers.standard.sensors.filesystem import FileSensor -48 | +46 + +47 | from airflow.sensors.python import PythonSensor +48 + from airflow.providers.standard.sensors.filesystem import FileSensor | note: This is an unsafe fix and may change runtime behavior @@ -498,10 +479,8 @@ AIR312 [*] `airflow.sensors.python.PythonSensor` is deprecated and moved into `s | help: Install `apache-airflow-providers-standard>=0.0.1` and use `PythonSensor` from `airflow.providers.standard.sensors.python` instead. | -46 | from airflow.sensors.filesystem import FileSensor - - from airflow.sensors.python import PythonSensor -47 + from airflow.providers.standard.sensors.python import PythonSensor -48 | +47 + +48 + from airflow.providers.standard.sensors.python import PythonSensor | note: This is an unsafe fix and may change runtime behavior @@ -516,12 +495,10 @@ AIR312 [*] `airflow.sensors.time_sensor.TimeSensor` is deprecated and moved into | help: Install `apache-airflow-providers-standard>=0.0.1` and use `TimeSensor` from `airflow.providers.standard.sensors.time` instead. | -59 | from airflow.sensors.time_sensor import ( - - TimeSensor, -60 | TimeSensorAsync, -61 | ) +59 + from airflow.sensors.time_sensor import ( +60 + TimeSensorAsync, +61 + ) 62 + from airflow.providers.standard.sensors.time import TimeSensor -63 | | note: This is an unsafe fix and may change runtime behavior @@ -536,11 +513,10 @@ AIR312 [*] `airflow.sensors.time_sensor.TimeSensorAsync` is deprecated and moved | help: Install `apache-airflow-providers-standard>=0.0.1` and use `TimeSensorAsync` from `airflow.providers.standard.sensors.time` instead. | -60 | TimeSensor, - - TimeSensorAsync, -61 | ) +59 + from airflow.sensors.time_sensor import ( +60 + TimeSensor, +61 + ) 62 + from airflow.providers.standard.sensors.time import TimeSensorAsync -63 | | note: This is an unsafe fix and may change runtime behavior @@ -556,13 +532,13 @@ AIR312 [*] `airflow.sensors.time_delta.TimeDeltaSensor` is deprecated and moved | help: Install `apache-airflow-providers-standard>=0.0.1` and use `TimeDeltaSensor` from `airflow.providers.standard.sensors.time_delta` instead. | -67 | from airflow.sensors.time_delta import ( - - TimeDeltaSensor, -68 | TimeDeltaSensorAsync, --------------------------------------------------------------------------------- +67 + from airflow.sensors.time_delta import ( +68 + TimeDeltaSensorAsync, +69 + ) +70 | from airflow.sensors.weekday import DayOfWeekSensor + … 79 | ) 80 + from airflow.providers.standard.sensors.time_delta import TimeDeltaSensor -81 | | note: This is an unsafe fix and may change runtime behavior @@ -577,13 +553,13 @@ AIR312 [*] `airflow.sensors.time_delta.TimeDeltaSensorAsync` is deprecated and m | help: Install `apache-airflow-providers-standard>=0.0.1` and use `TimeDeltaSensorAsync` from `airflow.providers.standard.sensors.time_delta` instead. | -68 | TimeDeltaSensor, - - TimeDeltaSensorAsync, -69 | ) --------------------------------------------------------------------------------- +67 + from airflow.sensors.time_delta import ( +68 + TimeDeltaSensor, +69 + ) +70 | from airflow.sensors.weekday import DayOfWeekSensor + … 79 | ) 80 + from airflow.providers.standard.sensors.time_delta import TimeDeltaSensorAsync -81 | | note: This is an unsafe fix and may change runtime behavior @@ -599,13 +575,11 @@ AIR312 [*] `airflow.sensors.weekday.DayOfWeekSensor` is deprecated and moved int | help: Install `apache-airflow-providers-standard>=0.0.1` and use `DayOfWeekSensor` from `airflow.providers.standard.sensors.weekday` instead. | -70 | ) - - from airflow.sensors.weekday import DayOfWeekSensor -71 | from airflow.triggers.external_task import ( --------------------------------------------------------------------------------- -79 | ) -80 + from airflow.providers.standard.sensors.weekday import DayOfWeekSensor -81 | +71 + +72 | from airflow.triggers.external_task import ( + … +80 | ) +81 + from airflow.providers.standard.sensors.weekday import DayOfWeekSensor | note: This is an unsafe fix and may change runtime behavior @@ -621,13 +595,13 @@ AIR312 [*] `airflow.triggers.external_task.DagStateTrigger` is deprecated and mo | help: Install `apache-airflow-providers-standard>=0.0.3` and use `DagStateTrigger` from `airflow.providers.standard.triggers.external_task` instead. | -72 | from airflow.triggers.external_task import ( - - DagStateTrigger, -73 | WorkflowTrigger, --------------------------------------------------------------------------------- +72 + from airflow.triggers.external_task import ( +73 + WorkflowTrigger, +74 + ) +75 | from airflow.triggers.file import FileTrigger + … 79 | ) 80 + from airflow.providers.standard.triggers.external_task import DagStateTrigger -81 | | note: This is an unsafe fix and may change runtime behavior @@ -643,13 +617,13 @@ AIR312 [*] `airflow.triggers.external_task.WorkflowTrigger` is deprecated and mo | help: Install `apache-airflow-providers-standard>=0.0.3` and use `WorkflowTrigger` from `airflow.providers.standard.triggers.external_task` instead. | -73 | DagStateTrigger, - - WorkflowTrigger, -74 | ) --------------------------------------------------------------------------------- +72 + from airflow.triggers.external_task import ( +73 + DagStateTrigger, +74 + ) +75 | from airflow.triggers.file import FileTrigger + … 79 | ) 80 + from airflow.providers.standard.triggers.external_task import WorkflowTrigger -81 | | note: This is an unsafe fix and may change runtime behavior @@ -665,14 +639,11 @@ AIR312 [*] `airflow.triggers.file.FileTrigger` is deprecated and moved into `sta | help: Install `apache-airflow-providers-standard>=0.0.3` and use `FileTrigger` from `airflow.providers.standard.triggers.file` instead. | -75 | ) - - from airflow.triggers.file import FileTrigger -76 | from airflow.triggers.temporal import ( -77 | DateTimeTrigger, -78 | TimeDeltaTrigger, -79 | ) -80 + from airflow.providers.standard.triggers.file import FileTrigger -81 | +76 + +77 | from airflow.triggers.temporal import ( + … +80 | ) +81 + from airflow.providers.standard.triggers.file import FileTrigger | note: This is an unsafe fix and may change runtime behavior @@ -687,12 +658,10 @@ AIR312 [*] `airflow.triggers.temporal.DateTimeTrigger` is deprecated and moved i | help: Install `apache-airflow-providers-standard>=0.0.3` and use `DateTimeTrigger` from `airflow.providers.standard.triggers.temporal` instead. | -77 | from airflow.triggers.temporal import ( - - DateTimeTrigger, -78 | TimeDeltaTrigger, -79 | ) +77 + from airflow.triggers.temporal import ( +78 + TimeDeltaTrigger, +79 + ) 80 + from airflow.providers.standard.triggers.temporal import DateTimeTrigger -81 | | note: This is an unsafe fix and may change runtime behavior @@ -705,10 +674,9 @@ AIR312 [*] `airflow.triggers.temporal.TimeDeltaTrigger` is deprecated and moved | ^^^^^^^^^^^^^^^^ help: Install `apache-airflow-providers-standard>=0.0.3` and use `TimeDeltaTrigger` from `airflow.providers.standard.triggers.temporal` instead. | -78 | DateTimeTrigger, - - TimeDeltaTrigger, -79 | ) +77 + from airflow.triggers.temporal import ( +78 + DateTimeTrigger, +79 + ) 80 + from airflow.providers.standard.triggers.temporal import TimeDeltaTrigger -81 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR321_AIR321_names.py.snap b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR321_AIR321_names.py.snap index 8f824539cb637..9b95683f864d8 100644 --- a/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR321_AIR321_names.py.snap +++ b/crates/ruff_linter/src/rules/airflow/snapshots/ruff_linter__rules__airflow__tests__AIR321_AIR321_names.py.snap @@ -47,10 +47,8 @@ AIR321 [*] `airflow.utils.task_group.TaskGroup` is moved in Airflow 3.1 | help: `TaskGroup` has been moved to `airflow.sdk` since Airflow 3.1 (with apache-airflow-task-sdk>=1.1.0). | -17 | # airflow.utils.task_group - - from airflow.utils.task_group import TaskGroup -18 + from airflow.sdk import TaskGroup -19 | +18 + +19 + from airflow.sdk import TaskGroup | note: This is an unsafe fix and may change runtime behavior @@ -66,13 +64,15 @@ AIR321 [*] `airflow.utils.timezone.coerce_datetime` is moved in Airflow 3.1 | help: `coerce_datetime` has been moved to `airflow.sdk.timezone` since Airflow 3.1 (with apache-airflow-task-sdk>=1.1.0). | -24 | from airflow.utils.timezone import ( - - coerce_datetime, -25 | convert_to_utc, --------------------------------------------------------------------------------- -31 | ) +24 + from airflow.utils.timezone import ( +25 + convert_to_utc, +26 + datetime, +27 + make_naive, +28 + parse, +29 + utc, +30 + utcnow, +31 + ) 32 + from airflow.sdk.timezone import coerce_datetime -33 | | note: This is an unsafe fix and may change runtime behavior @@ -87,13 +87,15 @@ AIR321 [*] `airflow.utils.timezone.convert_to_utc` is moved in Airflow 3.1 | help: `convert_to_utc` has been moved to `airflow.sdk.timezone` since Airflow 3.1 (with apache-airflow-task-sdk>=1.1.0). | -25 | coerce_datetime, - - convert_to_utc, -26 | datetime, --------------------------------------------------------------------------------- -31 | ) +24 + from airflow.utils.timezone import ( +25 + coerce_datetime, +26 + datetime, +27 + make_naive, +28 + parse, +29 + utc, +30 + utcnow, +31 + ) 32 + from airflow.sdk.timezone import convert_to_utc -33 | | note: This is an unsafe fix and may change runtime behavior @@ -109,13 +111,15 @@ AIR321 [*] `airflow.utils.timezone.datetime` is moved in Airflow 3.1 | help: `datetime` has been moved to `airflow.sdk.timezone` since Airflow 3.1 (with apache-airflow-task-sdk>=1.1.0). | -26 | convert_to_utc, - - datetime, -27 | make_naive, --------------------------------------------------------------------------------- -31 | ) +24 + from airflow.utils.timezone import ( +25 + coerce_datetime, +26 + convert_to_utc, +27 + make_naive, +28 + parse, +29 + utc, +30 + utcnow, +31 + ) 32 + from airflow.sdk.timezone import datetime -33 | | note: This is an unsafe fix and may change runtime behavior @@ -131,14 +135,15 @@ AIR321 [*] `airflow.utils.timezone.make_naive` is moved in Airflow 3.1 | help: `make_naive` has been moved to `airflow.sdk.timezone` since Airflow 3.1 (with apache-airflow-task-sdk>=1.1.0). | -27 | datetime, - - make_naive, -28 | parse, -29 | utc, -30 | utcnow, -31 | ) +24 + from airflow.utils.timezone import ( +25 + coerce_datetime, +26 + convert_to_utc, +27 + datetime, +28 + parse, +29 + utc, +30 + utcnow, +31 + ) 32 + from airflow.sdk.timezone import make_naive -33 | | note: This is an unsafe fix and may change runtime behavior @@ -154,13 +159,15 @@ AIR321 [*] `airflow.utils.timezone.parse` is moved in Airflow 3.1 | help: `parse` has been moved to `airflow.sdk.timezone` since Airflow 3.1 (with apache-airflow-task-sdk>=1.1.0). | -28 | make_naive, - - parse, -29 | utc, -30 | utcnow, -31 | ) +24 + from airflow.utils.timezone import ( +25 + coerce_datetime, +26 + convert_to_utc, +27 + datetime, +28 + make_naive, +29 + utc, +30 + utcnow, +31 + ) 32 + from airflow.sdk.timezone import parse -33 | | note: This is an unsafe fix and may change runtime behavior @@ -175,12 +182,15 @@ AIR321 [*] `airflow.utils.timezone.utc` is moved in Airflow 3.1 | help: `utc` has been moved to `airflow.sdk.timezone` since Airflow 3.1 (with apache-airflow-task-sdk>=1.1.0). | -29 | parse, - - utc, -30 | utcnow, -31 | ) +24 + from airflow.utils.timezone import ( +25 + coerce_datetime, +26 + convert_to_utc, +27 + datetime, +28 + make_naive, +29 + parse, +30 + utcnow, +31 + ) 32 + from airflow.sdk.timezone import utc -33 | | note: This is an unsafe fix and may change runtime behavior @@ -196,11 +206,15 @@ AIR321 [*] `airflow.utils.timezone.utcnow` is moved in Airflow 3.1 | help: `utcnow` has been moved to `airflow.sdk.timezone` since Airflow 3.1 (with apache-airflow-task-sdk>=1.1.0). | -30 | utc, - - utcnow, -31 | ) +24 + from airflow.utils.timezone import ( +25 + coerce_datetime, +26 + convert_to_utc, +27 + datetime, +28 + make_naive, +29 + parse, +30 + utc, +31 + ) 32 + from airflow.sdk.timezone import utcnow -33 | | note: This is an unsafe fix and may change runtime behavior @@ -272,10 +286,8 @@ AIR321 [*] `airflow.models.baseoperator.BaseOperator` is moved in Airflow 3.1 | help: `BaseOperator` has been moved to `airflow.sdk` since Airflow 3.1 (with apache-airflow-task-sdk>=1.1.0). | -64 | # airflow.models.baseoperator - - from airflow.models.baseoperator import BaseOperator -65 + from airflow.sdk import BaseOperator -66 | +65 + +66 + from airflow.sdk import BaseOperator | note: This is an unsafe fix and may change runtime behavior @@ -291,14 +303,12 @@ AIR321 [*] `airflow.macros.ds_add` is moved in Airflow 3.1 | help: `ds_add` has been moved to `airflow.sdk.execution_time.macros` since Airflow 3.1. Requires `apache-airflow-task-sdk>=1.1.0,<=1.1.6`. For `apache-airflow-task-sdk>=1.1.7`, import from `airflow.sdk` instead. | -70 | from airflow.macros import ( - - ds_add, -71 | ds_format, -72 | datetime_diff_for_humans, -73 | ds_format_locale, -74 | ) +70 + from airflow.macros import ( +71 + ds_format, +72 + datetime_diff_for_humans, +73 + ds_format_locale, +74 + ) 75 + from airflow.sdk.execution_time.macros import ds_add -76 | | note: This is an unsafe fix and may change runtime behavior @@ -313,13 +323,12 @@ AIR321 [*] `airflow.macros.ds_format` is moved in Airflow 3.1 | help: `ds_format` has been moved to `airflow.sdk.execution_time.macros` since Airflow 3.1. Requires `apache-airflow-task-sdk>=1.1.0,<=1.1.6`. For `apache-airflow-task-sdk>=1.1.7`, import from `airflow.sdk` instead. | -71 | ds_add, - - ds_format, -72 | datetime_diff_for_humans, -73 | ds_format_locale, -74 | ) +70 + from airflow.macros import ( +71 + ds_add, +72 + datetime_diff_for_humans, +73 + ds_format_locale, +74 + ) 75 + from airflow.sdk.execution_time.macros import ds_format -76 | | note: This is an unsafe fix and may change runtime behavior @@ -335,12 +344,12 @@ AIR321 [*] `airflow.macros.datetime_diff_for_humans` is moved in Airflow 3.1 | help: `datetime_diff_for_humans` has been moved to `airflow.sdk.execution_time.macros` since Airflow 3.1. Requires `apache-airflow-task-sdk>=1.1.0,<=1.1.6`. For `apache-airflow-task-sdk>=1.1.7`, import from `airflow.sdk` instead. | -72 | ds_format, - - datetime_diff_for_humans, -73 | ds_format_locale, -74 | ) +70 + from airflow.macros import ( +71 + ds_add, +72 + ds_format, +73 + ds_format_locale, +74 + ) 75 + from airflow.sdk.execution_time.macros import datetime_diff_for_humans -76 | | note: This is an unsafe fix and may change runtime behavior @@ -356,11 +365,12 @@ AIR321 [*] `airflow.macros.ds_format_locale` is moved in Airflow 3.1 | help: `ds_format_locale` has been moved to `airflow.sdk.execution_time.macros` since Airflow 3.1. Requires `apache-airflow-task-sdk>=1.1.0,<=1.1.6`. For `apache-airflow-task-sdk>=1.1.7`, import from `airflow.sdk` instead. | -73 | datetime_diff_for_humans, - - ds_format_locale, -74 | ) +70 + from airflow.macros import ( +71 + ds_add, +72 + ds_format, +73 + datetime_diff_for_humans, +74 + ) 75 + from airflow.sdk.execution_time.macros import ds_format_locale -76 | | note: This is an unsafe fix and may change runtime behavior @@ -376,13 +386,11 @@ AIR321 [*] `airflow.io.get_fs` is moved in Airflow 3.1 | help: `get_fs` has been moved to `airflow.sdk.io` since Airflow 3.1 (with apache-airflow-task-sdk>=1.1.0). | -86 | from airflow.io import ( - - get_fs, -87 | has_fs, -88 | Properties, -89 | ) +86 + from airflow.io import ( +87 + has_fs, +88 + Properties, +89 + ) 90 + from airflow.sdk.io import get_fs -91 | | note: This is an unsafe fix and may change runtime behavior @@ -396,12 +404,11 @@ AIR321 [*] `airflow.io.has_fs` is moved in Airflow 3.1 | help: `has_fs` has been moved to `airflow.sdk.io` since Airflow 3.1 (with apache-airflow-task-sdk>=1.1.0). | -87 | get_fs, - - has_fs, -88 | Properties, -89 | ) +86 + from airflow.io import ( +87 + get_fs, +88 + Properties, +89 + ) 90 + from airflow.sdk.io import has_fs -91 | | note: This is an unsafe fix and may change runtime behavior @@ -417,11 +424,11 @@ AIR321 [*] `airflow.io.Properties` is moved in Airflow 3.1 | help: `Properties` has been moved to `airflow.sdk.io` since Airflow 3.1 (with apache-airflow-task-sdk>=1.1.0). | -88 | has_fs, - - Properties, -89 | ) +86 + from airflow.io import ( +87 + get_fs, +88 + has_fs, +89 + ) 90 + from airflow.sdk.io import Properties -91 | | note: This is an unsafe fix and may change runtime behavior @@ -437,10 +444,8 @@ AIR321 [*] `airflow.secrets.cache.SecretCache` is moved in Airflow 3.1 | help: `SecretCache` has been moved to `airflow.sdk` since Airflow 3.1 (with apache-airflow-task-sdk>=1.1.0). | -96 | # airflow.secrets.cache - - from airflow.secrets.cache import SecretCache -97 + from airflow.sdk import SecretCache -98 | SecretCache() +97 + +98 + from airflow.sdk import SecretCache | note: This is an unsafe fix and may change runtime behavior @@ -453,9 +458,7 @@ AIR321 [*] `airflow.hooks.base.BaseHook` is moved in Airflow 3.1 | ^^^^^^^^ help: `BaseHook` has been moved to `airflow.sdk` since Airflow 3.1 (with apache-airflow-task-sdk>=1.1.0). | -100 | # airflow.hooks - - from airflow.hooks.base import BaseHook -101 + from airflow.sdk import BaseHook -102 | BaseHook() +101 + +102 + from airflow.sdk import BaseHook | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/eradicate/snapshots/ruff_linter__rules__eradicate__tests__ERA001_ERA001.py.snap b/crates/ruff_linter/src/rules/eradicate/snapshots/ruff_linter__rules__eradicate__tests__ERA001_ERA001.py.snap index 0bc73f1f9a49f..a9a3e8e28f82a 100644 --- a/crates/ruff_linter/src/rules/eradicate/snapshots/ruff_linter__rules__eradicate__tests__ERA001_ERA001.py.snap +++ b/crates/ruff_linter/src/rules/eradicate/snapshots/ruff_linter__rules__eradicate__tests__ERA001_ERA001.py.snap @@ -11,8 +11,7 @@ ERA001 [*] Found commented-out code | help: Remove commented-out code | - - #import os -1 | # from foo import junk +1 - #import os | note: This is a display-only fix and is likely to be incorrect @@ -27,9 +26,7 @@ ERA001 [*] Found commented-out code | help: Remove commented-out code | -1 | #import os - - # from foo import junk -2 | #a = 3 +2 - # from foo import junk | note: This is a display-only fix and is likely to be incorrect @@ -45,9 +42,7 @@ ERA001 [*] Found commented-out code | help: Remove commented-out code | -2 | # from foo import junk - - #a = 3 -3 | a = 4 +3 - #a = 3 | note: This is a display-only fix and is likely to be incorrect @@ -63,9 +58,7 @@ ERA001 [*] Found commented-out code | help: Remove commented-out code | -4 | a = 4 - - #foo(1, 2, 3) -5 | +5 - #foo(1, 2, 3) | note: This is a display-only fix and is likely to be incorrect @@ -80,9 +73,7 @@ ERA001 [*] Found commented-out code | help: Remove commented-out code | -12 | # # This is a (nested) comment. - - #return True -13 | return False +13 - #return True | note: This is a display-only fix and is likely to be incorrect @@ -95,9 +86,7 @@ ERA001 [*] Found commented-out code | ^^^^^^^ help: Remove commented-out code | -20 | pass - - # b = c -21 | +21 - # b = c | note: This is a display-only fix and is likely to be incorrect @@ -113,9 +102,7 @@ ERA001 [*] Found commented-out code | help: Remove commented-out code | -25 | # "key1": 123, # noqa: ERA001 - - # "key2": 456, -26 | # "key3": 789, # test +26 - # "key2": 456, | note: This is a display-only fix and is likely to be incorrect @@ -130,9 +117,7 @@ ERA001 [*] Found commented-out code | help: Remove commented-out code | -26 | # "key2": 456, - - # "key3": 789, # test -27 | } +27 - # "key3": 789, # test | note: This is a display-only fix and is likely to be incorrect @@ -148,9 +133,7 @@ ERA001 [*] Found commented-out code | help: Remove commented-out code | -31 | - - # case 1: -32 | # try: +32 - # case 1: | note: This is a display-only fix and is likely to be incorrect @@ -165,9 +148,7 @@ ERA001 [*] Found commented-out code | help: Remove commented-out code | -32 | # case 1: - - # try: -33 | # try: # with comment +33 - # try: | note: This is a display-only fix and is likely to be incorrect @@ -183,9 +164,7 @@ ERA001 [*] Found commented-out code | help: Remove commented-out code | -33 | # try: - - # try: # with comment -34 | # try: print() +34 - # try: # with comment | note: This is a display-only fix and is likely to be incorrect @@ -201,9 +180,7 @@ ERA001 [*] Found commented-out code | help: Remove commented-out code | -34 | # try: # with comment - - # try: print() -35 | # except: +35 - # try: print() | note: This is a display-only fix and is likely to be incorrect @@ -219,9 +196,7 @@ ERA001 [*] Found commented-out code | help: Remove commented-out code | -35 | # try: print() - - # except: -36 | # except Foo: +36 - # except: | note: This is a display-only fix and is likely to be incorrect @@ -236,9 +211,7 @@ ERA001 [*] Found commented-out code | help: Remove commented-out code | -36 | # except: - - # except Foo: -37 | # except Exception as e: print(e) +37 - # except Foo: | note: This is a display-only fix and is likely to be incorrect @@ -251,9 +224,7 @@ ERA001 [*] Found commented-out code | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove commented-out code | -37 | # except Foo: - - # except Exception as e: print(e) -38 | +38 - # except Exception as e: print(e) | note: This is a display-only fix and is likely to be incorrect @@ -268,9 +239,7 @@ ERA001 [*] Found commented-out code | help: Remove commented-out code | -43 | # requires-python = ">=3.11" - - # dependencies = [ -44 | # "requests<3", +44 - # dependencies = [ | note: This is a display-only fix and is likely to be incorrect @@ -285,9 +254,7 @@ ERA001 [*] Found commented-out code | help: Remove commented-out code | -46 | # "rich", - - # ] -47 | # /// +47 - # ] | note: This is a display-only fix and is likely to be incorrect @@ -303,9 +270,7 @@ ERA001 [*] Found commented-out code | help: Remove commented-out code | -74 | # requires-python = ">=3.11" - - # dependencies = [ -75 | # "requests<3", +75 - # dependencies = [ | note: This is a display-only fix and is likely to be incorrect @@ -321,8 +286,6 @@ ERA001 [*] Found commented-out code | help: Remove commented-out code | -77 | # "rich", - - # ] -78 | +78 - # ] | note: This is a display-only fix and is likely to be incorrect diff --git a/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__deferred_annotations_diff_fast-api-redundant-response-model_FAST001.py.snap b/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__deferred_annotations_diff_fast-api-redundant-response-model_FAST001.py.snap index d22530e81d454..fbd45a8f26feb 100644 --- a/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__deferred_annotations_diff_fast-api-redundant-response-model_FAST001.py.snap +++ b/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__deferred_annotations_diff_fast-api-redundant-response-model_FAST001.py.snap @@ -20,10 +20,8 @@ FAST001 [*] FastAPI route with redundant `response_model` argument | help: Remove argument | -16 | - - @app.post("/items/", response_model=Item) +17 - @app.post("/items/", response_model=Item) 17 + @app.post("/items/") -18 | async def create_item(item: Item) -> Item: | note: This is an unsafe fix and may change runtime behavior @@ -38,10 +36,8 @@ FAST001 [*] FastAPI route with redundant `response_model` argument | help: Remove argument | -21 | - - @app.post("/items/", response_model=list[Item]) +22 - @app.post("/items/", response_model=list[Item]) 22 + @app.post("/items/") -23 | async def create_item(item: Item) -> list[Item]: | note: This is an unsafe fix and may change runtime behavior @@ -56,10 +52,8 @@ FAST001 [*] FastAPI route with redundant `response_model` argument | help: Remove argument | -26 | - - @app.post("/items/", response_model=List[Item]) +27 - @app.post("/items/", response_model=List[Item]) 27 + @app.post("/items/") -28 | async def create_item(item: Item) -> List[Item]: | note: This is an unsafe fix and may change runtime behavior @@ -74,10 +68,8 @@ FAST001 [*] FastAPI route with redundant `response_model` argument | help: Remove argument | -31 | - - @app.post("/items/", response_model=Dict[str, Item]) +32 - @app.post("/items/", response_model=Dict[str, Item]) 32 + @app.post("/items/") -33 | async def create_item(item: Item) -> Dict[str, Item]: | note: This is an unsafe fix and may change runtime behavior @@ -92,10 +84,8 @@ FAST001 [*] FastAPI route with redundant `response_model` argument | help: Remove argument | -36 | - - @app.post("/items/", response_model=str) +37 - @app.post("/items/", response_model=str) 37 + @app.post("/items/") -38 | async def create_item(item: Item) -> str: | note: This is an unsafe fix and may change runtime behavior @@ -110,10 +100,8 @@ FAST001 [*] FastAPI route with redundant `response_model` argument | help: Remove argument | -41 | - - @app.get("/items/", response_model=Item) +42 - @app.get("/items/", response_model=Item) 42 + @app.get("/items/") -43 | async def create_item(item: Item) -> Item: | note: This is an unsafe fix and may change runtime behavior @@ -128,10 +116,8 @@ FAST001 [*] FastAPI route with redundant `response_model` argument | help: Remove argument | -46 | - - @app.get("/items/", response_model=Item) +47 - @app.get("/items/", response_model=Item) 47 + @app.get("/items/") -48 | @app.post("/items/", response_model=Item) | note: This is an unsafe fix and may change runtime behavior @@ -147,10 +133,8 @@ FAST001 [*] FastAPI route with redundant `response_model` argument | help: Remove argument | -47 | @app.get("/items/", response_model=Item) - - @app.post("/items/", response_model=Item) +48 - @app.post("/items/", response_model=Item) 48 + @app.post("/items/") -49 | async def create_item(item: Item) -> Item: | note: This is an unsafe fix and may change runtime behavior @@ -165,10 +149,8 @@ FAST001 [*] FastAPI route with redundant `response_model` argument | help: Remove argument | -52 | - - @router.get("/items/", response_model=Item) +53 - @router.get("/items/", response_model=Item) 53 + @router.get("/items/") -54 | async def create_item(item: Item) -> Item: | note: This is an unsafe fix and may change runtime behavior @@ -185,9 +167,7 @@ FAST001 [*] FastAPI route with redundant `response_model` argument | help: Remove argument | -122 | # Error - - @app_arg.get("/", response_model=str) +123 - @app_arg.get("/", response_model=str) 123 + @app_arg.get("/") -124 | async def get_root() -> str: | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__deferred_annotations_diff_fast-api-unused-path-parameter_FAST003.py.snap b/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__deferred_annotations_diff_fast-api-unused-path-parameter_FAST003.py.snap index 21c2d85831bd0..5456dbeb01d64 100644 --- a/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__deferred_annotations_diff_fast-api-unused-path-parameter_FAST003.py.snap +++ b/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__deferred_annotations_diff_fast-api-unused-path-parameter_FAST003.py.snap @@ -21,11 +21,8 @@ FAST003 [*] Parameter `thing_id` appears in route path, but not in `single` sign | help: Add `thing_id` to function signature | -158 | @app.get("/things/{thing_id}") - - async def single(other: Annotated[str, Depends(something_else)]): ... -159 + async def single(other: Annotated[str, Depends(something_else)], thing_id): ... -160 | @app.get("/things/{thing_id}") - | +159 | async def single(other: Annotated[str, Depends(something_else)], thing_id): ... + | ++++++++++ note: This is an unsafe fix and may change runtime behavior @@ -40,11 +37,8 @@ FAST003 [*] Parameter `id` appears in route path, but not in `get_id_pydantic_fu | help: Add `id` to function signature | -198 | async def get_id_pydantic_full( - - params: Annotated[PydanticParams, Depends(PydanticParams)], -199 + params: Annotated[PydanticParams, Depends(PydanticParams)], id, -200 | ): ... - | +199 | params: Annotated[PydanticParams, Depends(PydanticParams)], id, + | ++++ note: This is an unsafe fix and may change runtime behavior @@ -60,11 +54,8 @@ FAST003 [*] Parameter `id` appears in route path, but not in `get_id_pydantic_sh | help: Add `id` to function signature | -201 | @app.get("/{id}") - - async def get_id_pydantic_short(params: Annotated[PydanticParams, Depends()]): ... -202 + async def get_id_pydantic_short(params: Annotated[PydanticParams, Depends()], id): ... -203 | @app.get("/{id}") - | +202 | async def get_id_pydantic_short(params: Annotated[PydanticParams, Depends()], id): ... + | ++++ note: This is an unsafe fix and may change runtime behavior @@ -77,11 +68,8 @@ FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing_c | help: Add `thing_id` to function signature | -314 | @app.get("/things/{thing_id}") - - async def read_thing_callable_dep(query: Annotated[str, Depends(CallableQuery)]): ... -315 + async def read_thing_callable_dep(query: Annotated[str, Depends(CallableQuery)], thing_id): ... -316 | - | +315 | async def read_thing_callable_dep(query: Annotated[str, Depends(CallableQuery)], thing_id): ... + | ++++++++++ note: This is an unsafe fix and may change runtime behavior @@ -94,11 +82,8 @@ FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing_c | help: Add `thing_id` to function signature | -345 | @app.get("/things/{thing_id}") - - async def read_thing_callable_dep_missing(query: Annotated[str, Depends(CallableQueryOther)]): ... -346 + async def read_thing_callable_dep_missing(query: Annotated[str, Depends(CallableQueryOther)], thing_id): ... -347 | - | +346 | async def read_thing_callable_dep_missing(query: Annotated[str, Depends(CallableQueryOther)], thing_id): ... + | ++++++++++ note: This is an unsafe fix and may change runtime behavior @@ -113,11 +98,8 @@ FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing_i | help: Add `thing_id` to function signature | -351 | @app.get("/things/{thing_id}") - - async def read_thing_init_and_call_instance(query: Annotated[str, Depends(InitAndCallQuery())]): ... -352 + async def read_thing_init_and_call_instance(query: Annotated[str, Depends(InitAndCallQuery())], thing_id): ... -353 | - | +352 | async def read_thing_init_and_call_instance(query: Annotated[str, Depends(InitAndCallQuery())], thing_id): ... + | ++++++++++ note: This is an unsafe fix and may change runtime behavior @@ -130,9 +112,6 @@ FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing_e | help: Add `thing_id` to function signature | -361 | @app.get("/things/{thing_id}") - - async def read_thing_empty_class_dep(query: Annotated[str, Depends(EmptyClass)]): ... -362 + async def read_thing_empty_class_dep(query: Annotated[str, Depends(EmptyClass)], thing_id): ... -363 | - | +362 | async def read_thing_empty_class_dep(query: Annotated[str, Depends(EmptyClass)], thing_id): ... + | ++++++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_0.py.snap b/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_0.py.snap index 3a47b1c435a35..c8b319f12f527 100644 --- a/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_0.py.snap +++ b/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_0.py.snap @@ -13,14 +13,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -14 | from pydantic import BaseModel 15 + from typing import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 24 | def get_items( - - current_user: User = Depends(get_current_user), -25 + current_user: Annotated[User, Depends(get_current_user)], -26 | some_security_param: str = Security(get_oauth2_user), +25 ~ current_user: Annotated[User, Depends(get_current_user)], | note: This is an unsafe fix and may change runtime behavior @@ -36,14 +34,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -14 | from pydantic import BaseModel 15 + from typing import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 25 | current_user: User = Depends(get_current_user), - - some_security_param: str = Security(get_oauth2_user), -26 + some_security_param: Annotated[str, Security(get_oauth2_user)], -27 | ): +26 ~ some_security_param: Annotated[str, Security(get_oauth2_user)], | note: This is an unsafe fix and may change runtime behavior @@ -59,14 +55,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -14 | from pydantic import BaseModel 15 + from typing import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 32 | def do_stuff( - - some_path_param: str = Path(), -33 + some_path_param: Annotated[str, Path()], -34 | some_cookie_param: str = Cookie(), +33 ~ some_path_param: Annotated[str, Path()], | note: This is an unsafe fix and may change runtime behavior @@ -82,14 +76,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -14 | from pydantic import BaseModel 15 + from typing import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 33 | some_path_param: str = Path(), - - some_cookie_param: str = Cookie(), -34 + some_cookie_param: Annotated[str, Cookie()], -35 | some_file_param: UploadFile = File(), +34 ~ some_cookie_param: Annotated[str, Cookie()], | note: This is an unsafe fix and may change runtime behavior @@ -105,14 +97,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -14 | from pydantic import BaseModel 15 + from typing import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 34 | some_cookie_param: str = Cookie(), - - some_file_param: UploadFile = File(), -35 + some_file_param: Annotated[UploadFile, File()], -36 | some_form_param: str = Form(), +35 ~ some_file_param: Annotated[UploadFile, File()], | note: This is an unsafe fix and may change runtime behavior @@ -128,14 +118,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -14 | from pydantic import BaseModel 15 + from typing import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 35 | some_file_param: UploadFile = File(), - - some_form_param: str = Form(), -36 + some_form_param: Annotated[str, Form()], -37 | some_query_param: str | None = Query(default=None), +36 ~ some_form_param: Annotated[str, Form()], | note: This is an unsafe fix and may change runtime behavior @@ -151,14 +139,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -14 | from pydantic import BaseModel 15 + from typing import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 36 | some_form_param: str = Form(), - - some_query_param: str | None = Query(default=None), -37 + some_query_param: Annotated[str | None, Query()] = None, -38 | some_body_param: str = Body("foo"), +37 ~ some_query_param: Annotated[str | None, Query()] = None, | note: This is an unsafe fix and may change runtime behavior @@ -174,14 +160,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -14 | from pydantic import BaseModel 15 + from typing import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 37 | some_query_param: str | None = Query(default=None), - - some_body_param: str = Body("foo"), -38 + some_body_param: Annotated[str, Body()] = "foo", -39 | some_header_param: int = Header(default=5), +38 ~ some_body_param: Annotated[str, Body()] = "foo", | note: This is an unsafe fix and may change runtime behavior @@ -197,14 +181,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -14 | from pydantic import BaseModel 15 + from typing import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 38 | some_body_param: str = Body("foo"), - - some_header_param: int = Header(default=5), -39 + some_header_param: Annotated[int, Header()] = 5, -40 | ): +39 ~ some_header_param: Annotated[int, Header()] = 5, | note: This is an unsafe fix and may change runtime behavior @@ -220,14 +202,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -14 | from pydantic import BaseModel 15 + from typing import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 47 | limit: int, - - current_user: User = Depends(get_current_user), -48 + current_user: Annotated[User, Depends(get_current_user)], -49 | ): +48 ~ current_user: Annotated[User, Depends(get_current_user)], | note: This is an unsafe fix and may change runtime behavior @@ -243,14 +223,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -14 | from pydantic import BaseModel 15 + from typing import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 53 | def get_users( - - current_user: User = Depends(get_current_user), -54 + current_user: Annotated[User, Depends(get_current_user)], -55 | skip: int = 0, +54 ~ current_user: Annotated[User, Depends(get_current_user)], | note: This is an unsafe fix and may change runtime behavior @@ -264,14 +242,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -14 | from pydantic import BaseModel 15 + from typing import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 61 | @app.get("/items/{item_id}") - - async def read_items(*, item_id: int = Path(title="The ID of the item to get"), q: str): -62 + async def read_items(*, item_id: Annotated[int, Path(title="The ID of the item to get")], q: str): -63 | pass +62 ~ async def read_items(*, item_id: Annotated[int, Path(title="The ID of the item to get")], q: str): | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_0.py_py38.snap b/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_0.py_py38.snap index 6558597efe0e8..4edcb2ae4eb93 100644 --- a/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_0.py_py38.snap +++ b/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_0.py_py38.snap @@ -13,14 +13,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -14 | from pydantic import BaseModel 15 + from typing_extensions import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 24 | def get_items( - - current_user: User = Depends(get_current_user), -25 + current_user: Annotated[User, Depends(get_current_user)], -26 | some_security_param: str = Security(get_oauth2_user), +25 ~ current_user: Annotated[User, Depends(get_current_user)], | note: This is an unsafe fix and may change runtime behavior @@ -36,14 +34,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -14 | from pydantic import BaseModel 15 + from typing_extensions import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 25 | current_user: User = Depends(get_current_user), - - some_security_param: str = Security(get_oauth2_user), -26 + some_security_param: Annotated[str, Security(get_oauth2_user)], -27 | ): +26 ~ some_security_param: Annotated[str, Security(get_oauth2_user)], | note: This is an unsafe fix and may change runtime behavior @@ -59,14 +55,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -14 | from pydantic import BaseModel 15 + from typing_extensions import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 32 | def do_stuff( - - some_path_param: str = Path(), -33 + some_path_param: Annotated[str, Path()], -34 | some_cookie_param: str = Cookie(), +33 ~ some_path_param: Annotated[str, Path()], | note: This is an unsafe fix and may change runtime behavior @@ -82,14 +76,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -14 | from pydantic import BaseModel 15 + from typing_extensions import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 33 | some_path_param: str = Path(), - - some_cookie_param: str = Cookie(), -34 + some_cookie_param: Annotated[str, Cookie()], -35 | some_file_param: UploadFile = File(), +34 ~ some_cookie_param: Annotated[str, Cookie()], | note: This is an unsafe fix and may change runtime behavior @@ -105,14 +97,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -14 | from pydantic import BaseModel 15 + from typing_extensions import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 34 | some_cookie_param: str = Cookie(), - - some_file_param: UploadFile = File(), -35 + some_file_param: Annotated[UploadFile, File()], -36 | some_form_param: str = Form(), +35 ~ some_file_param: Annotated[UploadFile, File()], | note: This is an unsafe fix and may change runtime behavior @@ -128,14 +118,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -14 | from pydantic import BaseModel 15 + from typing_extensions import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 35 | some_file_param: UploadFile = File(), - - some_form_param: str = Form(), -36 + some_form_param: Annotated[str, Form()], -37 | some_query_param: str | None = Query(default=None), +36 ~ some_form_param: Annotated[str, Form()], | note: This is an unsafe fix and may change runtime behavior @@ -151,14 +139,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -14 | from pydantic import BaseModel 15 + from typing_extensions import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 36 | some_form_param: str = Form(), - - some_query_param: str | None = Query(default=None), -37 + some_query_param: Annotated[str | None, Query()] = None, -38 | some_body_param: str = Body("foo"), +37 ~ some_query_param: Annotated[str | None, Query()] = None, | note: This is an unsafe fix and may change runtime behavior @@ -174,14 +160,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -14 | from pydantic import BaseModel 15 + from typing_extensions import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 37 | some_query_param: str | None = Query(default=None), - - some_body_param: str = Body("foo"), -38 + some_body_param: Annotated[str, Body()] = "foo", -39 | some_header_param: int = Header(default=5), +38 ~ some_body_param: Annotated[str, Body()] = "foo", | note: This is an unsafe fix and may change runtime behavior @@ -197,14 +181,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -14 | from pydantic import BaseModel 15 + from typing_extensions import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 38 | some_body_param: str = Body("foo"), - - some_header_param: int = Header(default=5), -39 + some_header_param: Annotated[int, Header()] = 5, -40 | ): +39 ~ some_header_param: Annotated[int, Header()] = 5, | note: This is an unsafe fix and may change runtime behavior @@ -220,14 +202,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -14 | from pydantic import BaseModel 15 + from typing_extensions import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 47 | limit: int, - - current_user: User = Depends(get_current_user), -48 + current_user: Annotated[User, Depends(get_current_user)], -49 | ): +48 ~ current_user: Annotated[User, Depends(get_current_user)], | note: This is an unsafe fix and may change runtime behavior @@ -243,14 +223,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -14 | from pydantic import BaseModel 15 + from typing_extensions import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 53 | def get_users( - - current_user: User = Depends(get_current_user), -54 + current_user: Annotated[User, Depends(get_current_user)], -55 | skip: int = 0, +54 ~ current_user: Annotated[User, Depends(get_current_user)], | note: This is an unsafe fix and may change runtime behavior @@ -264,14 +242,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -14 | from pydantic import BaseModel 15 + from typing_extensions import Annotated -16 | --------------------------------------------------------------------------------- +16 + +17 | app = FastAPI() + … 61 | @app.get("/items/{item_id}") - - async def read_items(*, item_id: int = Path(title="The ID of the item to get"), q: str): -62 + async def read_items(*, item_id: Annotated[int, Path(title="The ID of the item to get")], q: str): -63 | pass +62 ~ async def read_items(*, item_id: Annotated[int, Path(title="The ID of the item to get")], q: str): | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_1.py.snap b/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_1.py.snap index 93fedc3dacb58..89b76cf105667 100644 --- a/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_1.py.snap +++ b/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_1.py.snap @@ -11,14 +11,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -4 | from fastapi import FastAPI, Query -5 + from typing import Annotated -6 | --------------------------------------------------------------------------------- + 5 + from typing import Annotated + 6 + + 7 | app = FastAPI() + … 10 | @app.get("/test") - - def handler(echo: str = Query("")): -11 + def handler(echo: Annotated[str, Query()] = ""): -12 | return echo +11 ~ def handler(echo: Annotated[str, Query()] = ""): | note: This is an unsafe fix and may change runtime behavior @@ -32,14 +30,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -4 | from fastapi import FastAPI, Query -5 + from typing import Annotated -6 | --------------------------------------------------------------------------------- + 5 + from typing import Annotated + 6 + + 7 | app = FastAPI() + … 15 | @app.get("/test") - - def handler2(echo: str = Query(default="")): -16 + def handler2(echo: Annotated[str, Query()] = ""): -17 | return echo +16 ~ def handler2(echo: Annotated[str, Query()] = ""): | note: This is an unsafe fix and may change runtime behavior @@ -53,13 +49,11 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -4 | from fastapi import FastAPI, Query -5 + from typing import Annotated -6 | --------------------------------------------------------------------------------- + 5 + from typing import Annotated + 6 + + 7 | app = FastAPI() + … 20 | @app.get("/test") - - def handler3(echo: str = Query("123", min_length=3, max_length=50)): -21 + def handler3(echo: Annotated[str, Query(min_length=3, max_length=50)] = "123"): -22 | return echo +21 ~ def handler3(echo: Annotated[str, Query(min_length=3, max_length=50)] = "123"): | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_1.py_py38.snap b/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_1.py_py38.snap index edcaf5ed579d5..e241d28705eb6 100644 --- a/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_1.py_py38.snap +++ b/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_1.py_py38.snap @@ -11,14 +11,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -4 | from fastapi import FastAPI, Query -5 + from typing_extensions import Annotated -6 | --------------------------------------------------------------------------------- + 5 + from typing_extensions import Annotated + 6 + + 7 | app = FastAPI() + … 10 | @app.get("/test") - - def handler(echo: str = Query("")): -11 + def handler(echo: Annotated[str, Query()] = ""): -12 | return echo +11 ~ def handler(echo: Annotated[str, Query()] = ""): | note: This is an unsafe fix and may change runtime behavior @@ -32,14 +30,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -4 | from fastapi import FastAPI, Query -5 + from typing_extensions import Annotated -6 | --------------------------------------------------------------------------------- + 5 + from typing_extensions import Annotated + 6 + + 7 | app = FastAPI() + … 15 | @app.get("/test") - - def handler2(echo: str = Query(default="")): -16 + def handler2(echo: Annotated[str, Query()] = ""): -17 | return echo +16 ~ def handler2(echo: Annotated[str, Query()] = ""): | note: This is an unsafe fix and may change runtime behavior @@ -53,13 +49,11 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -4 | from fastapi import FastAPI, Query -5 + from typing_extensions import Annotated -6 | --------------------------------------------------------------------------------- + 5 + from typing_extensions import Annotated + 6 + + 7 | app = FastAPI() + … 20 | @app.get("/test") - - def handler3(echo: str = Query("123", min_length=3, max_length=50)): -21 + def handler3(echo: Annotated[str, Query(min_length=3, max_length=50)] = "123"): -22 | return echo +21 ~ def handler3(echo: Annotated[str, Query(min_length=3, max_length=50)] = "123"): | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_2.py.snap b/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_2.py.snap index 0ba73bae60224..52f9d1a1eb3aa 100644 --- a/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_2.py.snap +++ b/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_2.py.snap @@ -13,14 +13,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -3 | from fastapi import Body, Cookie, FastAPI, Header, Query -4 + from typing import Annotated -5 | --------------------------------------------------------------------------------- + 4 + from typing import Annotated + 5 + + 6 | app = FastAPI() + … 14 | # This should become: param: Annotated[str, Query(description="Test param")] - - param: str = Query(..., description="Test param"), -15 + param: Annotated[str, Query(description="Test param")], -16 | ) -> str: +15 ~ param: Annotated[str, Query(description="Test param")], | note: This is an unsafe fix and may change runtime behavior @@ -36,14 +34,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -3 | from fastapi import Body, Cookie, FastAPI, Header, Query -4 + from typing import Annotated -5 | --------------------------------------------------------------------------------- + 4 + from typing import Annotated + 5 + + 6 | app = FastAPI() + … 22 | # This should become: auth: Annotated[str, Header(description="Auth header")] - - auth: str = Header(..., description="Auth header"), -23 + auth: Annotated[str, Header(description="Auth header")], -24 | ) -> str: +23 ~ auth: Annotated[str, Header(description="Auth header")], | note: This is an unsafe fix and may change runtime behavior @@ -59,14 +55,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -3 | from fastapi import Body, Cookie, FastAPI, Header, Query -4 + from typing import Annotated -5 | --------------------------------------------------------------------------------- + 4 + from typing import Annotated + 5 + + 6 | app = FastAPI() + … 30 | # This should become: data: Annotated[dict, Body(description="Request body")] - - data: dict = Body(..., description="Request body"), -31 + data: Annotated[dict, Body(description="Request body")], -32 | ) -> dict: +31 ~ data: Annotated[dict, Body(description="Request body")], | note: This is an unsafe fix and may change runtime behavior @@ -82,14 +76,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -3 | from fastapi import Body, Cookie, FastAPI, Header, Query -4 + from typing import Annotated -5 | --------------------------------------------------------------------------------- + 4 + from typing import Annotated + 5 + + 6 | app = FastAPI() + … 38 | # This should become: session: Annotated[str, Cookie(description="Session ID")] - - session: str = Cookie(..., description="Session ID"), -39 + session: Annotated[str, Cookie(description="Session ID")], -40 | ) -> str: +39 ~ session: Annotated[str, Cookie(description="Session ID")], | note: This is an unsafe fix and may change runtime behavior @@ -105,14 +97,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -3 | from fastapi import Body, Cookie, FastAPI, Header, Query -4 + from typing import Annotated -5 | --------------------------------------------------------------------------------- + 4 + from typing import Annotated + 5 + + 6 | app = FastAPI() + … 46 | # This should become: id: Annotated[str, Query()] - - id: str = Query(...), -47 + id: Annotated[str, Query()], -48 | ) -> str: +47 ~ id: Annotated[str, Query()], | note: This is an unsafe fix and may change runtime behavior @@ -128,14 +118,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -3 | from fastapi import Body, Cookie, FastAPI, Header, Query -4 + from typing import Annotated -5 | --------------------------------------------------------------------------------- + 4 + from typing import Annotated + 5 + + 6 | app = FastAPI() + … 54 | # This should become: param: Annotated[str, Query(description="Test", min_length=1, max_length=10)] - - param: str = Query(..., description="Test", min_length=1, max_length=10), -55 + param: Annotated[str, Query(description="Test", min_length=1, max_length=10)], -56 | ) -> str: +55 ~ param: Annotated[str, Query(description="Test", min_length=1, max_length=10)], | note: This is an unsafe fix and may change runtime behavior @@ -151,14 +139,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -3 | from fastapi import Body, Cookie, FastAPI, Header, Query -4 + from typing import Annotated -5 | --------------------------------------------------------------------------------- + 4 + from typing import Annotated + 5 + + 6 | app = FastAPI() + … 65 | # This should become: param: Annotated[str, Query(description="Test")] = "default" - - param: str = Query("default", description="Test"), -66 + param: Annotated[str, Query(description="Test")] = "default", -67 | ) -> str: +66 ~ param: Annotated[str, Query(description="Test")] = "default", | note: This is an unsafe fix and may change runtime behavior @@ -174,14 +160,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -3 | from fastapi import Body, Cookie, FastAPI, Header, Query -4 + from typing import Annotated -5 | --------------------------------------------------------------------------------- + 4 + from typing import Annotated + 5 + + 6 | app = FastAPI() + … 73 | # This should become: param: Annotated[str | None, Query(description="Test")] = None - - param: str | None = Query(None, description="Test"), -74 + param: Annotated[str | None, Query(description="Test")] = None, -75 | ) -> str: +74 ~ param: Annotated[str | None, Query(description="Test")] = None, | note: This is an unsafe fix and may change runtime behavior @@ -197,14 +181,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -3 | from fastapi import Body, Cookie, FastAPI, Header, Query -4 + from typing import Annotated -5 | --------------------------------------------------------------------------------- + 4 + from typing import Annotated + 5 + + 6 | app = FastAPI() + … 81 | # First param should be fixed with default preserved - - optional_param: str = Query("default", description="Optional"), -82 + optional_param: Annotated[str, Query(description="Optional")] = "default", -83 | # Second param should not be fixed because of the preceding default +82 ~ optional_param: Annotated[str, Query(description="Optional")] = "default", | note: This is an unsafe fix and may change runtime behavior @@ -233,13 +215,11 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing.Annotated` | -3 | from fastapi import Body, Cookie, FastAPI, Header, Query -4 + from typing import Annotated -5 | --------------------------------------------------------------------------------- + 4 + from typing import Annotated + 5 + + 6 | app = FastAPI() + … 85 | # Third param should be fixed with default preserved - - another_optional_param: int = Query(42, description="Another optional"), -86 + another_optional_param: Annotated[int, Query(description="Another optional")] = 42, -87 | ) -> str: +86 ~ another_optional_param: Annotated[int, Query(description="Another optional")] = 42, | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_2.py_py38.snap b/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_2.py_py38.snap index 6a316632d9bbb..703b9f315f259 100644 --- a/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_2.py_py38.snap +++ b/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-non-annotated-dependency_FAST002_2.py_py38.snap @@ -13,14 +13,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -3 | from fastapi import Body, Cookie, FastAPI, Header, Query -4 + from typing_extensions import Annotated -5 | --------------------------------------------------------------------------------- + 4 + from typing_extensions import Annotated + 5 + + 6 | app = FastAPI() + … 14 | # This should become: param: Annotated[str, Query(description="Test param")] - - param: str = Query(..., description="Test param"), -15 + param: Annotated[str, Query(description="Test param")], -16 | ) -> str: +15 ~ param: Annotated[str, Query(description="Test param")], | note: This is an unsafe fix and may change runtime behavior @@ -36,14 +34,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -3 | from fastapi import Body, Cookie, FastAPI, Header, Query -4 + from typing_extensions import Annotated -5 | --------------------------------------------------------------------------------- + 4 + from typing_extensions import Annotated + 5 + + 6 | app = FastAPI() + … 22 | # This should become: auth: Annotated[str, Header(description="Auth header")] - - auth: str = Header(..., description="Auth header"), -23 + auth: Annotated[str, Header(description="Auth header")], -24 | ) -> str: +23 ~ auth: Annotated[str, Header(description="Auth header")], | note: This is an unsafe fix and may change runtime behavior @@ -59,14 +55,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -3 | from fastapi import Body, Cookie, FastAPI, Header, Query -4 + from typing_extensions import Annotated -5 | --------------------------------------------------------------------------------- + 4 + from typing_extensions import Annotated + 5 + + 6 | app = FastAPI() + … 30 | # This should become: data: Annotated[dict, Body(description="Request body")] - - data: dict = Body(..., description="Request body"), -31 + data: Annotated[dict, Body(description="Request body")], -32 | ) -> dict: +31 ~ data: Annotated[dict, Body(description="Request body")], | note: This is an unsafe fix and may change runtime behavior @@ -82,14 +76,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -3 | from fastapi import Body, Cookie, FastAPI, Header, Query -4 + from typing_extensions import Annotated -5 | --------------------------------------------------------------------------------- + 4 + from typing_extensions import Annotated + 5 + + 6 | app = FastAPI() + … 38 | # This should become: session: Annotated[str, Cookie(description="Session ID")] - - session: str = Cookie(..., description="Session ID"), -39 + session: Annotated[str, Cookie(description="Session ID")], -40 | ) -> str: +39 ~ session: Annotated[str, Cookie(description="Session ID")], | note: This is an unsafe fix and may change runtime behavior @@ -105,14 +97,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -3 | from fastapi import Body, Cookie, FastAPI, Header, Query -4 + from typing_extensions import Annotated -5 | --------------------------------------------------------------------------------- + 4 + from typing_extensions import Annotated + 5 + + 6 | app = FastAPI() + … 46 | # This should become: id: Annotated[str, Query()] - - id: str = Query(...), -47 + id: Annotated[str, Query()], -48 | ) -> str: +47 ~ id: Annotated[str, Query()], | note: This is an unsafe fix and may change runtime behavior @@ -128,14 +118,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -3 | from fastapi import Body, Cookie, FastAPI, Header, Query -4 + from typing_extensions import Annotated -5 | --------------------------------------------------------------------------------- + 4 + from typing_extensions import Annotated + 5 + + 6 | app = FastAPI() + … 54 | # This should become: param: Annotated[str, Query(description="Test", min_length=1, max_length=10)] - - param: str = Query(..., description="Test", min_length=1, max_length=10), -55 + param: Annotated[str, Query(description="Test", min_length=1, max_length=10)], -56 | ) -> str: +55 ~ param: Annotated[str, Query(description="Test", min_length=1, max_length=10)], | note: This is an unsafe fix and may change runtime behavior @@ -151,14 +139,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -3 | from fastapi import Body, Cookie, FastAPI, Header, Query -4 + from typing_extensions import Annotated -5 | --------------------------------------------------------------------------------- + 4 + from typing_extensions import Annotated + 5 + + 6 | app = FastAPI() + … 65 | # This should become: param: Annotated[str, Query(description="Test")] = "default" - - param: str = Query("default", description="Test"), -66 + param: Annotated[str, Query(description="Test")] = "default", -67 | ) -> str: +66 ~ param: Annotated[str, Query(description="Test")] = "default", | note: This is an unsafe fix and may change runtime behavior @@ -174,14 +160,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -3 | from fastapi import Body, Cookie, FastAPI, Header, Query -4 + from typing_extensions import Annotated -5 | --------------------------------------------------------------------------------- + 4 + from typing_extensions import Annotated + 5 + + 6 | app = FastAPI() + … 73 | # This should become: param: Annotated[str | None, Query(description="Test")] = None - - param: str | None = Query(None, description="Test"), -74 + param: Annotated[str | None, Query(description="Test")] = None, -75 | ) -> str: +74 ~ param: Annotated[str | None, Query(description="Test")] = None, | note: This is an unsafe fix and may change runtime behavior @@ -197,14 +181,12 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -3 | from fastapi import Body, Cookie, FastAPI, Header, Query -4 + from typing_extensions import Annotated -5 | --------------------------------------------------------------------------------- + 4 + from typing_extensions import Annotated + 5 + + 6 | app = FastAPI() + … 81 | # First param should be fixed with default preserved - - optional_param: str = Query("default", description="Optional"), -82 + optional_param: Annotated[str, Query(description="Optional")] = "default", -83 | # Second param should not be fixed because of the preceding default +82 ~ optional_param: Annotated[str, Query(description="Optional")] = "default", | note: This is an unsafe fix and may change runtime behavior @@ -233,13 +215,11 @@ FAST002 [*] FastAPI dependency without `Annotated` | help: Replace with `typing_extensions.Annotated` | -3 | from fastapi import Body, Cookie, FastAPI, Header, Query -4 + from typing_extensions import Annotated -5 | --------------------------------------------------------------------------------- + 4 + from typing_extensions import Annotated + 5 + + 6 | app = FastAPI() + … 85 | # Third param should be fixed with default preserved - - another_optional_param: int = Query(42, description="Another optional"), -86 + another_optional_param: Annotated[int, Query(description="Another optional")] = 42, -87 | ) -> str: +86 ~ another_optional_param: Annotated[int, Query(description="Another optional")] = 42, | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-unused-path-parameter_FAST003.py.snap b/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-unused-path-parameter_FAST003.py.snap index a9ce197dee9c6..2ecd96484ef11 100644 --- a/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-unused-path-parameter_FAST003.py.snap +++ b/crates/ruff_linter/src/rules/fastapi/snapshots/ruff_linter__rules__fastapi__tests__fast-api-unused-path-parameter_FAST003.py.snap @@ -12,11 +12,8 @@ FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing` | help: Add `thing_id` to function signature | -9 | @app.get("/things/{thing_id}") - - async def read_thing(query: str): -10 + async def read_thing(query: str, thing_id): -11 | return {"query": query} - | +10 | async def read_thing(query: str, thing_id): + | ++++++++++ note: This is an unsafe fix and may change runtime behavior FAST003 [*] Parameter `isbn` appears in route path, but not in `read_thing` signature @@ -29,11 +26,8 @@ FAST003 [*] Parameter `isbn` appears in route path, but not in `read_thing` sign | help: Add `isbn` to function signature | -14 | @app.get("/books/isbn-{isbn}") - - async def read_thing(): -15 + async def read_thing(isbn): -16 | ... - | +15 | async def read_thing(isbn): + | ++++ note: This is an unsafe fix and may change runtime behavior FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing` signature @@ -46,11 +40,8 @@ FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing` | help: Add `thing_id` to function signature | -19 | @app.get("/things/{thing_id:path}") - - async def read_thing(query: str): -20 + async def read_thing(query: str, thing_id): -21 | return {"query": query} - | +20 | async def read_thing(query: str, thing_id): + | ++++++++++ note: This is an unsafe fix and may change runtime behavior FAST003 [*] Parameter `title` appears in route path, but not in `read_thing` signature @@ -63,11 +54,8 @@ FAST003 [*] Parameter `title` appears in route path, but not in `read_thing` sig | help: Add `title` to function signature | -29 | @app.get("/books/{author}/{title}") - - async def read_thing(author: str): -30 + async def read_thing(author: str, title): -31 | return {"author": author} - | +30 | async def read_thing(author: str, title): + | +++++++ note: This is an unsafe fix and may change runtime behavior FAST003 [*] Parameter `author_name` appears in route path, but not in `read_thing` signature @@ -80,11 +68,8 @@ FAST003 [*] Parameter `author_name` appears in route path, but not in `read_thin | help: Add `author_name` to function signature | -34 | @app.get("/books/{author_name}/{title}") - - async def read_thing(): -35 + async def read_thing(author_name): -36 | ... - | +35 | async def read_thing(author_name): + | +++++++++++ note: This is an unsafe fix and may change runtime behavior FAST003 [*] Parameter `title` appears in route path, but not in `read_thing` signature @@ -97,11 +82,8 @@ FAST003 [*] Parameter `title` appears in route path, but not in `read_thing` sig | help: Add `title` to function signature | -34 | @app.get("/books/{author_name}/{title}") - - async def read_thing(): -35 + async def read_thing(title): -36 | ... - | +35 | async def read_thing(title): + | +++++ note: This is an unsafe fix and may change runtime behavior FAST003 Parameter `author` appears in route path, but only as a positional-only argument in `read_thing` signature @@ -132,11 +114,8 @@ FAST003 [*] Parameter `title` appears in route path, but not in `read_thing` sig | help: Add `title` to function signature | -46 | author: str, - - query: str, -47 + query: str, title, -48 | ): ... - | +47 | query: str, title, + | +++++++ note: This is an unsafe fix and may change runtime behavior FAST003 [*] Parameter `page` appears in route path, but not in `read_thing` signature @@ -149,11 +128,8 @@ FAST003 [*] Parameter `page` appears in route path, but not in `read_thing` sign | help: Add `page` to function signature | -46 | author: str, - - query: str, -47 + query: str, page, -48 | ): ... - | +47 | query: str, page, + | ++++++ note: This is an unsafe fix and may change runtime behavior FAST003 [*] Parameter `author` appears in route path, but not in `read_thing` signature @@ -166,11 +142,8 @@ FAST003 [*] Parameter `author` appears in route path, but not in `read_thing` si | help: Add `author` to function signature | -51 | @app.get("/books/{author}/{title}") - - async def read_thing(): -52 + async def read_thing(author): -53 | ... - | +52 | async def read_thing(author): + | ++++++ note: This is an unsafe fix and may change runtime behavior FAST003 [*] Parameter `title` appears in route path, but not in `read_thing` signature @@ -183,11 +156,8 @@ FAST003 [*] Parameter `title` appears in route path, but not in `read_thing` sig | help: Add `title` to function signature | -51 | @app.get("/books/{author}/{title}") - - async def read_thing(): -52 + async def read_thing(title): -53 | ... - | +52 | async def read_thing(title): + | +++++ note: This is an unsafe fix and may change runtime behavior FAST003 [*] Parameter `title` appears in route path, but not in `read_thing` signature @@ -200,11 +170,8 @@ FAST003 [*] Parameter `title` appears in route path, but not in `read_thing` sig | help: Add `title` to function signature | -56 | @app.get("/books/{author}/{title}") - - async def read_thing(*, author: str): -57 + async def read_thing(title, *, author: str): -58 | ... - | +57 | async def read_thing(title, *, author: str): + | ++++++ note: This is an unsafe fix and may change runtime behavior FAST003 [*] Parameter `title` appears in route path, but not in `read_thing` signature @@ -217,11 +184,8 @@ FAST003 [*] Parameter `title` appears in route path, but not in `read_thing` sig | help: Add `title` to function signature | -61 | @app.get("/books/{author}/{title}") - - async def read_thing(hello, /, *, author: str): -62 + async def read_thing(hello, /, title, *, author: str): -63 | ... - | +62 | async def read_thing(hello, /, title, *, author: str): + | ++++++ note: This is an unsafe fix and may change runtime behavior FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing` signature @@ -234,11 +198,8 @@ FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing` | help: Add `thing_id` to function signature | -67 | async def read_thing( - - query: str, -68 + query: str, thing_id, -69 | ): - | +68 | query: str, thing_id, + | ++++++++++ note: This is an unsafe fix and may change runtime behavior FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing` signature @@ -251,11 +212,8 @@ FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing` | help: Add `thing_id` to function signature | -74 | async def read_thing( - - query: str = "default", -75 + thing_id, query: str = "default", -76 | ): - | +75 | thing_id, query: str = "default", + | +++++++++ note: This is an unsafe fix and may change runtime behavior FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing` signature @@ -268,11 +226,8 @@ FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing` | help: Add `thing_id` to function signature | -81 | async def read_thing( - - *, query: str = "default", -82 + thing_id, *, query: str = "default", -83 | ): - | +82 | thing_id, *, query: str = "default", + | +++++++++ note: This is an unsafe fix and may change runtime behavior FAST003 [*] Parameter `name` appears in route path, but not in `read_thing` signature @@ -285,11 +240,8 @@ FAST003 [*] Parameter `name` appears in route path, but not in `read_thing` sign | help: Add `name` to function signature | -87 | @app.get("/books/{name}/{title}") - - async def read_thing(*, author: Annotated[str, Path(alias="author_name")], title: str): -88 + async def read_thing(name, *, author: Annotated[str, Path(alias="author_name")], title: str): -89 | return {"author": author, "title": title} - | +88 | async def read_thing(name, *, author: Annotated[str, Path(alias="author_name")], title: str): + | +++++ note: This is an unsafe fix and may change runtime behavior FAST003 [*] Parameter `thing_id` appears in route path, but not in `default` signature @@ -303,11 +255,8 @@ FAST003 [*] Parameter `thing_id` appears in route path, but not in `default` sig | help: Add `thing_id` to function signature | -160 | @app.get("/things/{thing_id}") - - async def default(other: str = Depends(something_else)): ... -161 + async def default(thing_id, other: str = Depends(something_else)): ... -162 | - | +161 | async def default(thing_id, other: str = Depends(something_else)): ... + | +++++++++ note: This is an unsafe fix and may change runtime behavior FAST003 [*] Parameter `id` appears in route path, but not in `get_id_init_not_annotated` signature @@ -321,11 +270,8 @@ FAST003 [*] Parameter `id` appears in route path, but not in `get_id_init_not_an | help: Add `id` to function signature | -203 | @app.get("/{id}") - - async def get_id_init_not_annotated(params = Depends(InitParams)): ... -204 + async def get_id_init_not_annotated(id, params = Depends(InitParams)): ... -205 | - | +204 | async def get_id_init_not_annotated(id, params = Depends(InitParams)): ... + | +++ note: This is an unsafe fix and may change runtime behavior FAST003 Parameter `import` appears in route path, but not in `get_import` signature @@ -361,11 +307,8 @@ FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing_v | help: Add `thing_id` to function signature | -278 | @app.get("/things/{thing_id}") - - async def read_thing_vararg(*query: str): ... -279 + async def read_thing_vararg(thing_id, *query: str): ... -280 | - | +279 | async def read_thing_vararg(thing_id, *query: str): ... + | +++++++++ note: This is an unsafe fix and may change runtime behavior FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing_kwarg` signature @@ -379,11 +322,8 @@ FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing_k | help: Add `thing_id` to function signature | -281 | @app.get("/things/{thing_id}") - - async def read_thing_kwarg(**query: str): ... -282 + async def read_thing_kwarg(thing_id, **query: str): ... -283 | - | +282 | async def read_thing_kwarg(thing_id, **query: str): ... + | +++++++++ note: This is an unsafe fix and may change runtime behavior FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing_vararg_kwarg` signature @@ -397,11 +337,8 @@ FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing_v | help: Add `thing_id` to function signature | -284 | @app.get("/things/{thing_id}") - - async def read_thing_vararg_kwarg(*args, **kwargs): ... -285 + async def read_thing_vararg_kwarg(thing_id, *args, **kwargs): ... -286 | - | +285 | async def read_thing_vararg_kwarg(thing_id, *args, **kwargs): ... + | +++++++++ note: This is an unsafe fix and may change runtime behavior FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing_posonly` signature @@ -414,11 +351,8 @@ FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing_p | help: Add `thing_id` to function signature | -288 | @app.get("/things/{thing_id}") - - async def read_thing_posonly(query: str, /): ... -289 + async def read_thing_posonly(query: str, /, thing_id): ... -290 | - | +289 | async def read_thing_posonly(query: str, /, thing_id): ... + | ++++++++++ note: This is an unsafe fix and may change runtime behavior FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing_posonly_trailing` signature @@ -432,11 +366,8 @@ FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing_p | help: Add `thing_id` to function signature | -291 | @app.get("/things/{thing_id}") - - async def read_thing_posonly_trailing(query: str, /,): ... -292 + async def read_thing_posonly_trailing(query: str, /, thing_id,): ... -293 | - | +292 | async def read_thing_posonly_trailing(query: str, /, thing_id,): ... + | +++++++++ note: This is an unsafe fix and may change runtime behavior FAST003 Parameter `thing_id` appears in route path, but not in `read_thing_posonly_default` signature @@ -483,8 +414,6 @@ FAST003 [*] Parameter `thing_id` appears in route path, but not in `read_thing_i | help: Add `thing_id` to function signature | -370 | @app.get("/things/{thing_id}") - - async def read_thing_init_and_call_instance_default(query: str = Depends(InitAndCallQuery())): ... -371 + async def read_thing_init_and_call_instance_default(thing_id, query: str = Depends(InitAndCallQuery())): ... - | +371 | async def read_thing_init_and_call_instance_default(thing_id, query: str = Depends(InitAndCallQuery())): ... + | +++++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__auto_return_type.snap b/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__auto_return_type.snap index 777fb7d85a3ac..3b97b2f0ab912 100644 --- a/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__auto_return_type.snap +++ b/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__auto_return_type.snap @@ -10,10 +10,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | - - def func(): -1 + def func() -> int: -2 | return 1 - | +1 | def func() -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -25,11 +23,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `float` | -4 | - - def func(): -5 + def func() -> float: -6 | return 1.5 - | +5 | def func() -> float: + | ++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -41,12 +36,9 @@ ANN201 [*] Missing return type annotation for public function `func` 11 | return 1 | help: Add return type annotation: `float` - | -8 | - - def func(x: int): -9 + def func(x: int) -> float: -10 | if x > 0: - | + | +9 | def func(x: int) -> float: + | ++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -58,11 +50,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `bool` | -15 | - - def func(): -16 + def func() -> bool: -17 | return True - | +16 | def func() -> bool: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -75,11 +64,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `None` | -19 | - - def func(x: int): -20 + def func(x: int) -> None: -21 | if x > 0: - | +20 | def func(x: int) -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -91,11 +77,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `str | float` | -26 | - - def func(x: int): -27 + def func(x: int) -> str | float: -28 | return 1 or 2.5 if x > 0 else 1.5 or "str" - | +27 | def func(x: int) -> str | float: + | ++++++++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -107,11 +90,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `str | float` | -30 | - - def func(x: int): -31 + def func(x: int) -> str | float: -32 | return 1 + 2.5 if x > 0 else 1.5 or "str" - | +31 | def func(x: int) -> str | float: + | ++++++++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 Missing return type annotation for public function `func` @@ -143,11 +123,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | -44 | - - def func(x: int): -45 + def func(x: int) -> int: -46 | if not x: - | +45 | def func(x: int) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -160,11 +137,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int | None` | -51 | - - def func(x: int): -52 + def func(x: int) -> int | None: -53 | if not x: - | +52 | def func(x: int) -> int | None: + | +++++++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -177,11 +151,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `str | int | None` | -58 | - - def func(x: int): -59 + def func(x: int) -> str | int | None: -60 | if not x: - | +59 | def func(x: int) -> str | int | None: + | +++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -194,11 +165,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int | None` | -67 | - - def func(x: int): -68 + def func(x: int) -> int | None: -69 | if x: - | +68 | def func(x: int) -> int | None: + | +++++++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -210,11 +178,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `None` | -72 | - - def func(): -73 + def func() -> None: -74 | x = 1 - | +73 | def func() -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -227,11 +192,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int | None` | -76 | - - def func(x: int): -77 + def func(x: int) -> int | None: -78 | if x > 0: - | +77 | def func(x: int) -> int | None: + | +++++++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -244,11 +206,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `str | int | None` | -81 | - - def func(x: int): -82 + def func(x: int) -> str | int | None: -83 | match x: - | +82 | def func(x: int) -> str | int | None: + | +++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -261,11 +220,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int | None` | -89 | - - def func(x: int): -90 + def func(x: int) -> int | None: -91 | for i in range(5): - | +90 | def func(x: int) -> int | None: + | +++++++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -278,11 +234,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | -95 | - - def func(x: int): -96 + def func(x: int) -> int: -97 | for i in range(5): - | +96 | def func(x: int) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -295,11 +248,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int | None` | -103 | - - def func(x: int): -104 + def func(x: int) -> int | None: -105 | for i in range(5): - | +104 | def func(x: int) -> int | None: + | +++++++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -312,11 +262,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int | None` | -111 | - - def func(x: int): -112 + def func(x: int) -> int | None: -113 | try: - | +112 | def func(x: int) -> int | None: + | +++++++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -329,11 +276,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | -118 | - - def func(x: int): -119 + def func(x: int) -> int: -120 | try: - | +119 | def func(x: int) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -346,11 +290,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | -127 | - - def func(x: int): -128 + def func(x: int) -> int: -129 | try: - | +128 | def func(x: int) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -363,11 +304,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int | None` | -136 | - - def func(x: int): -137 + def func(x: int) -> int | None: -138 | try: - | +137 | def func(x: int) -> int | None: + | +++++++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -380,11 +318,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int | None` | -145 | - - def func(x: int): -146 + def func(x: int) -> int | None: -147 | while x > 0: - | +146 | def func(x: int) -> int | None: + | +++++++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 Missing return type annotation for public function `method` @@ -451,11 +386,8 @@ ANN201 [*] Missing return type annotation for public function `method` | help: Add return type annotation: `float` | -179 | @abstractmethod - - def method(self): -180 + def method(self) -> float: -181 | if self.x > 0: - | +180 | def method(self) -> float: + | ++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -468,11 +400,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int | None` | -186 | - - def func(x: int): -187 + def func(x: int) -> int | None: -188 | try: - | +187 | def func(x: int) -> int | None: + | +++++++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -485,11 +414,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | -193 | - - def func(x: int): -194 + def func(x: int) -> int: -195 | try: - | +194 | def func(x: int) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -502,14 +428,12 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `Never` | -153 | from abc import abstractmethod 154 + from typing import Never -155 | --------------------------------------------------------------------------------- +155 + +156 | + … 203 | - - def func(x: int): -204 + def func(x: int) -> Never: -205 | if not x: +204 ~ def func(x: int) -> Never: | note: This is an unsafe fix and may change runtime behavior @@ -523,11 +447,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | -209 | - - def func(x: int): -210 + def func(x: int) -> int: -211 | if not x: - | +210 | def func(x: int) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -540,11 +461,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | -233 | - - def func(x: int): -234 + def func(x: int) -> int: -235 | if not x: - | +234 | def func(x: int) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -557,11 +475,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | -239 | - - def func(x: int): -240 + def func(x: int) -> int: -241 | if not x: - | +240 | def func(x: int) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -574,11 +489,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int | None` | -247 | - - def func(): -248 + def func() -> int | None: -249 | try: - | +248 | def func() -> int | None: + | +++++++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -591,11 +503,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int | None` | -254 | - - def func(): -255 + def func() -> int | None: -256 | try: - | +255 | def func() -> int | None: + | +++++++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -608,11 +517,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | -261 | - - def func(x: int): -262 + def func(x: int) -> int: -263 | for _ in range(3): - | +262 | def func(x: int) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -625,11 +531,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `None` | -268 | - - def func(x: int): -269 + def func(x: int) -> None: -270 | if x > 5: - | +269 | def func(x: int) -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -642,11 +545,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `None` | -275 | - - def func(x: int): -276 + def func(x: int) -> None: -277 | if x > 5: - | +276 | def func(x: int) -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -659,11 +559,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int | None` | -282 | - - def func(x: int): -283 + def func(x: int) -> int | None: -284 | if x > 5: - | +283 | def func(x: int) -> int | None: + | +++++++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -676,11 +573,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | -289 | - - def func(): -290 + def func() -> int: -291 | try: - | +290 | def func() -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -693,11 +587,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `str | int` | -298 | - - def func(x: int): -299 + def func(x: int) -> str | int: -300 | match x: - | +299 | def func(x: int) -> str | int: + | ++++++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 Missing return type annotation for public function `func` @@ -752,14 +643,10 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `Never` | -216 | - - from typing import overload -217 + from typing import overload, Never +217 ~ from typing import overload, Never 218 | --------------------------------------------------------------------------------- + … 325 | # Test case: function that raises other exceptions should still get NoReturn - - def func(): -326 + def func() -> Never: -327 | raise ValueError +326 ~ def func() -> Never: | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__auto_return_type_py38.snap b/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__auto_return_type_py38.snap index 6f89a8d42ec4a..78c01a3f958c8 100644 --- a/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__auto_return_type_py38.snap +++ b/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__auto_return_type_py38.snap @@ -10,10 +10,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | - - def func(): -1 + def func() -> int: -2 | return 1 - | +1 | def func() -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -25,11 +23,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `float` | -4 | - - def func(): -5 + def func() -> float: -6 | return 1.5 - | +5 | def func() -> float: + | ++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -41,12 +36,9 @@ ANN201 [*] Missing return type annotation for public function `func` 11 | return 1 | help: Add return type annotation: `float` - | -8 | - - def func(x: int): -9 + def func(x: int) -> float: -10 | if x > 0: - | + | +9 | def func(x: int) -> float: + | ++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -58,11 +50,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `bool` | -15 | - - def func(): -16 + def func() -> bool: -17 | return True - | +16 | def func() -> bool: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -75,11 +64,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `None` | -19 | - - def func(x: int): -20 + def func(x: int) -> None: -21 | if x > 0: - | +20 | def func(x: int) -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -91,13 +77,12 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `Union[str, float]` | -1 + from typing import Union -2 | def func(): --------------------------------------------------------------------------------- + 1 + from typing import Union + 2 | def func(): + 3 | return 1 + … 27 | - - def func(x: int): -28 + def func(x: int) -> Union[str, float]: -29 | return 1 or 2.5 if x > 0 else 1.5 or "str" +28 ~ def func(x: int) -> Union[str, float]: | note: This is an unsafe fix and may change runtime behavior @@ -110,13 +95,12 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `Union[str, float]` | -1 + from typing import Union -2 | def func(): --------------------------------------------------------------------------------- + 1 + from typing import Union + 2 | def func(): + 3 | return 1 + … 31 | - - def func(x: int): -32 + def func(x: int) -> Union[str, float]: -33 | return 1 + 2.5 if x > 0 else 1.5 or "str" +32 ~ def func(x: int) -> Union[str, float]: | note: This is an unsafe fix and may change runtime behavior @@ -149,11 +133,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | -44 | - - def func(x: int): -45 + def func(x: int) -> int: -46 | if not x: - | +45 | def func(x: int) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -166,13 +147,12 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `Optional[int]` | -1 + from typing import Optional -2 | def func(): --------------------------------------------------------------------------------- + 1 + from typing import Optional + 2 | def func(): + 3 | return 1 + … 52 | - - def func(x: int): -53 + def func(x: int) -> Optional[int]: -54 | if not x: +53 ~ def func(x: int) -> Optional[int]: | note: This is an unsafe fix and may change runtime behavior @@ -186,13 +166,12 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `Union[str, int, None]` | -1 + from typing import Union -2 | def func(): --------------------------------------------------------------------------------- + 1 + from typing import Union + 2 | def func(): + 3 | return 1 + … 59 | - - def func(x: int): -60 + def func(x: int) -> Union[str, int, None]: -61 | if not x: +60 ~ def func(x: int) -> Union[str, int, None]: | note: This is an unsafe fix and may change runtime behavior @@ -206,13 +185,12 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `Optional[int]` | -1 + from typing import Optional -2 | def func(): --------------------------------------------------------------------------------- + 1 + from typing import Optional + 2 | def func(): + 3 | return 1 + … 68 | - - def func(x: int): -69 + def func(x: int) -> Optional[int]: -70 | if x: +69 ~ def func(x: int) -> Optional[int]: | note: This is an unsafe fix and may change runtime behavior @@ -225,11 +203,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `None` | -72 | - - def func(): -73 + def func() -> None: -74 | x = 1 - | +73 | def func() -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -242,13 +217,12 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `Optional[int]` | -1 + from typing import Optional -2 | def func(): --------------------------------------------------------------------------------- + 1 + from typing import Optional + 2 | def func(): + 3 | return 1 + … 77 | - - def func(x: int): -78 + def func(x: int) -> Optional[int]: -79 | if x > 0: +78 ~ def func(x: int) -> Optional[int]: | note: This is an unsafe fix and may change runtime behavior @@ -262,13 +236,12 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `Union[str, int, None]` | -1 + from typing import Union -2 | def func(): --------------------------------------------------------------------------------- + 1 + from typing import Union + 2 | def func(): + 3 | return 1 + … 82 | - - def func(x: int): -83 + def func(x: int) -> Union[str, int, None]: -84 | match x: +83 ~ def func(x: int) -> Union[str, int, None]: | note: This is an unsafe fix and may change runtime behavior @@ -282,13 +255,12 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `Optional[int]` | -1 + from typing import Optional -2 | def func(): --------------------------------------------------------------------------------- + 1 + from typing import Optional + 2 | def func(): + 3 | return 1 + … 90 | - - def func(x: int): -91 + def func(x: int) -> Optional[int]: -92 | for i in range(5): +91 ~ def func(x: int) -> Optional[int]: | note: This is an unsafe fix and may change runtime behavior @@ -302,11 +274,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | -95 | - - def func(x: int): -96 + def func(x: int) -> int: -97 | for i in range(5): - | +96 | def func(x: int) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -319,13 +288,12 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `Optional[int]` | -1 + from typing import Optional -2 | def func(): --------------------------------------------------------------------------------- + 1 + from typing import Optional + 2 | def func(): + 3 | return 1 + … 104 | - - def func(x: int): -105 + def func(x: int) -> Optional[int]: -106 | for i in range(5): +105 ~ def func(x: int) -> Optional[int]: | note: This is an unsafe fix and may change runtime behavior @@ -339,13 +307,12 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `Optional[int]` | -1 + from typing import Optional -2 | def func(): --------------------------------------------------------------------------------- + 1 + from typing import Optional + 2 | def func(): + 3 | return 1 + … 112 | - - def func(x: int): -113 + def func(x: int) -> Optional[int]: -114 | try: +113 ~ def func(x: int) -> Optional[int]: | note: This is an unsafe fix and may change runtime behavior @@ -359,11 +326,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | -118 | - - def func(x: int): -119 + def func(x: int) -> int: -120 | try: - | +119 | def func(x: int) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -376,11 +340,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | -127 | - - def func(x: int): -128 + def func(x: int) -> int: -129 | try: - | +128 | def func(x: int) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -393,13 +354,12 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `Optional[int]` | -1 + from typing import Optional -2 | def func(): --------------------------------------------------------------------------------- + 1 + from typing import Optional + 2 | def func(): + 3 | return 1 + … 137 | - - def func(x: int): -138 + def func(x: int) -> Optional[int]: -139 | try: +138 ~ def func(x: int) -> Optional[int]: | note: This is an unsafe fix and may change runtime behavior @@ -413,13 +373,12 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `Optional[int]` | -1 + from typing import Optional -2 | def func(): --------------------------------------------------------------------------------- + 1 + from typing import Optional + 2 | def func(): + 3 | return 1 + … 146 | - - def func(x: int): -147 + def func(x: int) -> Optional[int]: -148 | while x > 0: +147 ~ def func(x: int) -> Optional[int]: | note: This is an unsafe fix and may change runtime behavior @@ -487,11 +446,8 @@ ANN201 [*] Missing return type annotation for public function `method` | help: Add return type annotation: `float` | -179 | @abstractmethod - - def method(self): -180 + def method(self) -> float: -181 | if self.x > 0: - | +180 | def method(self) -> float: + | ++++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -504,14 +460,12 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `Optional[int]` | -153 | from abc import abstractmethod 154 + from typing import Optional -155 | --------------------------------------------------------------------------------- +155 + +156 | + … 187 | - - def func(x: int): -188 + def func(x: int) -> Optional[int]: -189 | try: +188 ~ def func(x: int) -> Optional[int]: | note: This is an unsafe fix and may change runtime behavior @@ -525,11 +479,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | -193 | - - def func(x: int): -194 + def func(x: int) -> int: -195 | try: - | +194 | def func(x: int) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -542,14 +493,12 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `NoReturn` | -153 | from abc import abstractmethod 154 + from typing import NoReturn -155 | --------------------------------------------------------------------------------- +155 + +156 | + … 203 | - - def func(x: int): -204 + def func(x: int) -> NoReturn: -205 | if not x: +204 ~ def func(x: int) -> NoReturn: | note: This is an unsafe fix and may change runtime behavior @@ -563,11 +512,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | -209 | - - def func(x: int): -210 + def func(x: int) -> int: -211 | if not x: - | +210 | def func(x: int) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -580,11 +526,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | -233 | - - def func(x: int): -234 + def func(x: int) -> int: -235 | if not x: - | +234 | def func(x: int) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -597,11 +540,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | -239 | - - def func(x: int): -240 + def func(x: int) -> int: -241 | if not x: - | +240 | def func(x: int) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -614,15 +554,11 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `Optional[int]` | -216 | - - from typing import overload -217 + from typing import overload, Optional +217 ~ from typing import overload, Optional 218 | --------------------------------------------------------------------------------- + … 247 | - - def func(): -248 + def func() -> Optional[int]: -249 | try: +248 ~ def func() -> Optional[int]: | note: This is an unsafe fix and may change runtime behavior @@ -636,15 +572,11 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `Optional[int]` | -216 | - - from typing import overload -217 + from typing import overload, Optional +217 ~ from typing import overload, Optional 218 | --------------------------------------------------------------------------------- + … 254 | - - def func(): -255 + def func() -> Optional[int]: -256 | try: +255 ~ def func() -> Optional[int]: | note: This is an unsafe fix and may change runtime behavior @@ -658,11 +590,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | -261 | - - def func(x: int): -262 + def func(x: int) -> int: -263 | for _ in range(3): - | +262 | def func(x: int) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -675,11 +604,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `None` | -268 | - - def func(x: int): -269 + def func(x: int) -> None: -270 | if x > 5: - | +269 | def func(x: int) -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -692,11 +618,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `None` | -275 | - - def func(x: int): -276 + def func(x: int) -> None: -277 | if x > 5: - | +276 | def func(x: int) -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -709,15 +632,11 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `Optional[int]` | -216 | - - from typing import overload -217 + from typing import overload, Optional +217 ~ from typing import overload, Optional 218 | --------------------------------------------------------------------------------- + … 282 | - - def func(x: int): -283 + def func(x: int) -> Optional[int]: -284 | if x > 5: +283 ~ def func(x: int) -> Optional[int]: | note: This is an unsafe fix and may change runtime behavior @@ -731,11 +650,8 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `int` | -289 | - - def func(): -290 + def func() -> int: -291 | try: - | +290 | def func() -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `func` @@ -748,15 +664,11 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `Union[str, int]` | -216 | - - from typing import overload -217 + from typing import overload, Union +217 ~ from typing import overload, Union 218 | --------------------------------------------------------------------------------- + … 298 | - - def func(x: int): -299 + def func(x: int) -> Union[str, int]: -300 | match x: +299 ~ def func(x: int) -> Union[str, int]: | note: This is an unsafe fix and may change runtime behavior @@ -812,14 +724,10 @@ ANN201 [*] Missing return type annotation for public function `func` | help: Add return type annotation: `NoReturn` | -216 | - - from typing import overload -217 + from typing import overload, NoReturn +217 ~ from typing import overload, NoReturn 218 | --------------------------------------------------------------------------------- + … 325 | # Test case: function that raises other exceptions should still get NoReturn - - def func(): -326 + def func() -> NoReturn: -327 | raise ValueError +326 ~ def func() -> NoReturn: | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__defaults.snap b/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__defaults.snap index d4d3b4e9bbefe..b89c0408d8353 100644 --- a/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__defaults.snap +++ b/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__defaults.snap @@ -11,11 +11,8 @@ ANN201 [*] Missing return type annotation for public function `foo` | help: Add return type annotation: `None` | -4 | # Error - - def foo(a, b): -5 + def foo(a, b) -> None: -6 | pass - | +5 | def foo(a, b) -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN001 Missing type annotation for function argument `a` @@ -46,11 +43,8 @@ ANN201 [*] Missing return type annotation for public function `foo` | help: Add return type annotation: `None` | -9 | # Error - - def foo(a: int, b): -10 + def foo(a: int, b) -> None: -11 | pass - | +10 | def foo(a: int, b) -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN001 Missing type annotation for function argument `b` @@ -81,11 +75,8 @@ ANN201 [*] Missing return type annotation for public function `foo` | help: Add return type annotation: `None` | -19 | # Error - - def foo(a: int, b: int): -20 + def foo(a: int, b: int) -> None: -21 | pass - | +20 | def foo(a: int, b: int) -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `foo` @@ -98,11 +89,8 @@ ANN201 [*] Missing return type annotation for public function `foo` | help: Add return type annotation: `None` | -24 | # Error - - def foo(): -25 + def foo() -> None: -26 | pass - | +25 | def foo() -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN401 Dynamically typed expressions (typing.Any) are disallowed in `a` @@ -285,11 +273,8 @@ ANN204 [*] Missing return type annotation for special method `__init__` | help: Add return type annotation: `None` | -158 | @decorator() - - def __init__(self: "Foo", foo: int): -159 + def __init__(self: "Foo", foo: int) -> None: -160 | ... - | +159 | def __init__(self: "Foo", foo: int) -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN204 [*] Missing return type annotation for special method `__init__` @@ -303,11 +288,8 @@ ANN204 [*] Missing return type annotation for special method `__init__` | help: Add return type annotation: `None` | -164 | class Class: - - def __init__(self): -165 + def __init__(self) -> None: -166 | print(f"{self.attr=}") - | +165 | def __init__(self) -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `quoted_escape` @@ -319,10 +301,8 @@ ANN201 [*] Missing return type annotation for public function `quoted_escape` | ^^^^^^^^^^^^^ help: Add return type annotation: `None` | -171 | # should not cause a stack overflow. - - def quoted_escape(x: "'in\x74'"): pass -172 + def quoted_escape(x: "'in\x74'") -> None: pass - | +172 | def quoted_escape(x: "'in\x74'") -> None: pass + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN401 Dynamically typed expressions (typing.Any) are disallowed in `x` diff --git a/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__ignore_fully_untyped.snap b/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__ignore_fully_untyped.snap index 09a88c89c8bfa..eb99ceaf6c4e2 100644 --- a/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__ignore_fully_untyped.snap +++ b/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__ignore_fully_untyped.snap @@ -10,11 +10,8 @@ ANN201 [*] Missing return type annotation for public function `error_partially_t | help: Add return type annotation: `None` | -23 | - - def error_partially_typed_1(a: int, b): -24 + def error_partially_typed_1(a: int, b) -> None: -25 | pass - | +24 | def error_partially_typed_1(a: int, b) -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN001 Missing type annotation for function argument `b` @@ -42,11 +39,8 @@ ANN201 [*] Missing return type annotation for public function `error_partially_t | help: Add return type annotation: `None` | -31 | - - def error_partially_typed_3(a: int, b: int): -32 + def error_partially_typed_3(a: int, b: int) -> None: -33 | pass - | +32 | def error_partially_typed_3(a: int, b: int) -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `error_typed_self` @@ -60,9 +54,6 @@ ANN201 [*] Missing return type annotation for public function `error_typed_self` | help: Add return type annotation: `None` | -42 | - - def error_typed_self(self: X): -43 + def error_typed_self(self: X) -> None: -44 | pass - | +43 | def error_typed_self(self: X) -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__mypy_init_return.snap b/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__mypy_init_return.snap index 32bcfea7c8477..de8aed9af44af 100644 --- a/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__mypy_init_return.snap +++ b/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__mypy_init_return.snap @@ -12,11 +12,8 @@ ANN204 [*] Missing return type annotation for special method `__init__` | help: Add return type annotation: `None` | -4 | class Foo: - - def __init__(self): -5 + def __init__(self) -> None: -6 | ... - | +5 | def __init__(self) -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN204 [*] Missing return type annotation for special method `__init__` @@ -30,11 +27,8 @@ ANN204 [*] Missing return type annotation for special method `__init__` | help: Add return type annotation: `None` | -10 | class Foo: - - def __init__(self, foo): -11 + def __init__(self, foo) -> None: -12 | ... - | +11 | def __init__(self, foo) -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN202 [*] Missing return type annotation for private function `__init__` @@ -47,11 +41,8 @@ ANN202 [*] Missing return type annotation for private function `__init__` | help: Add return type annotation: `None` | -39 | # Error - - def __init__(self, foo: int): -40 + def __init__(self, foo: int) -> None: -41 | ... - | +40 | def __init__(self, foo: int) -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN204 [*] Missing return type annotation for special method `__init__` @@ -65,9 +56,6 @@ ANN204 [*] Missing return type annotation for special method `__init__` | help: Add return type annotation: `None` | -46 | class Foo: - - def __init__(self, *arg): -47 + def __init__(self, *arg) -> None: -48 | ... - | +47 | def __init__(self, *arg) -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__shadowed_builtins.snap b/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__shadowed_builtins.snap index e5bca2f9e5aa0..136ddd50526f7 100644 --- a/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__shadowed_builtins.snap +++ b/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__shadowed_builtins.snap @@ -12,12 +12,9 @@ ANN201 [*] Missing return type annotation for public function `foo` | help: Add return type annotation: `builtins.str` | -2 | from typing import override 3 + import builtins -4 | - - def foo(): -5 + def foo() -> builtins.str: -6 | return "!" +4 + +5 ~ def foo() -> builtins.str: | note: This is an unsafe fix and may change runtime behavior @@ -32,15 +29,12 @@ ANN202 [*] Missing return type annotation for private function `_foo` | help: Add return type annotation: `builtins.str` | -2 | from typing import override 3 + import builtins -4 | +4 + 5 | def foo(): 6 | return "!" 7 | - - def _foo(): -8 + def _foo() -> builtins.str: -9 | return "!" +8 ~ def _foo() -> builtins.str: | note: This is an unsafe fix and may change runtime behavior @@ -55,14 +49,12 @@ ANN204 [*] Missing return type annotation for special method `__str__` | help: Add return type annotation: `str` | -2 | from typing import override -3 + import builtins -4 | --------------------------------------------------------------------------------- + 3 + import builtins + 4 + + 5 | def foo(): + … 12 | @override - - def __str__(self): -13 + def __str__(self) -> builtins.str: -14 | return "!" +13 ~ def __str__(self) -> builtins.str: | note: This is an unsafe fix and may change runtime behavior @@ -76,14 +68,12 @@ ANN205 [*] Missing return type annotation for staticmethod `foo` | help: Add return type annotation: `builtins.str` | -2 | from typing import override -3 + import builtins -4 | --------------------------------------------------------------------------------- + 3 + import builtins + 4 + + 5 | def foo(): + … 16 | @staticmethod - - def foo(): -17 + def foo() -> builtins.str: -18 | return "!" +17 ~ def foo() -> builtins.str: | note: This is an unsafe fix and may change runtime behavior @@ -97,13 +87,11 @@ ANN206 [*] Missing return type annotation for classmethod `bar` | help: Add return type annotation: `builtins.str` | -2 | from typing import override -3 + import builtins -4 | --------------------------------------------------------------------------------- + 3 + import builtins + 4 + + 5 | def foo(): + … 20 | @classmethod - - def bar(cls): -21 + def bar(cls) -> builtins.str: -22 | return "!" +21 ~ def bar(cls) -> builtins.str: | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__simple_magic_methods.snap b/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__simple_magic_methods.snap index 7021170166719..5d2af747b4598 100644 --- a/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__simple_magic_methods.snap +++ b/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__simple_magic_methods.snap @@ -11,11 +11,8 @@ ANN204 [*] Missing return type annotation for special method `__str__` | help: Add return type annotation: `str` | -1 | class Foo: - - def __str__(self): -2 + def __str__(self) -> str: -3 | ... - | +2 | def __str__(self) -> str: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN204 [*] Missing return type annotation for special method `__repr__` @@ -29,11 +26,8 @@ ANN204 [*] Missing return type annotation for special method `__repr__` | help: Add return type annotation: `str` | -4 | - - def __repr__(self): -5 + def __repr__(self) -> str: -6 | ... - | +5 | def __repr__(self) -> str: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN204 [*] Missing return type annotation for special method `__len__` @@ -47,11 +41,8 @@ ANN204 [*] Missing return type annotation for special method `__len__` | help: Add return type annotation: `int` | -7 | - - def __len__(self): -8 + def __len__(self) -> int: -9 | ... - | +8 | def __len__(self) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN204 [*] Missing return type annotation for special method `__length_hint__` @@ -65,11 +56,8 @@ ANN204 [*] Missing return type annotation for special method `__length_hint__` | help: Add return type annotation: `int` | -10 | - - def __length_hint__(self): -11 + def __length_hint__(self) -> int: -12 | ... - | +11 | def __length_hint__(self) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN204 [*] Missing return type annotation for special method `__init__` @@ -83,11 +71,8 @@ ANN204 [*] Missing return type annotation for special method `__init__` | help: Add return type annotation: `None` | -13 | - - def __init__(self): -14 + def __init__(self) -> None: -15 | ... - | +14 | def __init__(self) -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN204 [*] Missing return type annotation for special method `__del__` @@ -101,11 +86,8 @@ ANN204 [*] Missing return type annotation for special method `__del__` | help: Add return type annotation: `None` | -16 | - - def __del__(self): -17 + def __del__(self) -> None: -18 | ... - | +17 | def __del__(self) -> None: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN204 [*] Missing return type annotation for special method `__bool__` @@ -119,11 +101,8 @@ ANN204 [*] Missing return type annotation for special method `__bool__` | help: Add return type annotation: `bool` | -19 | - - def __bool__(self): -20 + def __bool__(self) -> bool: -21 | ... - | +20 | def __bool__(self) -> bool: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN204 [*] Missing return type annotation for special method `__bytes__` @@ -137,11 +116,8 @@ ANN204 [*] Missing return type annotation for special method `__bytes__` | help: Add return type annotation: `bytes` | -22 | - - def __bytes__(self): -23 + def __bytes__(self) -> bytes: -24 | ... - | +23 | def __bytes__(self) -> bytes: + | ++++++++ note: This is an unsafe fix and may change runtime behavior ANN204 [*] Missing return type annotation for special method `__format__` @@ -155,11 +131,8 @@ ANN204 [*] Missing return type annotation for special method `__format__` | help: Add return type annotation: `str` | -25 | - - def __format__(self, format_spec): -26 + def __format__(self, format_spec) -> str: -27 | ... - | +26 | def __format__(self, format_spec) -> str: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN204 [*] Missing return type annotation for special method `__contains__` @@ -173,11 +146,8 @@ ANN204 [*] Missing return type annotation for special method `__contains__` | help: Add return type annotation: `bool` | -28 | - - def __contains__(self, item): -29 + def __contains__(self, item) -> bool: -30 | ... - | +29 | def __contains__(self, item) -> bool: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN204 [*] Missing return type annotation for special method `__complex__` @@ -191,11 +161,8 @@ ANN204 [*] Missing return type annotation for special method `__complex__` | help: Add return type annotation: `complex` | -31 | - - def __complex__(self): -32 + def __complex__(self) -> complex: -33 | ... - | +32 | def __complex__(self) -> complex: + | ++++++++++ note: This is an unsafe fix and may change runtime behavior ANN204 [*] Missing return type annotation for special method `__int__` @@ -209,11 +176,8 @@ ANN204 [*] Missing return type annotation for special method `__int__` | help: Add return type annotation: `int` | -34 | - - def __int__(self): -35 + def __int__(self) -> int: -36 | ... - | +35 | def __int__(self) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior ANN204 [*] Missing return type annotation for special method `__float__` @@ -227,11 +191,8 @@ ANN204 [*] Missing return type annotation for special method `__float__` | help: Add return type annotation: `float` | -37 | - - def __float__(self): -38 + def __float__(self) -> float: -39 | ... - | +38 | def __float__(self) -> float: + | ++++++++ note: This is an unsafe fix and may change runtime behavior ANN204 [*] Missing return type annotation for special method `__index__` @@ -245,9 +206,6 @@ ANN204 [*] Missing return type annotation for special method `__index__` | help: Add return type annotation: `int` | -40 | - - def __index__(self): -41 + def __index__(self) -> int: -42 | ... - | +41 | def __index__(self) -> int: + | ++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__suppress_none_returning.snap b/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__suppress_none_returning.snap index 2db4acc16e77b..ecd39d42b32cf 100644 --- a/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__suppress_none_returning.snap +++ b/crates/ruff_linter/src/rules/flake8_annotations/snapshots/ruff_linter__rules__flake8_annotations__tests__suppress_none_returning.snap @@ -11,11 +11,8 @@ ANN201 [*] Missing return type annotation for public function `foo` | help: Add return type annotation: `bool` | -44 | # Error - - def foo(): -45 + def foo() -> bool: -46 | return True - | +45 | def foo() -> bool: + | +++++++ note: This is an unsafe fix and may change runtime behavior ANN201 [*] Missing return type annotation for public function `foo` @@ -29,11 +26,8 @@ ANN201 [*] Missing return type annotation for public function `foo` | help: Add return type annotation: `bool | None` | -49 | # Error - - def foo(): -50 + def foo() -> bool | None: -51 | a = 2 + 2 - | +50 | def foo() -> bool | None: + | ++++++++++++++ note: This is an unsafe fix and may change runtime behavior ANN001 Missing type annotation for function argument `a` diff --git a/crates/ruff_linter/src/rules/flake8_async/snapshots/ruff_linter__rules__flake8_async__tests__ASYNC105_ASYNC105.py.snap b/crates/ruff_linter/src/rules/flake8_async/snapshots/ruff_linter__rules__flake8_async__tests__ASYNC105_ASYNC105.py.snap index 4e28a6e8bf883..ecb550bee97e0 100644 --- a/crates/ruff_linter/src/rules/flake8_async/snapshots/ruff_linter__rules__flake8_async__tests__ASYNC105_ASYNC105.py.snap +++ b/crates/ruff_linter/src/rules/flake8_async/snapshots/ruff_linter__rules__flake8_async__tests__ASYNC105_ASYNC105.py.snap @@ -12,11 +12,8 @@ ASYNC105 [*] Call to `trio.aclose_forcefully` is not immediately awaited | help: Add `await` | -29 | # ASYNC105 - - trio.aclose_forcefully(foo) -30 + await trio.aclose_forcefully(foo) -31 | trio.open_file(foo) - | +30 | await trio.aclose_forcefully(foo) + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.open_file` is not immediately awaited @@ -31,11 +28,8 @@ ASYNC105 [*] Call to `trio.open_file` is not immediately awaited | help: Add `await` | -30 | trio.aclose_forcefully(foo) - - trio.open_file(foo) -31 + await trio.open_file(foo) -32 | trio.open_ssl_over_tcp_listeners(foo, foo) - | +31 | await trio.open_file(foo) + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.open_ssl_over_tcp_listeners` is not immediately awaited @@ -50,11 +44,8 @@ ASYNC105 [*] Call to `trio.open_ssl_over_tcp_listeners` is not immediately await | help: Add `await` | -31 | trio.open_file(foo) - - trio.open_ssl_over_tcp_listeners(foo, foo) -32 + await trio.open_ssl_over_tcp_listeners(foo, foo) -33 | trio.open_ssl_over_tcp_stream(foo, foo) - | +32 | await trio.open_ssl_over_tcp_listeners(foo, foo) + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.open_ssl_over_tcp_stream` is not immediately awaited @@ -69,11 +60,8 @@ ASYNC105 [*] Call to `trio.open_ssl_over_tcp_stream` is not immediately awaited | help: Add `await` | -32 | trio.open_ssl_over_tcp_listeners(foo, foo) - - trio.open_ssl_over_tcp_stream(foo, foo) -33 + await trio.open_ssl_over_tcp_stream(foo, foo) -34 | trio.open_tcp_listeners(foo) - | +33 | await trio.open_ssl_over_tcp_stream(foo, foo) + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.open_tcp_listeners` is not immediately awaited @@ -88,11 +76,8 @@ ASYNC105 [*] Call to `trio.open_tcp_listeners` is not immediately awaited | help: Add `await` | -33 | trio.open_ssl_over_tcp_stream(foo, foo) - - trio.open_tcp_listeners(foo) -34 + await trio.open_tcp_listeners(foo) -35 | trio.open_tcp_stream(foo, foo) - | +34 | await trio.open_tcp_listeners(foo) + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.open_tcp_stream` is not immediately awaited @@ -107,11 +92,8 @@ ASYNC105 [*] Call to `trio.open_tcp_stream` is not immediately awaited | help: Add `await` | -34 | trio.open_tcp_listeners(foo) - - trio.open_tcp_stream(foo, foo) -35 + await trio.open_tcp_stream(foo, foo) -36 | trio.open_unix_socket(foo) - | +35 | await trio.open_tcp_stream(foo, foo) + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.open_unix_socket` is not immediately awaited @@ -126,11 +108,8 @@ ASYNC105 [*] Call to `trio.open_unix_socket` is not immediately awaited | help: Add `await` | -35 | trio.open_tcp_stream(foo, foo) - - trio.open_unix_socket(foo) -36 + await trio.open_unix_socket(foo) -37 | trio.run_process(foo) - | +36 | await trio.open_unix_socket(foo) + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.run_process` is not immediately awaited @@ -145,11 +124,8 @@ ASYNC105 [*] Call to `trio.run_process` is not immediately awaited | help: Add `await` | -36 | trio.open_unix_socket(foo) - - trio.run_process(foo) -37 + await trio.run_process(foo) -38 | trio.serve_listeners(foo, foo) - | +37 | await trio.run_process(foo) + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.serve_listeners` is not immediately awaited @@ -164,11 +140,8 @@ ASYNC105 [*] Call to `trio.serve_listeners` is not immediately awaited | help: Add `await` | -37 | trio.run_process(foo) - - trio.serve_listeners(foo, foo) -38 + await trio.serve_listeners(foo, foo) -39 | trio.serve_ssl_over_tcp(foo, foo, foo) - | +38 | await trio.serve_listeners(foo, foo) + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.serve_ssl_over_tcp` is not immediately awaited @@ -183,11 +156,8 @@ ASYNC105 [*] Call to `trio.serve_ssl_over_tcp` is not immediately awaited | help: Add `await` | -38 | trio.serve_listeners(foo, foo) - - trio.serve_ssl_over_tcp(foo, foo, foo) -39 + await trio.serve_ssl_over_tcp(foo, foo, foo) -40 | trio.serve_tcp(foo, foo) - | +39 | await trio.serve_ssl_over_tcp(foo, foo, foo) + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.serve_tcp` is not immediately awaited @@ -202,11 +172,8 @@ ASYNC105 [*] Call to `trio.serve_tcp` is not immediately awaited | help: Add `await` | -39 | trio.serve_ssl_over_tcp(foo, foo, foo) - - trio.serve_tcp(foo, foo) -40 + await trio.serve_tcp(foo, foo) -41 | trio.sleep(foo) - | +40 | await trio.serve_tcp(foo, foo) + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.sleep` is not immediately awaited @@ -221,11 +188,8 @@ ASYNC105 [*] Call to `trio.sleep` is not immediately awaited | help: Add `await` | -40 | trio.serve_tcp(foo, foo) - - trio.sleep(foo) -41 + await trio.sleep(foo) -42 | trio.sleep_forever() - | +41 | await trio.sleep(foo) + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.sleep_forever` is not immediately awaited @@ -240,11 +204,8 @@ ASYNC105 [*] Call to `trio.sleep_forever` is not immediately awaited | help: Add `await` | -41 | trio.sleep(foo) - - trio.sleep_forever() -42 + await trio.sleep_forever() -43 | trio.sleep_until(foo) - | +42 | await trio.sleep_forever() + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.lowlevel.cancel_shielded_checkpoint` is not immediately awaited @@ -259,11 +220,8 @@ ASYNC105 [*] Call to `trio.lowlevel.cancel_shielded_checkpoint` is not immediate | help: Add `await` | -43 | trio.sleep_until(foo) - - trio.lowlevel.cancel_shielded_checkpoint() -44 + await trio.lowlevel.cancel_shielded_checkpoint() -45 | trio.lowlevel.checkpoint() - | +44 | await trio.lowlevel.cancel_shielded_checkpoint() + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.lowlevel.checkpoint` is not immediately awaited @@ -278,11 +236,8 @@ ASYNC105 [*] Call to `trio.lowlevel.checkpoint` is not immediately awaited | help: Add `await` | -44 | trio.lowlevel.cancel_shielded_checkpoint() - - trio.lowlevel.checkpoint() -45 + await trio.lowlevel.checkpoint() -46 | trio.lowlevel.checkpoint_if_cancelled() - | +45 | await trio.lowlevel.checkpoint() + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.lowlevel.checkpoint_if_cancelled` is not immediately awaited @@ -297,11 +252,8 @@ ASYNC105 [*] Call to `trio.lowlevel.checkpoint_if_cancelled` is not immediately | help: Add `await` | -45 | trio.lowlevel.checkpoint() - - trio.lowlevel.checkpoint_if_cancelled() -46 + await trio.lowlevel.checkpoint_if_cancelled() -47 | trio.lowlevel.open_process() - | +46 | await trio.lowlevel.checkpoint_if_cancelled() + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.lowlevel.open_process` is not immediately awaited @@ -316,11 +268,8 @@ ASYNC105 [*] Call to `trio.lowlevel.open_process` is not immediately awaited | help: Add `await` | -46 | trio.lowlevel.checkpoint_if_cancelled() - - trio.lowlevel.open_process() -47 + await trio.lowlevel.open_process() -48 | trio.lowlevel.permanently_detach_coroutine_object(foo) - | +47 | await trio.lowlevel.open_process() + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.lowlevel.permanently_detach_coroutine_object` is not immediately awaited @@ -335,11 +284,8 @@ ASYNC105 [*] Call to `trio.lowlevel.permanently_detach_coroutine_object` is not | help: Add `await` | -47 | trio.lowlevel.open_process() - - trio.lowlevel.permanently_detach_coroutine_object(foo) -48 + await trio.lowlevel.permanently_detach_coroutine_object(foo) -49 | trio.lowlevel.reattach_detached_coroutine_object(foo, foo) - | +48 | await trio.lowlevel.permanently_detach_coroutine_object(foo) + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.lowlevel.reattach_detached_coroutine_object` is not immediately awaited @@ -354,11 +300,8 @@ ASYNC105 [*] Call to `trio.lowlevel.reattach_detached_coroutine_object` is not i | help: Add `await` | -48 | trio.lowlevel.permanently_detach_coroutine_object(foo) - - trio.lowlevel.reattach_detached_coroutine_object(foo, foo) -49 + await trio.lowlevel.reattach_detached_coroutine_object(foo, foo) -50 | trio.lowlevel.temporarily_detach_coroutine_object(foo) - | +49 | await trio.lowlevel.reattach_detached_coroutine_object(foo, foo) + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.lowlevel.temporarily_detach_coroutine_object` is not immediately awaited @@ -373,11 +316,8 @@ ASYNC105 [*] Call to `trio.lowlevel.temporarily_detach_coroutine_object` is not | help: Add `await` | -49 | trio.lowlevel.reattach_detached_coroutine_object(foo, foo) - - trio.lowlevel.temporarily_detach_coroutine_object(foo) -50 + await trio.lowlevel.temporarily_detach_coroutine_object(foo) -51 | trio.lowlevel.wait_readable(foo) - | +50 | await trio.lowlevel.temporarily_detach_coroutine_object(foo) + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.lowlevel.wait_readable` is not immediately awaited @@ -392,11 +332,8 @@ ASYNC105 [*] Call to `trio.lowlevel.wait_readable` is not immediately awaited | help: Add `await` | -50 | trio.lowlevel.temporarily_detach_coroutine_object(foo) - - trio.lowlevel.wait_readable(foo) -51 + await trio.lowlevel.wait_readable(foo) -52 | trio.lowlevel.wait_task_rescheduled(foo) - | +51 | await trio.lowlevel.wait_readable(foo) + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.lowlevel.wait_task_rescheduled` is not immediately awaited @@ -410,11 +347,8 @@ ASYNC105 [*] Call to `trio.lowlevel.wait_task_rescheduled` is not immediately aw | help: Add `await` | -51 | trio.lowlevel.wait_readable(foo) - - trio.lowlevel.wait_task_rescheduled(foo) -52 + await trio.lowlevel.wait_task_rescheduled(foo) -53 | trio.lowlevel.wait_writable(foo) - | +52 | await trio.lowlevel.wait_task_rescheduled(foo) + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.lowlevel.wait_writable` is not immediately awaited @@ -429,11 +363,8 @@ ASYNC105 [*] Call to `trio.lowlevel.wait_writable` is not immediately awaited | help: Add `await` | -52 | trio.lowlevel.wait_task_rescheduled(foo) - - trio.lowlevel.wait_writable(foo) -53 + await trio.lowlevel.wait_writable(foo) -54 | - | +53 | await trio.lowlevel.wait_writable(foo) + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 [*] Call to `trio.open_file` is not immediately awaited @@ -447,11 +378,8 @@ ASYNC105 [*] Call to `trio.open_file` is not immediately awaited | help: Add `await` | -57 | - - async with trio.open_file(foo): # ASYNC105 -58 + async with await trio.open_file(foo): # ASYNC105 -59 | pass - | +58 | async with await trio.open_file(foo): # ASYNC105 + | +++++ note: This is an unsafe fix and may change runtime behavior ASYNC105 Call to `trio.open_file` is not immediately awaited diff --git a/crates/ruff_linter/src/rules/flake8_async/snapshots/ruff_linter__rules__flake8_async__tests__ASYNC115_ASYNC115.py.snap b/crates/ruff_linter/src/rules/flake8_async/snapshots/ruff_linter__rules__flake8_async__tests__ASYNC115_ASYNC115.py.snap index 539627b95dee7..1183e60352b5c 100644 --- a/crates/ruff_linter/src/rules/flake8_async/snapshots/ruff_linter__rules__flake8_async__tests__ASYNC115_ASYNC115.py.snap +++ b/crates/ruff_linter/src/rules/flake8_async/snapshots/ruff_linter__rules__flake8_async__tests__ASYNC115_ASYNC115.py.snap @@ -18,9 +18,7 @@ help: Replace with `trio.lowlevel.checkpoint()` 3 | import trio 4 | from trio import sleep 5 | - - await trio.sleep(0) # ASYNC115 -6 + await trio.lowlevel.checkpoint() # ASYNC115 -7 | await trio.sleep(1) # OK +6 ~ await trio.lowlevel.checkpoint() # ASYNC115 | ASYNC115 [*] Use `trio.lowlevel.checkpoint()` instead of `trio.sleep(0)` @@ -35,13 +33,12 @@ ASYNC115 [*] Use `trio.lowlevel.checkpoint()` instead of `trio.sleep(0)` | help: Replace with `trio.lowlevel.checkpoint()` | -1 + import trio.lowlevel -2 | async def func(): --------------------------------------------------------------------------------- + 1 + import trio.lowlevel + 2 | async def func(): + 3 | import trio + … 11 | - - trio.sleep(0) # ASYNC115 -12 + trio.lowlevel.checkpoint() # ASYNC115 -13 | foo = 0 +12 ~ trio.lowlevel.checkpoint() # ASYNC115 | ASYNC115 [*] Use `trio.lowlevel.checkpoint()` instead of `trio.sleep(0)` @@ -56,13 +53,12 @@ ASYNC115 [*] Use `trio.lowlevel.checkpoint()` instead of `trio.sleep(0)` | help: Replace with `trio.lowlevel.checkpoint()` | -1 + import trio.lowlevel -2 | async def func(): --------------------------------------------------------------------------------- + 1 + import trio.lowlevel + 2 | async def func(): + 3 | import trio + … 17 | - - sleep(0) # ASYNC115 -18 + trio.lowlevel.checkpoint() # ASYNC115 -19 | +18 ~ trio.lowlevel.checkpoint() # ASYNC115 | ASYNC115 [*] Use `trio.lowlevel.checkpoint()` instead of `trio.sleep(0)` @@ -74,13 +70,12 @@ ASYNC115 [*] Use `trio.lowlevel.checkpoint()` instead of `trio.sleep(0)` | ^^^^^^^^^^^^^ help: Replace with `trio.lowlevel.checkpoint()` | -1 + import trio.lowlevel -2 | async def func(): --------------------------------------------------------------------------------- + 1 + import trio.lowlevel + 2 | async def func(): + 3 | import trio + … 48 | - - trio.run(trio.sleep(0)) # ASYNC115 -49 + trio.run(trio.lowlevel.checkpoint()) # ASYNC115 -50 | +49 ~ trio.run(trio.lowlevel.checkpoint()) # ASYNC115 | ASYNC115 [*] Use `trio.lowlevel.checkpoint()` instead of `trio.sleep(0)` @@ -91,14 +86,11 @@ ASYNC115 [*] Use `trio.lowlevel.checkpoint()` instead of `trio.sleep(0)` | ^^^^^^^^ help: Replace with `trio.lowlevel.checkpoint()` | -51 | from trio import Event, sleep 52 + import trio.lowlevel -53 | +53 + 54 | 55 | def func(): - - sleep(0) # ASYNC115 -56 + trio.lowlevel.checkpoint() # ASYNC115 -57 | +56 ~ trio.lowlevel.checkpoint() # ASYNC115 | ASYNC115 [*] Use `trio.lowlevel.checkpoint()` instead of `trio.sleep(0)` @@ -109,14 +101,12 @@ ASYNC115 [*] Use `trio.lowlevel.checkpoint()` instead of `trio.sleep(0)` | ^^^^^^^^^^^^^^^^ help: Replace with `trio.lowlevel.checkpoint()` | -51 | from trio import Event, sleep 52 + import trio.lowlevel -53 | --------------------------------------------------------------------------------- +53 + +54 | + … 59 | async def func(): - - await sleep(seconds=0) # ASYNC115 -60 + await trio.lowlevel.checkpoint() # ASYNC115 -61 | +60 ~ await trio.lowlevel.checkpoint() # ASYNC115 | ASYNC115 [*] Use `anyio.lowlevel.checkpoint()` instead of `anyio.sleep(0)` @@ -131,14 +121,12 @@ ASYNC115 [*] Use `anyio.lowlevel.checkpoint()` instead of `anyio.sleep(0)` | help: Replace with `anyio.lowlevel.checkpoint()` | -51 | from trio import Event, sleep 52 + import anyio.lowlevel -53 | --------------------------------------------------------------------------------- +53 + +54 | + … 85 | - - await anyio.sleep(0) # ASYNC115 -86 + await anyio.lowlevel.checkpoint() # ASYNC115 -87 | await anyio.sleep(1) # OK +86 ~ await anyio.lowlevel.checkpoint() # ASYNC115 | ASYNC115 [*] Use `anyio.lowlevel.checkpoint()` instead of `anyio.sleep(0)` @@ -153,14 +141,12 @@ ASYNC115 [*] Use `anyio.lowlevel.checkpoint()` instead of `anyio.sleep(0)` | help: Replace with `anyio.lowlevel.checkpoint()` | -51 | from trio import Event, sleep 52 + import anyio.lowlevel -53 | --------------------------------------------------------------------------------- +53 + +54 | + … 91 | - - anyio.sleep(0) # ASYNC115 -92 + anyio.lowlevel.checkpoint() # ASYNC115 -93 | foo = 0 +92 ~ anyio.lowlevel.checkpoint() # ASYNC115 | ASYNC115 [*] Use `anyio.lowlevel.checkpoint()` instead of `anyio.sleep(0)` @@ -175,14 +161,12 @@ ASYNC115 [*] Use `anyio.lowlevel.checkpoint()` instead of `anyio.sleep(0)` | help: Replace with `anyio.lowlevel.checkpoint()` | -51 | from trio import Event, sleep 52 + import anyio.lowlevel -53 | --------------------------------------------------------------------------------- +53 + +54 | + … 97 | - - sleep(0) # ASYNC115 -98 + anyio.lowlevel.checkpoint() # ASYNC115 -99 | +98 ~ anyio.lowlevel.checkpoint() # ASYNC115 | ASYNC115 [*] Use `anyio.lowlevel.checkpoint()` instead of `anyio.sleep(0)` @@ -194,14 +178,12 @@ ASYNC115 [*] Use `anyio.lowlevel.checkpoint()` instead of `anyio.sleep(0)` | ^^^^^^^^^^^^^^ help: Replace with `anyio.lowlevel.checkpoint()` | -51 | from trio import Event, sleep -52 + import anyio.lowlevel -53 | --------------------------------------------------------------------------------- + 52 + import anyio.lowlevel + 53 + + 54 | + … 128 | - - anyio.run(anyio.sleep(0)) # ASYNC115 -129 + anyio.run(anyio.lowlevel.checkpoint()) # ASYNC115 -130 | +129 ~ anyio.run(anyio.lowlevel.checkpoint()) # ASYNC115 | ASYNC115 [*] Use `anyio.lowlevel.checkpoint()` instead of `anyio.sleep(0)` @@ -215,14 +197,12 @@ ASYNC115 [*] Use `anyio.lowlevel.checkpoint()` instead of `anyio.sleep(0)` | help: Replace with `anyio.lowlevel.checkpoint()` | -51 | from trio import Event, sleep -52 + import anyio.lowlevel -53 | --------------------------------------------------------------------------------- + 52 + import anyio.lowlevel + 53 + + 54 | + … 156 | - - await anyio.sleep(delay=0) # ASYNC115 -157 + await anyio.lowlevel.checkpoint() # ASYNC115 -158 | await anyio.sleep(seconds=0) # OK +157 ~ await anyio.lowlevel.checkpoint() # ASYNC115 | ASYNC115 [*] Use `trio.lowlevel.checkpoint()` instead of `trio.sleep(0)` @@ -236,14 +216,12 @@ ASYNC115 [*] Use `trio.lowlevel.checkpoint()` instead of `trio.sleep(0)` | help: Replace with `trio.lowlevel.checkpoint()` | -51 | from trio import Event, sleep -52 + import trio.lowlevel -53 | --------------------------------------------------------------------------------- + 52 + import trio.lowlevel + 53 + + 54 | + … 166 | - - await trio.sleep(seconds=0) # ASYNC115 -167 + await trio.lowlevel.checkpoint() # ASYNC115 -168 | await trio.sleep(delay=0) # OK +167 ~ await trio.lowlevel.checkpoint() # ASYNC115 | ASYNC115 [*] Use `trio.lowlevel.checkpoint()` instead of `trio.sleep(0)` @@ -259,17 +237,12 @@ ASYNC115 [*] Use `trio.lowlevel.checkpoint()` instead of `trio.sleep(0)` | help: Replace with `trio.lowlevel.checkpoint()` | -51 | from trio import Event, sleep -52 + import trio.lowlevel -53 | --------------------------------------------------------------------------------- + 52 + import trio.lowlevel + 53 + + 54 | + … 175 | await ( - - trio # comment - - .sleep( # comment - - 0 # comment - - ) -176 + trio.lowlevel.checkpoint() -177 | ) +176 ~ trio.lowlevel.checkpoint() | note: This is an unsafe fix and may change runtime behavior @@ -282,11 +255,10 @@ ASYNC115 [*] Use `anyio.lowlevel.checkpoint()` instead of `anyio.sleep(0)` | ^^^^^^^^^^^^^^ help: Replace with `anyio.lowlevel.checkpoint()` | -51 | from trio import Event, sleep -52 + import anyio.lowlevel -53 | --------------------------------------------------------------------------------- + 52 + import anyio.lowlevel + 53 + + 54 | + … 188 | - - await anyio_sleep(0) # ASYNC115 -189 + await anyio.lowlevel.checkpoint() # ASYNC115 +189 ~ await anyio.lowlevel.checkpoint() # ASYNC115 | diff --git a/crates/ruff_linter/src/rules/flake8_async/snapshots/ruff_linter__rules__flake8_async__tests__ASYNC116_ASYNC116.py.snap b/crates/ruff_linter/src/rules/flake8_async/snapshots/ruff_linter__rules__flake8_async__tests__ASYNC116_ASYNC116.py.snap index 12ebd5ca0eeb2..84f6285192dc6 100644 --- a/crates/ruff_linter/src/rules/flake8_async/snapshots/ruff_linter__rules__flake8_async__tests__ASYNC116_ASYNC116.py.snap +++ b/crates/ruff_linter/src/rules/flake8_async/snapshots/ruff_linter__rules__flake8_async__tests__ASYNC116_ASYNC116.py.snap @@ -12,10 +12,10 @@ ASYNC116 [*] `trio.sleep()` with >24 hour interval should usually be `trio.sleep | help: Replace with `trio.sleep_forever()` | + 8 ~ import trio + 9 | 10 | # These examples are probably not meant to ever wake up: - - await trio.sleep(100000) # error: 116, "async" -11 + await trio.sleep_forever() # error: 116, "async" -12 | +11 ~ await trio.sleep_forever() # error: 116, "async" | note: This is an unsafe fix and may change runtime behavior @@ -30,10 +30,11 @@ ASYNC116 [*] `trio.sleep()` with >24 hour interval should usually be `trio.sleep | help: Replace with `trio.sleep_forever()` | + 8 ~ import trio + 9 | + … 13 | # 'inf literal' overflow trick - - await trio.sleep(1e999) # error: 116, "async" -14 + await trio.sleep_forever() # error: 116, "async" -15 | +14 ~ await trio.sleep_forever() # error: 116, "async" | note: This is an unsafe fix and may change runtime behavior @@ -48,10 +49,11 @@ ASYNC116 [*] `trio.sleep()` with >24 hour interval should usually be `trio.sleep | help: Replace with `trio.sleep_forever()` | + 8 ~ import trio + 9 | + … 17 | await trio.sleep(86400) - - await trio.sleep(86400.01) # error: 116, "async" -18 + await trio.sleep_forever() # error: 116, "async" -19 | await trio.sleep(86401) # error: 116, "async" +18 ~ await trio.sleep_forever() # error: 116, "async" | note: This is an unsafe fix and may change runtime behavior @@ -67,10 +69,11 @@ ASYNC116 [*] `trio.sleep()` with >24 hour interval should usually be `trio.sleep | help: Replace with `trio.sleep_forever()` | + 8 ~ import trio + 9 | + … 18 | await trio.sleep(86400.01) # error: 116, "async" - - await trio.sleep(86401) # error: 116, "async" -19 + await trio.sleep_forever() # error: 116, "async" -20 | +19 ~ await trio.sleep_forever() # error: 116, "async" | note: This is an unsafe fix and may change runtime behavior @@ -85,10 +88,10 @@ ASYNC116 [*] `trio.sleep()` with >24 hour interval should usually be `trio.sleep | help: Replace with `trio.sleep_forever()` | +45 ~ import trio +46 | 47 | # does not require the call to be awaited, nor in an async fun - - trio.sleep(86401) # error: 116, "async" -48 + trio.sleep_forever() # error: 116, "async" -49 | # also checks that we don't break visit_Call +48 ~ trio.sleep_forever() # error: 116, "async" | note: This is an unsafe fix and may change runtime behavior @@ -101,10 +104,11 @@ ASYNC116 [*] `trio.sleep()` with >24 hour interval should usually be `trio.sleep | ^^^^^^^^^^^^^^^^^ help: Replace with `trio.sleep_forever()` | +45 ~ import trio +46 | + … 49 | # also checks that we don't break visit_Call - - trio.run(trio.sleep(86401)) # error: 116, "async" -50 + trio.run(trio.sleep_forever()) # error: 116, "async" -51 | +50 ~ trio.run(trio.sleep_forever()) # error: 116, "async" | note: This is an unsafe fix and may change runtime behavior @@ -116,14 +120,12 @@ ASYNC116 [*] `trio.sleep()` with >24 hour interval should usually be `trio.sleep | ^^^^^^^^^^^^ help: Replace with `trio.sleep_forever()` | -4 | from math import inf -5 + from trio import sleep_forever -6 | --------------------------------------------------------------------------------- + 5 + from trio import sleep_forever + 6 + + 7 | + … 57 | # catch from import - - await sleep(86401) # error: 116, "async" -58 + await sleep_forever() # error: 116, "async" -59 | +58 ~ await sleep_forever() # error: 116, "async" | note: This is an unsafe fix and may change runtime behavior @@ -138,10 +140,10 @@ ASYNC116 [*] `anyio.sleep()` with >24 hour interval should usually be `anyio.sle | help: Replace with `anyio.sleep_forever()` | +61 ~ import anyio +62 | 63 | # These examples are probably not meant to ever wake up: - - await anyio.sleep(100000) # error: 116, "async" -64 + await anyio.sleep_forever() # error: 116, "async" -65 | +64 ~ await anyio.sleep_forever() # error: 116, "async" | note: This is an unsafe fix and may change runtime behavior @@ -156,10 +158,11 @@ ASYNC116 [*] `anyio.sleep()` with >24 hour interval should usually be `anyio.sle | help: Replace with `anyio.sleep_forever()` | +61 ~ import anyio +62 | + … 66 | # 'inf literal' overflow trick - - await anyio.sleep(1e999) # error: 116, "async" -67 + await anyio.sleep_forever() # error: 116, "async" -68 | +67 ~ await anyio.sleep_forever() # error: 116, "async" | note: This is an unsafe fix and may change runtime behavior @@ -174,10 +177,11 @@ ASYNC116 [*] `anyio.sleep()` with >24 hour interval should usually be `anyio.sle | help: Replace with `anyio.sleep_forever()` | +61 ~ import anyio +62 | + … 70 | await anyio.sleep(86400) - - await anyio.sleep(86400.01) # error: 116, "async" -71 + await anyio.sleep_forever() # error: 116, "async" -72 | await anyio.sleep(86401) # error: 116, "async" +71 ~ await anyio.sleep_forever() # error: 116, "async" | note: This is an unsafe fix and may change runtime behavior @@ -193,10 +197,11 @@ ASYNC116 [*] `anyio.sleep()` with >24 hour interval should usually be `anyio.sle | help: Replace with `anyio.sleep_forever()` | +61 ~ import anyio +62 | + … 71 | await anyio.sleep(86400.01) # error: 116, "async" - - await anyio.sleep(86401) # error: 116, "async" -72 + await anyio.sleep_forever() # error: 116, "async" -73 | +72 ~ await anyio.sleep_forever() # error: 116, "async" | note: This is an unsafe fix and may change runtime behavior @@ -211,10 +216,10 @@ ASYNC116 [*] `anyio.sleep()` with >24 hour interval should usually be `anyio.sle | help: Replace with `anyio.sleep_forever()` | + 98 ~ import anyio + 99 | 100 | # does not require the call to be awaited, nor in an async fun - - anyio.sleep(86401) # error: 116, "async" -101 + anyio.sleep_forever() # error: 116, "async" -102 | # also checks that we don't break visit_Call +101 ~ anyio.sleep_forever() # error: 116, "async" | note: This is an unsafe fix and may change runtime behavior @@ -227,10 +232,11 @@ ASYNC116 [*] `anyio.sleep()` with >24 hour interval should usually be `anyio.sle | ^^^^^^^^^^^^^^^^^^ help: Replace with `anyio.sleep_forever()` | + 98 ~ import anyio + 99 | + … 102 | # also checks that we don't break visit_Call - - anyio.run(anyio.sleep(86401)) # error: 116, "async" -103 + anyio.run(anyio.sleep_forever()) # error: 116, "async" -104 | +103 ~ anyio.run(anyio.sleep_forever()) # error: 116, "async" | note: This is an unsafe fix and may change runtime behavior @@ -242,14 +248,12 @@ ASYNC116 [*] `anyio.sleep()` with >24 hour interval should usually be `anyio.sle | ^^^^^^^^^^^^ help: Replace with `anyio.sleep_forever()` | -4 | from math import inf -5 + from anyio import sleep_forever -6 | --------------------------------------------------------------------------------- + 5 + from anyio import sleep_forever + 6 + + 7 | + … 110 | # catch from import - - await sleep(86401) # error: 116, "async" -111 + await sleep_forever() # error: 116, "async" -112 | +111 ~ await sleep_forever() # error: 116, "async" | note: This is an unsafe fix and may change runtime behavior @@ -264,10 +268,11 @@ ASYNC116 [*] `anyio.sleep()` with >24 hour interval should usually be `anyio.sle | help: Replace with `anyio.sleep_forever()` | +114 ~ import anyio +115 | + … 118 | - - await anyio.sleep(delay=86401) # ASYNC116 -119 + await anyio.sleep_forever() # ASYNC116 -120 | await anyio.sleep(seconds=86401) # OK +119 ~ await anyio.sleep_forever() # ASYNC116 | note: This is an unsafe fix and may change runtime behavior @@ -282,10 +287,11 @@ ASYNC116 [*] `trio.sleep()` with >24 hour interval should usually be `trio.sleep | help: Replace with `trio.sleep_forever()` | +124 ~ import trio +125 | + … 128 | - - await trio.sleep(seconds=86401) # ASYNC116 -129 + await trio.sleep_forever() # ASYNC116 -130 | await trio.sleep(delay=86401) # OK +129 ~ await trio.sleep_forever() # ASYNC116 | note: This is an unsafe fix and may change runtime behavior @@ -300,10 +306,10 @@ ASYNC116 [*] `trio.sleep()` with >24 hour interval should usually be `trio.sleep | help: Replace with `trio.sleep_forever()` | +134 ~ import trio +135 | from trio import sleep 136 | - - await sleep(18446744073709551616) -137 + await trio.sleep_forever() -138 | await trio.sleep(99999999999999999999) +137 ~ await trio.sleep_forever() | note: This is an unsafe fix and may change runtime behavior @@ -315,8 +321,10 @@ ASYNC116 [*] `trio.sleep()` with >24 hour interval should usually be `trio.sleep | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `trio.sleep_forever()` | +134 ~ import trio +135 | from trio import sleep +136 | 137 | await sleep(18446744073709551616) - - await trio.sleep(99999999999999999999) -138 + await trio.sleep_forever() +138 ~ await trio.sleep_forever() | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B004_B004.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B004_B004.py.snap index 3a11ff494e9df..a3c4b1475408e 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B004_B004.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B004_B004.py.snap @@ -13,10 +13,8 @@ B004 [*] Using `hasattr(x, "__call__")` to test if x is callable is unreliable. | help: Replace with `callable()` | -2 | o = object() - - if hasattr(o, "__call__"): +3 - if hasattr(o, "__call__"): 3 + if callable(o): -4 | print("Ooh, callable! Or is it?") | note: This is an unsafe fix and may change runtime behavior @@ -43,10 +41,8 @@ B004 [*] Using `hasattr(x, "__call__")` to test if x is callable is unreliable. | help: Replace with `callable()` | -11 | o = object() - - if builtins.hasattr(o, "__call__"): +12 - if builtins.hasattr(o, "__call__"): 12 + if callable(o): -13 | print("B U G") | note: This is an unsafe fix and may change runtime behavior @@ -72,13 +68,12 @@ B004 [*] Using `hasattr(x, "__call__")` to test if x is callable is unreliable. | help: Replace with `callable()` | -1 + import builtins -2 | def this_is_a_bug(): --------------------------------------------------------------------------------- + 1 + import builtins + 2 | def this_is_a_bug(): + 3 | o = object() + … 24 | - - if hasattr(o, "__call__"): -25 + if builtins.callable(o): -26 | print("STILL a bug!") +25 ~ if builtins.callable(o): | note: This is an unsafe fix and may change runtime behavior @@ -100,16 +95,14 @@ B004 [*] Using `hasattr(x, "__call__")` to test if x is callable is unreliable. | help: Replace with `callable()` | -34 | # The autofix for this is unsafe due to the comments. - - hasattr( - - # comment 1 - - obj, # comment 2 - - # comment 3 - - "__call__", # comment 4 - - # comment 5 - - ) +35 - hasattr( +36 - # comment 1 +37 - obj, # comment 2 +38 - # comment 3 +39 - "__call__", # comment 4 +40 - # comment 5 +41 - ) 35 + callable(obj) -36 | | note: This is an unsafe fix and may change runtime behavior @@ -124,10 +117,8 @@ B004 [*] Using `hasattr(x, "__call__")` to test if x is callable is unreliable. | help: Replace with `callable()` | -44 | - - assert hasattr(operator, "__call__") +45 - assert hasattr(operator, "__call__") 45 + assert callable(operator) -46 | assert callable(operator) is False | note: This is an unsafe fix and may change runtime behavior @@ -140,9 +131,7 @@ B004 [*] Using `hasattr(x, "__call__")` to test if x is callable is unreliable. | help: Replace with `callable()` | -52 | - - assert hasattr(A(), "__call__") +53 - assert hasattr(A(), "__call__") 53 + assert callable(A()) -54 | assert callable(A()) is False | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_1.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_1.py.snap index fccb6abb9f666..2d95490128323 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_1.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_1.py.snap @@ -13,9 +13,7 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -2 | - - def foobar(foor, bar={}): +3 - def foobar(foor, bar={}): 3 + def foobar(foor, bar=None): -4 | """ | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_2.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_2.py.snap index cf7ea3a24b68d..048e7c94f0247 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_2.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_2.py.snap @@ -13,9 +13,7 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -3 | - - def foobar(foor, bar={}): +4 - def foobar(foor, bar={}): 4 + def foobar(foor, bar=None): -5 | """ | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_3.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_3.py.snap index 2a25950871d8a..8eac5262c88f7 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_3.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_3.py.snap @@ -11,9 +11,7 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -3 | - - def foobar(foor, bar={}): +4 - def foobar(foor, bar={}): 4 + def foobar(foor, bar=None): -5 | """ | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_4.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_4.py.snap index 33bd877748659..d035e7d3be6db 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_4.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_4.py.snap @@ -10,12 +10,9 @@ B006 [*] Do not use mutable data structures for argument defaults 8 | print(a) | help: Replace with `None`; initialize within function - | -6 | class FormFeedIndent: - - def __init__(self, a=[]): -7 + def __init__(self, a=None): -8 + if a is None: -9 + a = [] -10 | print(a) - | + | +7 ~ ␌ def __init__(self, a=None): +8 + if a is None: +9 + a = [] + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_5.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_5.py.snap index 018c6e39f4e9d..4f997a3af1cd0 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_5.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_5.py.snap @@ -10,13 +10,10 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -4 | - - def import_module_wrong(value: dict[str, str] = {}): -5 + def import_module_wrong(value: dict[str, str] = None): +5 ~ def import_module_wrong(value: dict[str, str] = None): 6 | import os 7 + if value is None: 8 + value = {} -9 | | note: This is an unsafe fix and may change runtime behavior @@ -29,14 +26,11 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -8 | - - def import_module_with_values_wrong(value: dict[str, str] = {}): -9 + def import_module_with_values_wrong(value: dict[str, str] = None): + 9 ~ def import_module_with_values_wrong(value: dict[str, str] = None): 10 | import os 11 | 12 + if value is None: 13 + value = {} -14 | return 2 | note: This is an unsafe fix and may change runtime behavior @@ -50,15 +44,12 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -14 | - - def import_modules_wrong(value: dict[str, str] = {}): -15 + def import_modules_wrong(value: dict[str, str] = None): +15 ~ def import_modules_wrong(value: dict[str, str] = None): 16 | import os 17 | import sys 18 | import itertools 19 + if value is None: 20 + value = {} -21 | | note: This is an unsafe fix and may change runtime behavior @@ -71,13 +62,10 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -20 | - - def from_import_module_wrong(value: dict[str, str] = {}): -21 + def from_import_module_wrong(value: dict[str, str] = None): +21 ~ def from_import_module_wrong(value: dict[str, str] = None): 22 | from os import path 23 + if value is None: 24 + value = {} -25 | | note: This is an unsafe fix and may change runtime behavior @@ -91,14 +79,11 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -24 | - - def from_imports_module_wrong(value: dict[str, str] = {}): -25 + def from_imports_module_wrong(value: dict[str, str] = None): +25 ~ def from_imports_module_wrong(value: dict[str, str] = None): 26 | from os import path 27 | from sys import version_info 28 + if value is None: 29 + value = {} -30 | | note: This is an unsafe fix and may change runtime behavior @@ -112,14 +97,11 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -29 | - - def import_and_from_imports_module_wrong(value: dict[str, str] = {}): -30 + def import_and_from_imports_module_wrong(value: dict[str, str] = None): +30 ~ def import_and_from_imports_module_wrong(value: dict[str, str] = None): 31 | import os 32 | from sys import version_info 33 + if value is None: 34 + value = {} -35 | | note: This is an unsafe fix and may change runtime behavior @@ -133,14 +115,11 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -34 | - - def import_docstring_module_wrong(value: dict[str, str] = {}): -35 + def import_docstring_module_wrong(value: dict[str, str] = None): +35 ~ def import_docstring_module_wrong(value: dict[str, str] = None): 36 | """Docstring""" 37 | import os 38 + if value is None: 39 + value = {} -40 | | note: This is an unsafe fix and may change runtime behavior @@ -154,14 +133,11 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -39 | - - def import_module_wrong(value: dict[str, str] = {}): -40 + def import_module_wrong(value: dict[str, str] = None): +40 ~ def import_module_wrong(value: dict[str, str] = None): 41 | """Docstring""" 42 | import os; import sys 43 + if value is None: 44 + value = {} -45 | | note: This is an unsafe fix and may change runtime behavior @@ -175,13 +151,10 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -44 | - - def import_module_wrong(value: dict[str, str] = {}): -45 + def import_module_wrong(value: dict[str, str] = None): +45 ~ def import_module_wrong(value: dict[str, str] = None): 46 | """Docstring""" 47 + if value is None: 48 + value = {} -49 | import os; import sys; x = 1 | note: This is an unsafe fix and may change runtime behavior @@ -195,14 +168,11 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -49 | - - def import_module_wrong(value: dict[str, str] = {}): -50 + def import_module_wrong(value: dict[str, str] = None): +50 ~ def import_module_wrong(value: dict[str, str] = None): 51 | """Docstring""" 52 | import os; import sys 53 + if value is None: 54 + value = {} -55 | | note: This is an unsafe fix and may change runtime behavior @@ -215,13 +185,10 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -54 | - - def import_module_wrong(value: dict[str, str] = {}): -55 + def import_module_wrong(value: dict[str, str] = None): +55 ~ def import_module_wrong(value: dict[str, str] = None): 56 | import os; import sys 57 + if value is None: 58 + value = {} -59 | | note: This is an unsafe fix and may change runtime behavior @@ -234,12 +201,9 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -58 | - - def import_module_wrong(value: dict[str, str] = {}): -59 + def import_module_wrong(value: dict[str, str] = None): +59 ~ def import_module_wrong(value: dict[str, str] = None): 60 + if value is None: 61 + value = {} -62 | import os; import sys; x = 1 | note: This is an unsafe fix and may change runtime behavior @@ -252,13 +216,10 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -62 | - - def import_module_wrong(value: dict[str, str] = {}): -63 + def import_module_wrong(value: dict[str, str] = None): +63 ~ def import_module_wrong(value: dict[str, str] = None): 64 | import os; import sys 65 + if value is None: 66 + value = {} -67 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_6.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_6.py.snap index dad396ffb92a0..c7a3d4eb287a0 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_6.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_6.py.snap @@ -12,11 +12,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -3 | - - def foobar(foor, bar={}): - - import os -4 + def foobar(foor, bar=None): -5 + import os +4 ~ def foobar(foor, bar=None): +5 ~ import os 6 + if bar is None: 7 + bar = {} | diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_7.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_7.py.snap index c2ce88d513beb..5f45c9253c7da 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_7.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_7.py.snap @@ -12,11 +12,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -3 | - - def foobar(foor, bar={}): - - import os -4 + def foobar(foor, bar=None): -5 + import os +4 ~ def foobar(foor, bar=None): +5 ~ import os 6 + if bar is None: 7 + bar = {} | diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_8.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_8.py.snap index 671b25ae3998d..1b67ad7159b3d 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_8.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_8.py.snap @@ -10,9 +10,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | - - def foo(a: list = []): +1 - def foo(a: list = []): 1 + def foo(a: list = None): -2 | raise NotImplementedError("") | note: This is an unsafe fix and may change runtime behavior @@ -26,10 +25,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -4 | - - def bar(a: dict = {}): +5 - def bar(a: dict = {}): 5 + def bar(a: dict = None): -6 | """ This one also has a docstring""" | note: This is an unsafe fix and may change runtime behavior @@ -43,13 +40,10 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -9 | - - def baz(a: list = []): -10 + def baz(a: list = None): +10 ~ def baz(a: list = None): 11 | """This one raises a different exception""" 12 + if a is None: 13 + a = [] -14 | raise IndexError() | note: This is an unsafe fix and may change runtime behavior @@ -62,10 +56,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -14 | - - def qux(a: list = []): +15 - def qux(a: list = []): 15 + def qux(a: list = None): -16 | raise NotImplementedError | note: This is an unsafe fix and may change runtime behavior @@ -78,9 +70,7 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -18 | - - def quux(a: list = []): +19 - def quux(a: list = []): 19 + def quux(a: list = None): -20 | raise NotImplemented | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_9.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_9.py.snap index 342b187a10acf..cb40c72b0720a 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_9.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_9.py.snap @@ -10,11 +10,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -16 | - - def f5(x=([1, ])): -17 + def f5(x=None): +17 ~ def f5(x=None): 18 + if x is None: 19 + x = [1] -20 | print(x) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_B008.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_B008.py.snap index d4e71b5232f58..8e9bd409fcecb 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_B008.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B006_B006_B008.py.snap @@ -10,10 +10,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -62 | - - def this_is_wrong(value=[1, 2, 3]): +63 - def this_is_wrong(value=[1, 2, 3]): 63 + def this_is_wrong(value=None): -64 | ... | note: This is an unsafe fix and may change runtime behavior @@ -26,10 +24,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -66 | - - def this_is_also_wrong(value={}): +67 - def this_is_also_wrong(value={}): 67 + def this_is_also_wrong(value=None): -68 | ... | note: This is an unsafe fix and may change runtime behavior @@ -44,10 +40,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -72 | @staticmethod - - def this_is_also_wrong_and_more_indented(value={}): +73 - def this_is_also_wrong_and_more_indented(value={}): 73 + def this_is_also_wrong_and_more_indented(value=None): -74 | pass | note: This is an unsafe fix and may change runtime behavior @@ -63,12 +57,10 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -76 | - - def multiline_arg_wrong(value={ - - - - }): +77 - def multiline_arg_wrong(value={ +78 - +79 - }): 77 + def multiline_arg_wrong(value=None): -78 | ... | note: This is an unsafe fix and may change runtime behavior @@ -90,10 +82,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -84 | - - def and_this(value=set()): +85 - def and_this(value=set()): 85 + def and_this(value=None): -86 | ... | note: This is an unsafe fix and may change runtime behavior @@ -106,10 +96,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -88 | - - def this_too(value=collections.OrderedDict()): +89 - def this_too(value=collections.OrderedDict()): 89 + def this_too(value=None): -90 | ... | note: This is an unsafe fix and may change runtime behavior @@ -122,10 +110,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -92 | - - async def async_this_too(value=collections.defaultdict()): +93 - async def async_this_too(value=collections.defaultdict()): 93 + async def async_this_too(value=None): -94 | ... | note: This is an unsafe fix and may change runtime behavior @@ -138,10 +124,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -96 | - - def dont_forget_me(value=collections.deque()): +97 - def dont_forget_me(value=collections.deque()): 97 + def dont_forget_me(value=None): -98 | ... | note: This is an unsafe fix and may change runtime behavior @@ -155,10 +139,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -101 | # B006 still flags mutable comprehension defaults. - - def list_comprehension_also_not_okay(default=[i**2 for i in range(3)]): +102 - def list_comprehension_also_not_okay(default=[i**2 for i in range(3)]): 102 + def list_comprehension_also_not_okay(default=None): -103 | pass | note: This is an unsafe fix and may change runtime behavior @@ -171,10 +153,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -105 | - - def dict_comprehension_also_not_okay(default={i: i**2 for i in range(3)}): +106 - def dict_comprehension_also_not_okay(default={i: i**2 for i in range(3)}): 106 + def dict_comprehension_also_not_okay(default=None): -107 | pass | note: This is an unsafe fix and may change runtime behavior @@ -187,10 +167,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -109 | - - def set_comprehension_also_not_okay(default={i**2 for i in range(3)}): +110 - def set_comprehension_also_not_okay(default={i**2 for i in range(3)}): 110 + def set_comprehension_also_not_okay(default=None): -111 | pass | note: This is an unsafe fix and may change runtime behavior @@ -203,10 +181,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -113 | - - def kwonlyargs_mutable(*, value=[]): +114 - def kwonlyargs_mutable(*, value=[]): 114 + def kwonlyargs_mutable(*, value=None): -115 | ... | note: This is an unsafe fix and may change runtime behavior @@ -221,10 +197,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -241 | # We should handle arbitrary nesting of these B008. - - def nested_combo(a=[float(3), dt.datetime.now()]): +242 - def nested_combo(a=[float(3), dt.datetime.now()]): 242 + def nested_combo(a=None): -243 | pass | note: This is an unsafe fix and may change runtime behavior @@ -239,10 +213,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -278 | def mutable_annotations( - - a: list[int] | None = [], +279 - a: list[int] | None = [], 279 + a: list[int] | None = None, -280 | b: Optional[Dict[int, int]] = {}, | note: This is an unsafe fix and may change runtime behavior @@ -258,10 +230,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -279 | a: list[int] | None = [], - - b: Optional[Dict[int, int]] = {}, +280 - b: Optional[Dict[int, int]] = {}, 280 + b: Optional[Dict[int, int]] = None, -281 | c: Annotated[Union[Set[str], abc.Sized], "annotation"] = set(), | note: This is an unsafe fix and may change runtime behavior @@ -277,10 +247,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -280 | b: Optional[Dict[int, int]] = {}, - - c: Annotated[Union[Set[str], abc.Sized], "annotation"] = set(), +281 - c: Annotated[Union[Set[str], abc.Sized], "annotation"] = set(), 281 + c: Annotated[Union[Set[str], abc.Sized], "annotation"] = None, -282 | d: typing_extensions.Annotated[Union[Set[str], abc.Sized], "annotation"] = set(), | note: This is an unsafe fix and may change runtime behavior @@ -296,10 +264,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -281 | c: Annotated[Union[Set[str], abc.Sized], "annotation"] = set(), - - d: typing_extensions.Annotated[Union[Set[str], abc.Sized], "annotation"] = set(), +282 - d: typing_extensions.Annotated[Union[Set[str], abc.Sized], "annotation"] = set(), 282 + d: typing_extensions.Annotated[Union[Set[str], abc.Sized], "annotation"] = None, -283 | ): | note: This is an unsafe fix and may change runtime behavior @@ -312,10 +278,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -286 | - - def single_line_func_wrong(value: dict[str, str] = {}): +287 - def single_line_func_wrong(value: dict[str, str] = {}): 287 + def single_line_func_wrong(value: dict[str, str] = None): -288 | """Docstring""" | note: This is an unsafe fix and may change runtime behavior @@ -329,10 +293,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -290 | - - def single_line_func_wrong(value: dict[str, str] = {}): +291 - def single_line_func_wrong(value: dict[str, str] = {}): 291 + def single_line_func_wrong(value: dict[str, str] = None): -292 | """Docstring""" | note: This is an unsafe fix and may change runtime behavior @@ -345,10 +307,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -295 | - - def single_line_func_wrong(value: dict[str, str] = {}): +296 - def single_line_func_wrong(value: dict[str, str] = {}): 296 + def single_line_func_wrong(value: dict[str, str] = None): -297 | """Docstring"""; ... | note: This is an unsafe fix and may change runtime behavior @@ -362,10 +322,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -299 | - - def single_line_func_wrong(value: dict[str, str] = {}): +300 - def single_line_func_wrong(value: dict[str, str] = {}): 300 + def single_line_func_wrong(value: dict[str, str] = None): -301 | """Docstring"""; \ | note: This is an unsafe fix and may change runtime behavior @@ -381,12 +339,10 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -304 | - - def single_line_func_wrong(value: dict[str, str] = { - - # This is a comment - - }): +305 - def single_line_func_wrong(value: dict[str, str] = { +306 - # This is a comment +307 - }): 305 + def single_line_func_wrong(value: dict[str, str] = None): -306 | """Docstring""" | note: This is an unsafe fix and may change runtime behavior @@ -409,9 +365,7 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -315 | - - def single_line_func_wrong(value: dict[str, str] = {}): +316 - def single_line_func_wrong(value: dict[str, str] = {}): 316 + def single_line_func_wrong(value: dict[str, str] = None): -317 | """Docstring without newline""" | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B007_B007.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B007_B007.py.snap index 5c56aec7be75e..5ff70a610ca9a 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B007_B007.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B007_B007.py.snap @@ -23,11 +23,8 @@ B007 [*] Loop control variable `k` not used within loop body | help: Rename unused `k` to `_k` | -17 | for j in range(10): - - for k in range(10): # k not used, i and j used transitively -18 + for _k in range(10): # k not used, i and j used transitively -19 | print(i + j) - | +18 | for _k in range(10): # k not used, i and j used transitively + | + note: This is an unsafe fix and may change runtime behavior B007 Loop control variable `i` not used within loop body @@ -48,11 +45,8 @@ B007 [*] Loop control variable `k` not used within loop body | help: Rename unused `k` to `_k` | -29 | - - for i, (j, (k, l)) in strange_generator(): # i, k not used -30 + for i, (j, (_k, l)) in strange_generator(): # i, k not used -31 | print(j, l) - | +30 | for i, (j, (_k, l)) in strange_generator(): # i, k not used + | + note: This is an unsafe fix and may change runtime behavior B007 Loop control variable `bar` may not be used within loop body @@ -113,11 +107,8 @@ B007 [*] Loop control variable `bar` not used within loop body | help: Rename unused `bar` to `_bar` | -51 | # Fixable. - - for foo, bar, baz in (["1", "2", "3"],): -52 + for foo, _bar, baz in (["1", "2", "3"],): -53 | if foo or baz: - | +52 | for foo, _bar, baz in (["1", "2", "3"],): + | + note: This is an unsafe fix and may change runtime behavior B007 Loop control variable `bar` not used within loop body @@ -144,11 +135,8 @@ B007 [*] Loop control variable `bar` not used within loop body | help: Rename unused `bar` to `_bar` | -67 | # Fixable. - - for foo, bar, baz in (["1", "2", "3"],): -68 + for foo, _bar, baz in (["1", "2", "3"],): -69 | if foo or baz: - | +68 | for foo, _bar, baz in (["1", "2", "3"],): + | + note: This is an unsafe fix and may change runtime behavior B007 Loop control variable `bar` not used within loop body diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B009_B009_B010.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B009_B009_B010.py.snap index 9ae70121a889b..5a2bc561fd79e 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B009_B009_B010.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B009_B009_B010.py.snap @@ -12,10 +12,8 @@ B009 [*] Do not call `getattr` with a constant attribute value. It is not any sa | help: Replace `getattr` with attribute access | -18 | # Invalid usage - - getattr(foo, "bar") +19 - getattr(foo, "bar") 19 + foo.bar -20 | getattr(foo, "_123abc") | B009 [*] Do not call `getattr` with a constant attribute value. It is not any safer than normal property access. @@ -30,10 +28,8 @@ B009 [*] Do not call `getattr` with a constant attribute value. It is not any sa | help: Replace `getattr` with attribute access | -19 | getattr(foo, "bar") - - getattr(foo, "_123abc") +20 - getattr(foo, "_123abc") 20 + foo._123abc -21 | getattr(foo, "__123abc__") | B009 [*] Do not call `getattr` with a constant attribute value. It is not any safer than normal property access. @@ -48,10 +44,8 @@ B009 [*] Do not call `getattr` with a constant attribute value. It is not any sa | help: Replace `getattr` with attribute access | -20 | getattr(foo, "_123abc") - - getattr(foo, "__123abc__") +21 - getattr(foo, "__123abc__") 21 + foo.__123abc__ -22 | getattr(foo, "abc123") | B009 [*] Do not call `getattr` with a constant attribute value. It is not any safer than normal property access. @@ -66,10 +60,8 @@ B009 [*] Do not call `getattr` with a constant attribute value. It is not any sa | help: Replace `getattr` with attribute access | -21 | getattr(foo, "__123abc__") - - getattr(foo, "abc123") +22 - getattr(foo, "abc123") 22 + foo.abc123 -23 | getattr(foo, r"abc123") | B009 [*] Do not call `getattr` with a constant attribute value. It is not any safer than normal property access. @@ -84,10 +76,8 @@ B009 [*] Do not call `getattr` with a constant attribute value. It is not any sa | help: Replace `getattr` with attribute access | -22 | getattr(foo, "abc123") - - getattr(foo, r"abc123") +23 - getattr(foo, r"abc123") 23 + foo.abc123 -24 | _ = lambda x: getattr(x, "bar") | B009 [*] Do not call `getattr` with a constant attribute value. It is not any safer than normal property access. @@ -102,10 +92,8 @@ B009 [*] Do not call `getattr` with a constant attribute value. It is not any sa | help: Replace `getattr` with attribute access | -23 | getattr(foo, r"abc123") - - _ = lambda x: getattr(x, "bar") +24 - _ = lambda x: getattr(x, "bar") 24 + _ = lambda x: x.bar -25 | if getattr(x, "bar"): | B009 [*] Do not call `getattr` with a constant attribute value. It is not any safer than normal property access. @@ -120,10 +108,8 @@ B009 [*] Do not call `getattr` with a constant attribute value. It is not any sa | help: Replace `getattr` with attribute access | -24 | _ = lambda x: getattr(x, "bar") - - if getattr(x, "bar"): +25 - if getattr(x, "bar"): 25 + if x.bar: -26 | pass | B009 [*] Do not call `getattr` with a constant attribute value. It is not any safer than normal property access. @@ -138,10 +124,8 @@ B009 [*] Do not call `getattr` with a constant attribute value. It is not any sa | help: Replace `getattr` with attribute access | -26 | pass - - getattr(1, "real") +27 - getattr(1, "real") 27 + (1).real -28 | getattr(1., "real") | B009 [*] Do not call `getattr` with a constant attribute value. It is not any safer than normal property access. @@ -156,10 +140,8 @@ B009 [*] Do not call `getattr` with a constant attribute value. It is not any sa | help: Replace `getattr` with attribute access | -27 | getattr(1, "real") - - getattr(1., "real") +28 - getattr(1., "real") 28 + (1.).real -29 | getattr(1.0, "real") | B009 [*] Do not call `getattr` with a constant attribute value. It is not any safer than normal property access. @@ -174,10 +156,8 @@ B009 [*] Do not call `getattr` with a constant attribute value. It is not any sa | help: Replace `getattr` with attribute access | -28 | getattr(1., "real") - - getattr(1.0, "real") +29 - getattr(1.0, "real") 29 + (1.0).real -30 | getattr(1j, "real") | B009 [*] Do not call `getattr` with a constant attribute value. It is not any safer than normal property access. @@ -192,10 +172,8 @@ B009 [*] Do not call `getattr` with a constant attribute value. It is not any sa | help: Replace `getattr` with attribute access | -29 | getattr(1.0, "real") - - getattr(1j, "real") +30 - getattr(1j, "real") 30 + (1j).real -31 | getattr(True, "real") | B009 [*] Do not call `getattr` with a constant attribute value. It is not any safer than normal property access. @@ -210,10 +188,8 @@ B009 [*] Do not call `getattr` with a constant attribute value. It is not any sa | help: Replace `getattr` with attribute access | -30 | getattr(1j, "real") - - getattr(True, "real") +31 - getattr(True, "real") 31 + (True).real -32 | getattr(x := 1, "real") | B009 [*] Do not call `getattr` with a constant attribute value. It is not any safer than normal property access. @@ -228,10 +204,8 @@ B009 [*] Do not call `getattr` with a constant attribute value. It is not any sa | help: Replace `getattr` with attribute access | -31 | getattr(True, "real") - - getattr(x := 1, "real") +32 - getattr(x := 1, "real") 32 + (x := 1).real -33 | getattr(x + y, "real") | B009 [*] Do not call `getattr` with a constant attribute value. It is not any safer than normal property access. @@ -246,10 +220,8 @@ B009 [*] Do not call `getattr` with a constant attribute value. It is not any sa | help: Replace `getattr` with attribute access | -32 | getattr(x := 1, "real") - - getattr(x + y, "real") +33 - getattr(x + y, "real") 33 + (x + y).real -34 | getattr("foo" | B009 [*] Do not call `getattr` with a constant attribute value. It is not any safer than normal property access. @@ -262,12 +234,8 @@ B009 [*] Do not call `getattr` with a constant attribute value. It is not any sa | |______________________^ help: Replace `getattr` with attribute access | -33 | getattr(x + y, "real") - - getattr("foo" - - "bar", "real") 34 + ("foo" 35 + "bar").real -36 | | B009 [*] Do not call `getattr` with a constant attribute value. It is not any safer than normal property access. @@ -281,10 +249,8 @@ B009 [*] Do not call `getattr` with a constant attribute value. It is not any sa | help: Replace `getattr` with attribute access | -57 | # Regression test for: https://github.com/astral-sh/ruff/issues/7455#issuecomment-1722458885 - - assert getattr(func, '_rpc')is True +58 - assert getattr(func, '_rpc')is True 58 + assert func._rpc is True -59 | | B009 [*] Do not call `getattr` with a constant attribute value. It is not any safer than normal property access. @@ -299,12 +265,8 @@ B009 [*] Do not call `getattr` with a constant attribute value. It is not any sa | help: Replace `getattr` with attribute access | -64 | # Regression test for: https://github.com/astral-sh/ruff/issues/7455#issuecomment-1739800901 - - getattr(self. - - registration.registry, '__name__') 65 + (self. 66 + registration.registry).__name__ -67 | | B009 [*] Do not call `getattr` with a constant attribute value. It is not any safer than normal property access. @@ -318,10 +280,8 @@ B009 [*] Do not call `getattr` with a constant attribute value. It is not any sa | help: Replace `getattr` with attribute access | -68 | import builtins - - builtins.getattr(foo, "bar") +69 - builtins.getattr(foo, "bar") 69 + foo.bar -70 | | B009 [*] Do not call `getattr` with a constant attribute value. It is not any safer than normal property access. @@ -335,10 +295,8 @@ B009 [*] Do not call `getattr` with a constant attribute value. It is not any sa | help: Replace `getattr` with attribute access | -79 | # Example: the long s character "ſ" normalizes to "s" under NFKC. - - getattr(foo, "ſ") +80 - getattr(foo, "ſ") 80 + foo.ſ -81 | setattr(foo, "ſ", 1) | note: This is an unsafe fix and may change runtime behavior @@ -353,12 +311,11 @@ B009 [*] Do not call `getattr` with a constant attribute value. It is not any sa | |_^ help: Replace `getattr` with attribute access | -83 | - - getattr( - - obj, - - # text - - "foo", - - ) +84 - getattr( +85 - obj, +86 - # text +87 - "foo", +88 - ) 84 + obj.foo | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B010_B009_B010.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B010_B009_B010.py.snap index b9036308d29f3..2dddd37dfaae3 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B010_B009_B010.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B010_B009_B010.py.snap @@ -12,10 +12,8 @@ B010 [*] Do not call `setattr` with a constant attribute value. It is not any sa | help: Replace `setattr` with assignment | -49 | # Invalid usage - - setattr(foo, "bar", None) +50 - setattr(foo, "bar", None) 50 + foo.bar = None -51 | setattr(foo, "_123abc", None) | B010 [*] Do not call `setattr` with a constant attribute value. It is not any safer than normal property access. @@ -30,10 +28,8 @@ B010 [*] Do not call `setattr` with a constant attribute value. It is not any sa | help: Replace `setattr` with assignment | -50 | setattr(foo, "bar", None) - - setattr(foo, "_123abc", None) +51 - setattr(foo, "_123abc", None) 51 + foo._123abc = None -52 | setattr(foo, "__123abc__", None) | B010 [*] Do not call `setattr` with a constant attribute value. It is not any safer than normal property access. @@ -48,10 +44,8 @@ B010 [*] Do not call `setattr` with a constant attribute value. It is not any sa | help: Replace `setattr` with assignment | -51 | setattr(foo, "_123abc", None) - - setattr(foo, "__123abc__", None) +52 - setattr(foo, "__123abc__", None) 52 + foo.__123abc__ = None -53 | setattr(foo, "abc123", None) | B010 [*] Do not call `setattr` with a constant attribute value. It is not any safer than normal property access. @@ -66,10 +60,8 @@ B010 [*] Do not call `setattr` with a constant attribute value. It is not any sa | help: Replace `setattr` with assignment | -52 | setattr(foo, "__123abc__", None) - - setattr(foo, "abc123", None) +53 - setattr(foo, "abc123", None) 53 + foo.abc123 = None -54 | setattr(foo, r"abc123", None) | B010 [*] Do not call `setattr` with a constant attribute value. It is not any safer than normal property access. @@ -83,10 +75,8 @@ B010 [*] Do not call `setattr` with a constant attribute value. It is not any sa | help: Replace `setattr` with assignment | -53 | setattr(foo, "abc123", None) - - setattr(foo, r"abc123", None) +54 - setattr(foo, r"abc123", None) 54 + foo.abc123 = None -55 | setattr(foo.bar, r"baz", None) | B010 [*] Do not call `setattr` with a constant attribute value. It is not any safer than normal property access. @@ -101,10 +91,8 @@ B010 [*] Do not call `setattr` with a constant attribute value. It is not any sa | help: Replace `setattr` with assignment | -54 | setattr(foo, r"abc123", None) - - setattr(foo.bar, r"baz", None) +55 - setattr(foo.bar, r"baz", None) 55 + foo.bar.baz = None -56 | | B010 [*] Do not call `setattr` with a constant attribute value. It is not any safer than normal property access. @@ -116,9 +104,7 @@ B010 [*] Do not call `setattr` with a constant attribute value. It is not any sa | ^^^^^^^^^^^^^^^^^^^^ help: Replace `setattr` with assignment | -80 | getattr(foo, "ſ") - - setattr(foo, "ſ", 1) +81 - setattr(foo, "ſ", 1) 81 + foo.ſ = 1 -82 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B011_B011.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B011_B011.py.snap index 60c7697ffed0c..5512f12abd3c1 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B011_B011.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B011_B011.py.snap @@ -12,10 +12,8 @@ B011 [*] Do not `assert False` (`python -O` removes these calls), raise `Asserti | help: Replace `assert False` | -7 | assert 1 != 2 - - assert False +8 - assert False 8 + raise AssertionError() -9 | assert 1 != 2, "message" | note: This is an unsafe fix and may change runtime behavior @@ -28,8 +26,7 @@ B011 [*] Do not `assert False` (`python -O` removes these calls), raise `Asserti | ^^^^^ help: Replace `assert False` | -9 | assert 1 != 2, "message" - - assert False, "message" +10 - assert False, "message" 10 + raise AssertionError("message") | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B013_B013.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B013_B013.py.snap index f4e2ff87385ee..e5d8a7c209e07 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B013_B013.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B013_B013.py.snap @@ -13,10 +13,8 @@ B013 [*] A length-one tuple literal is redundant in exception handlers | help: Replace with `except ValueError` | -4 | pass - - except (ValueError,): +5 - except (ValueError,): 5 + except ValueError: -6 | pass | B013 [*] A length-one tuple literal is redundant in exception handlers @@ -30,10 +28,8 @@ B013 [*] A length-one tuple literal is redundant in exception handlers | help: Replace with `except ValueError` | -12 | pass - - except(ValueError,): +13 - except(ValueError,): 13 + except ValueError: -14 | pass | B013 [*] A length-one tuple literal is redundant in exception handlers @@ -51,12 +47,10 @@ B013 [*] A length-one tuple literal is redundant in exception handlers | help: Replace with `except ValueError` | -24 | ... - - except ( - - ValueError, - - # text - - ): +25 - except ( +26 - ValueError, +27 - # text +28 - ): 25 + except ValueError: -26 | ... | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B014_B014.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B014_B014.py.snap index 3cabc77d4076a..7fe728f501de9 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B014_B014.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B014_B014.py.snap @@ -13,10 +13,8 @@ B014 [*] Exception handler with duplicate exception: `OSError` | help: De-duplicate exceptions | -16 | pass - - except (OSError, OSError) as err: +17 - except (OSError, OSError) as err: 17 + except OSError as err: -18 | # Duplicate exception types are useless | B014 [*] Exception handler with duplicate exception: `MyError` @@ -31,10 +29,8 @@ B014 [*] Exception handler with duplicate exception: `MyError` | help: De-duplicate exceptions | -27 | pass - - except (MyError, MyError): +28 - except (MyError, MyError): 28 + except MyError: -29 | # Detect duplicate non-builtin errors | B014 [*] Exception handler with duplicate exception: `re.error` @@ -49,10 +45,8 @@ B014 [*] Exception handler with duplicate exception: `re.error` | help: De-duplicate exceptions | -48 | pass - - except (re.error, re.error): +49 - except (re.error, re.error): 49 + except re.error: -50 | # Duplicate exception types as attributes | B014 [*] Exception handler with duplicate exception: `ValueError` @@ -66,10 +60,8 @@ B014 [*] Exception handler with duplicate exception: `ValueError` | help: De-duplicate exceptions | -81 | pass - - except (ValueError, ValueError, TypeError): +82 - except (ValueError, ValueError, TypeError): 82 + except (ValueError, TypeError): -83 | pass | B014 [*] Exception handler with duplicate exception: `re.error` @@ -83,10 +75,8 @@ B014 [*] Exception handler with duplicate exception: `re.error` | help: De-duplicate exceptions | -88 | pas - - except(re.error, re.error): +89 - except(re.error, re.error): 89 + except re.error: -90 | p | B014 [*] Exception handler with duplicate exception: `ValueError` @@ -105,15 +95,13 @@ B014 [*] Exception handler with duplicate exception: `ValueError` 101 | pass | help: De-duplicate exceptions - | -94 | pass - - except ( - - ValueError, - - ValueError, - - # text - - TypeError, - - ): -95 + except (ValueError, TypeError): -96 | pass - | + | + 95 - except ( + 96 - ValueError, + 97 - ValueError, + 98 - # text + 99 - TypeError, +100 - ): + 95 + except (ValueError, TypeError): + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B028_B028.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B028_B028.py.snap index 5382896aec5bf..c39cf7a85a9d4 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B028_B028.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B028_B028.py.snap @@ -13,11 +13,8 @@ B028 [*] No explicit `stacklevel` keyword argument found | help: Set `stacklevel=2` | -7 | - - warnings.warn("test", DeprecationWarning) -8 + warnings.warn("test", DeprecationWarning, stacklevel=2) -9 | warnings.warn("test", DeprecationWarning, source=None) - | +8 | warnings.warn("test", DeprecationWarning, stacklevel=2) + | ++++++++++++++ note: This is an unsafe fix and may change runtime behavior B028 [*] No explicit `stacklevel` keyword argument found @@ -30,12 +27,9 @@ B028 [*] No explicit `stacklevel` keyword argument found 11 | warnings.warn("test", DeprecationWarning, stacklevel=1) | help: Set `stacklevel=2` - | -8 | warnings.warn("test", DeprecationWarning) - - warnings.warn("test", DeprecationWarning, source=None) -9 + warnings.warn("test", DeprecationWarning, stacklevel=2, source=None) -10 | warnings.warn("test", DeprecationWarning, source=None, stacklevel=2) - | + | +9 | warnings.warn("test", DeprecationWarning, stacklevel=2, source=None) + | +++++++++++++ note: This is an unsafe fix and may change runtime behavior B028 [*] No explicit `stacklevel` keyword argument found @@ -50,11 +44,8 @@ B028 [*] No explicit `stacklevel` keyword argument found | help: Set `stacklevel=2` | -25 | # some comments here - - source = None # no trailing comma -26 + stacklevel=2, source = None # no trailing comma -27 | ) - | +26 | stacklevel=2, source = None # no trailing comma + | +++++++++++++ note: This is an unsafe fix and may change runtime behavior B028 [*] No explicit `stacklevel` keyword argument found @@ -69,9 +60,6 @@ B028 [*] No explicit `stacklevel` keyword argument found | help: Set `stacklevel=2` | -31 | # trigger diagnostic if `skip_file_prefixes` is present and set to the default value - - warnings.warn("test", skip_file_prefixes=()) -32 + warnings.warn("test", stacklevel=2, skip_file_prefixes=()) -33 | - | +32 | warnings.warn("test", stacklevel=2, skip_file_prefixes=()) + | +++++++++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B033_B033.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B033_B033.py.snap index e0c5f128b3189..6541c50e9290d 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B033_B033.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B033_B033.py.snap @@ -15,10 +15,8 @@ B033 [*] Sets should not contain duplicate item `"value1"` | help: Remove duplicate item | -3 | ### - - incorrect_set = {"value1", 23, 5, "value1"} +4 - incorrect_set = {"value1", 23, 5, "value1"} 4 + incorrect_set = {"value1", 23, 5} -5 | incorrect_set = {1, 1, 2} | B033 [*] Sets should not contain duplicate item `1` @@ -35,10 +33,8 @@ B033 [*] Sets should not contain duplicate item `1` | help: Remove duplicate item | -4 | incorrect_set = {"value1", 23, 5, "value1"} - - incorrect_set = {1, 1, 2} +5 - incorrect_set = {1, 1, 2} 5 + incorrect_set = {1, 2} -6 | incorrect_set_multiline = { | B033 [*] Sets should not contain duplicate item `"value1"` @@ -57,9 +53,9 @@ B033 [*] Sets should not contain duplicate item `"value1"` | help: Remove duplicate item | -9 | 5, - - "value1", -10 | # B033 + 9 - 5, +10 - "value1", + 9 + 5, | B033 [*] Sets should not contain duplicate item `1` @@ -76,10 +72,8 @@ B033 [*] Sets should not contain duplicate item `1` | help: Remove duplicate item | -12 | } - - incorrect_set = {1, 1} +13 - incorrect_set = {1, 1} 13 + incorrect_set = {1} -14 | incorrect_set = {1, 1,} | B033 [*] Sets should not contain duplicate item `1` @@ -96,10 +90,8 @@ B033 [*] Sets should not contain duplicate item `1` | help: Remove duplicate item | -13 | incorrect_set = {1, 1} - - incorrect_set = {1, 1,} +14 - incorrect_set = {1, 1,} 14 + incorrect_set = {1,} -15 | incorrect_set = {0, 1, 1,} | B033 [*] Sets should not contain duplicate item `1` @@ -116,10 +108,8 @@ B033 [*] Sets should not contain duplicate item `1` | help: Remove duplicate item | -14 | incorrect_set = {1, 1,} - - incorrect_set = {0, 1, 1,} +15 - incorrect_set = {0, 1, 1,} 15 + incorrect_set = {0, 1,} -16 | incorrect_set = {0, 1, 1} | B033 [*] Sets should not contain duplicate item `1` @@ -136,10 +126,8 @@ B033 [*] Sets should not contain duplicate item `1` | help: Remove duplicate item | -15 | incorrect_set = {0, 1, 1,} - - incorrect_set = {0, 1, 1} +16 - incorrect_set = {0, 1, 1} 16 + incorrect_set = {0, 1} -17 | incorrect_set = { | B033 [*] Sets should not contain duplicate item `1` @@ -156,9 +144,7 @@ B033 [*] Sets should not contain duplicate item `1` | help: Remove duplicate item | -19 | 1, - - 1, -20 | } +19 - 1, | B033 [*] Sets should not contain duplicate items, but `False` and `0` has the same value @@ -175,10 +161,8 @@ B033 [*] Sets should not contain duplicate items, but `False` and `0` has the sa | help: Remove duplicate item | -21 | } - - incorrect_set = {False, 1, 0} +22 - incorrect_set = {False, 1, 0} 22 + incorrect_set = {False, 1} -23 | incorrect_set_multiline_with_comment = { | B033 [*] Sets should not contain duplicate item `"value1"` @@ -196,9 +180,9 @@ B033 [*] Sets should not contain duplicate item `"value1"` | help: Remove duplicate item | -25 | 23, - - # B033 - - "value1", -26 | } +25 - 23, +26 - # B033 +27 - "value1", +25 + 23, | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B043_B043.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B043_B043.py.snap index a188337ef79cf..53e1ce6277b11 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B043_B043.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B043_B043.py.snap @@ -12,10 +12,8 @@ B043 [*] Do not call `delattr` with a constant attribute value. It is not any sa | help: Replace `delattr` with `del` statement | -17 | # Invalid usage - - delattr(foo, "bar") +18 - delattr(foo, "bar") 18 + del foo.bar -19 | delattr(foo, "_123abc") | B043 [*] Do not call `delattr` with a constant attribute value. It is not any safer than normal property deletion. @@ -30,10 +28,8 @@ B043 [*] Do not call `delattr` with a constant attribute value. It is not any sa | help: Replace `delattr` with `del` statement | -18 | delattr(foo, "bar") - - delattr(foo, "_123abc") +19 - delattr(foo, "_123abc") 19 + del foo._123abc -20 | delattr(foo, "__123abc__") | B043 [*] Do not call `delattr` with a constant attribute value. It is not any safer than normal property deletion. @@ -48,10 +44,8 @@ B043 [*] Do not call `delattr` with a constant attribute value. It is not any sa | help: Replace `delattr` with `del` statement | -19 | delattr(foo, "_123abc") - - delattr(foo, "__123abc__") +20 - delattr(foo, "__123abc__") 20 + del foo.__123abc__ -21 | delattr(foo, "abc123") | B043 [*] Do not call `delattr` with a constant attribute value. It is not any safer than normal property deletion. @@ -65,10 +59,8 @@ B043 [*] Do not call `delattr` with a constant attribute value. It is not any sa | help: Replace `delattr` with `del` statement | -20 | delattr(foo, "__123abc__") - - delattr(foo, "abc123") +21 - delattr(foo, "abc123") 21 + del foo.abc123 -22 | delattr(foo, r"abc123") | B043 [*] Do not call `delattr` with a constant attribute value. It is not any safer than normal property deletion. @@ -83,10 +75,8 @@ B043 [*] Do not call `delattr` with a constant attribute value. It is not any sa | help: Replace `delattr` with `del` statement | -21 | delattr(foo, "abc123") - - delattr(foo, r"abc123") +22 - delattr(foo, r"abc123") 22 + del foo.abc123 -23 | | B043 [*] Do not call `delattr` with a constant attribute value. It is not any safer than normal property deletion. @@ -100,10 +90,8 @@ B043 [*] Do not call `delattr` with a constant attribute value. It is not any sa | help: Replace `delattr` with `del` statement | -27 | # Non-NFKC attribute name (unsafe fix) - - delattr(foo, "\u017f") +28 - delattr(foo, "\u017f") 28 + del foo.ſ -29 | | note: This is an unsafe fix and may change runtime behavior @@ -122,14 +110,12 @@ B043 [*] Do not call `delattr` with a constant attribute value. It is not any sa | help: Replace `delattr` with `del` statement | -30 | # Comment in expression (unsafe fix) - - delattr( - - obj, - - # text - - "foo", - - ) +31 - delattr( +32 - obj, +33 - # text +34 - "foo", +35 - ) 31 + del obj.foo -32 | | note: This is an unsafe fix and may change runtime behavior @@ -141,7 +127,6 @@ B043 [*] Do not call `delattr` with a constant attribute value. It is not any sa | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace `delattr` with `del` statement | -37 | import builtins - - builtins.delattr(foo, "bar") +38 - builtins.delattr(foo, "bar") 38 + del foo.bar | diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B905.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B905.py.snap index 201710c1ec9b9..d5242f8c554fb 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B905.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B905.py.snap @@ -12,11 +12,8 @@ B905 [*] `zip()` without an explicit `strict=` parameter | help: Add explicit value for parameter `strict=` | -3 | # Errors - - zip("a", "b") -4 + zip("a", "b", strict=False) -5 | zip("a", "b", *zip("c")) - | +4 | zip("a", "b", strict=False) + | ++++++++++++++ note: This is an unsafe fix and may change runtime behavior B905 [*] `zip()` without an explicit `strict=` parameter @@ -31,11 +28,8 @@ B905 [*] `zip()` without an explicit `strict=` parameter | help: Add explicit value for parameter `strict=` | -4 | zip("a", "b") - - zip("a", "b", *zip("c")) -5 + zip("a", "b", *zip("c"), strict=False) -6 | zip(zip("a", "b"), strict=False) - | +5 | zip("a", "b", *zip("c"), strict=False) + | ++++++++++++++ note: This is an unsafe fix and may change runtime behavior B905 [*] `zip()` without an explicit `strict=` parameter @@ -49,11 +43,8 @@ B905 [*] `zip()` without an explicit `strict=` parameter | help: Add explicit value for parameter `strict=` | -5 | zip("a", "b", *zip("c")) - - zip(zip("a", "b"), strict=False) -6 + zip(zip("a", "b", strict=False), strict=False) -7 | zip(zip("a", strict=True),"b") - | +6 | zip(zip("a", "b", strict=False), strict=False) + | ++++++++++++++ note: This is an unsafe fix and may change runtime behavior B905 [*] `zip()` without an explicit `strict=` parameter @@ -68,11 +59,8 @@ B905 [*] `zip()` without an explicit `strict=` parameter | help: Add explicit value for parameter `strict=` | -6 | zip(zip("a", "b"), strict=False) - - zip(zip("a", strict=True),"b") -7 + zip(zip("a", strict=True),"b", strict=False) -8 | - | +7 | zip(zip("a", strict=True),"b", strict=False) + | ++++++++++++++ note: This is an unsafe fix and may change runtime behavior B905 [*] `zip()` without an explicit `strict=` parameter @@ -85,11 +73,8 @@ B905 [*] `zip()` without an explicit `strict=` parameter | help: Add explicit value for parameter `strict=` | -21 | # Errors (limited iterators). - - zip([1, 2, 3], repeat(1, 1)) -22 + zip([1, 2, 3], repeat(1, 1), strict=False) -23 | zip([1, 2, 3], repeat(1, times=4)) - | +22 | zip([1, 2, 3], repeat(1, 1), strict=False) + | ++++++++++++++ note: This is an unsafe fix and may change runtime behavior B905 [*] `zip()` without an explicit `strict=` parameter @@ -104,11 +89,8 @@ B905 [*] `zip()` without an explicit `strict=` parameter | help: Add explicit value for parameter `strict=` | -22 | zip([1, 2, 3], repeat(1, 1)) - - zip([1, 2, 3], repeat(1, times=4)) -23 + zip([1, 2, 3], repeat(1, times=4), strict=False) -24 | - | +23 | zip([1, 2, 3], repeat(1, times=4), strict=False) + | ++++++++++++++ note: This is an unsafe fix and may change runtime behavior B905 [*] `zip()` without an explicit `strict=` parameter @@ -120,8 +102,6 @@ B905 [*] `zip()` without an explicit `strict=` parameter | ^^^^^^^^^^^^^^^^^^^^^^ help: Add explicit value for parameter `strict=` | -33 | # Error - - zip(*lot_of_iterators) -34 + zip(*lot_of_iterators, strict=False) - | +34 | zip(*lot_of_iterators, strict=False) + | ++++++++++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B912_B912.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B912_B912.py.snap index 2adef201a2e60..6b2782b96093a 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B912_B912.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B912_B912.py.snap @@ -13,11 +13,8 @@ B912 [*] `map()` without an explicit `strict=` parameter | help: Add explicit value for parameter `strict=` | -4 | map(lambda x: x, [1, 2, 3]) - - map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6]) -5 + map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6], strict=False) -6 | map(lambda x, y, z: x + y + z, [1, 2, 3], [4, 5, 6], [7, 8, 9]) - | +5 | map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6], strict=False) + | ++++++++++++++ note: This is an unsafe fix and may change runtime behavior B912 [*] `map()` without an explicit `strict=` parameter @@ -32,11 +29,8 @@ B912 [*] `map()` without an explicit `strict=` parameter | help: Add explicit value for parameter `strict=` | -5 | map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6]) - - map(lambda x, y, z: x + y + z, [1, 2, 3], [4, 5, 6], [7, 8, 9]) -6 + map(lambda x, y, z: x + y + z, [1, 2, 3], [4, 5, 6], [7, 8, 9], strict=False) -7 | map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6], *map(lambda x: x, [7, 8, 9])) - | +6 | map(lambda x, y, z: x + y + z, [1, 2, 3], [4, 5, 6], [7, 8, 9], strict=False) + | ++++++++++++++ note: This is an unsafe fix and may change runtime behavior B912 [*] `map()` without an explicit `strict=` parameter @@ -51,12 +45,8 @@ B912 [*] `map()` without an explicit `strict=` parameter | help: Add explicit value for parameter `strict=` | -6 | map(lambda x, y, z: x + y + z, [1, 2, 3], [4, 5, 6], [7, 8, 9]) - - map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6], *map(lambda x: x, [7, 8, 9])) 7 | map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6], *map(lambda x: x, [7, 8, 9]), strict=False) -8 + map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6], *map(lambda x: x, [7, 8, 9]), strict=False) -9 | map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6], *map(lambda x: x, [7, 8, 9], strict=True)) - | + | ++++++++++++++ note: This is an unsafe fix and may change runtime behavior B912 [*] `map()` without an explicit `strict=` parameter @@ -70,12 +60,9 @@ B912 [*] `map()` without an explicit `strict=` parameter 11 | # Errors (limited iterators). | help: Add explicit value for parameter `strict=` - | -8 | map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6], *map(lambda x: x, [7, 8, 9]), strict=False) - - map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6], *map(lambda x: x, [7, 8, 9], strict=True)) -9 + map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6], *map(lambda x: x, [7, 8, 9], strict=True), strict=False) -10 | - | + | +9 | map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6], *map(lambda x: x, [7, 8, 9], strict=True), strict=False) + | ++++++++++++++ note: This is an unsafe fix and may change runtime behavior B912 [*] `map()` without an explicit `strict=` parameter @@ -88,11 +75,8 @@ B912 [*] `map()` without an explicit `strict=` parameter | help: Add explicit value for parameter `strict=` | -11 | # Errors (limited iterators). - - map(lambda x, y: x + y, [1, 2, 3], repeat(1, 1)) -12 + map(lambda x, y: x + y, [1, 2, 3], repeat(1, 1), strict=False) -13 | map(lambda x, y: x + y, [1, 2, 3], repeat(1, times=4)) - | +12 | map(lambda x, y: x + y, [1, 2, 3], repeat(1, 1), strict=False) + | ++++++++++++++ note: This is an unsafe fix and may change runtime behavior B912 [*] `map()` without an explicit `strict=` parameter @@ -107,11 +91,8 @@ B912 [*] `map()` without an explicit `strict=` parameter | help: Add explicit value for parameter `strict=` | -12 | map(lambda x, y: x + y, [1, 2, 3], repeat(1, 1)) - - map(lambda x, y: x + y, [1, 2, 3], repeat(1, times=4)) -13 + map(lambda x, y: x + y, [1, 2, 3], repeat(1, times=4), strict=False) -14 | - | +13 | map(lambda x, y: x + y, [1, 2, 3], repeat(1, times=4), strict=False) + | ++++++++++++++ note: This is an unsafe fix and may change runtime behavior B912 [*] `map()` without an explicit `strict=` parameter @@ -126,11 +107,8 @@ B912 [*] `map()` without an explicit `strict=` parameter | help: Add explicit value for parameter `strict=` | -16 | # Still an error even though it uses the qualified name - - builtins.map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6]) -17 + builtins.map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6], strict=False) -18 | - | +17 | builtins.map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6], strict=False) + | ++++++++++++++ note: This is an unsafe fix and may change runtime behavior B912 [*] `map()` without an explicit `strict=` parameter @@ -141,8 +119,6 @@ B912 [*] `map()` without an explicit `strict=` parameter | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add explicit value for parameter `strict=` | -35 | # Regression https://github.com/astral-sh/ruff/issues/20997 - - map(f, *lots_of_iterators) -36 + map(f, *lots_of_iterators, strict=False) - | +36 | map(f, *lots_of_iterators, strict=False) + | ++++++++++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__extend_immutable_calls_arg_annotation.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__extend_immutable_calls_arg_annotation.snap index 0aa542a980022..074f0a96c5bf7 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__extend_immutable_calls_arg_annotation.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__extend_immutable_calls_arg_annotation.snap @@ -10,9 +10,7 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -16 | - - def error_due_to_missing_import(foo: ImmutableTypeA = []): +17 - def error_due_to_missing_import(foo: ImmutableTypeA = []): 17 + def error_due_to_missing_import(foo: ImmutableTypeA = None): -18 | ... | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_1.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_1.py.snap index fccb6abb9f666..2d95490128323 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_1.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_1.py.snap @@ -13,9 +13,7 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -2 | - - def foobar(foor, bar={}): +3 - def foobar(foor, bar={}): 3 + def foobar(foor, bar=None): -4 | """ | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_2.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_2.py.snap index cf7ea3a24b68d..048e7c94f0247 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_2.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_2.py.snap @@ -13,9 +13,7 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -3 | - - def foobar(foor, bar={}): +4 - def foobar(foor, bar={}): 4 + def foobar(foor, bar=None): -5 | """ | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_3.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_3.py.snap index 2a25950871d8a..8eac5262c88f7 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_3.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_3.py.snap @@ -11,9 +11,7 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -3 | - - def foobar(foor, bar={}): +4 - def foobar(foor, bar={}): 4 + def foobar(foor, bar=None): -5 | """ | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_4.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_4.py.snap index 33bd877748659..d035e7d3be6db 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_4.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_4.py.snap @@ -10,12 +10,9 @@ B006 [*] Do not use mutable data structures for argument defaults 8 | print(a) | help: Replace with `None`; initialize within function - | -6 | class FormFeedIndent: - - def __init__(self, a=[]): -7 + def __init__(self, a=None): -8 + if a is None: -9 + a = [] -10 | print(a) - | + | +7 ~ ␌ def __init__(self, a=None): +8 + if a is None: +9 + a = [] + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_5.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_5.py.snap index 018c6e39f4e9d..4f997a3af1cd0 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_5.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_5.py.snap @@ -10,13 +10,10 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -4 | - - def import_module_wrong(value: dict[str, str] = {}): -5 + def import_module_wrong(value: dict[str, str] = None): +5 ~ def import_module_wrong(value: dict[str, str] = None): 6 | import os 7 + if value is None: 8 + value = {} -9 | | note: This is an unsafe fix and may change runtime behavior @@ -29,14 +26,11 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -8 | - - def import_module_with_values_wrong(value: dict[str, str] = {}): -9 + def import_module_with_values_wrong(value: dict[str, str] = None): + 9 ~ def import_module_with_values_wrong(value: dict[str, str] = None): 10 | import os 11 | 12 + if value is None: 13 + value = {} -14 | return 2 | note: This is an unsafe fix and may change runtime behavior @@ -50,15 +44,12 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -14 | - - def import_modules_wrong(value: dict[str, str] = {}): -15 + def import_modules_wrong(value: dict[str, str] = None): +15 ~ def import_modules_wrong(value: dict[str, str] = None): 16 | import os 17 | import sys 18 | import itertools 19 + if value is None: 20 + value = {} -21 | | note: This is an unsafe fix and may change runtime behavior @@ -71,13 +62,10 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -20 | - - def from_import_module_wrong(value: dict[str, str] = {}): -21 + def from_import_module_wrong(value: dict[str, str] = None): +21 ~ def from_import_module_wrong(value: dict[str, str] = None): 22 | from os import path 23 + if value is None: 24 + value = {} -25 | | note: This is an unsafe fix and may change runtime behavior @@ -91,14 +79,11 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -24 | - - def from_imports_module_wrong(value: dict[str, str] = {}): -25 + def from_imports_module_wrong(value: dict[str, str] = None): +25 ~ def from_imports_module_wrong(value: dict[str, str] = None): 26 | from os import path 27 | from sys import version_info 28 + if value is None: 29 + value = {} -30 | | note: This is an unsafe fix and may change runtime behavior @@ -112,14 +97,11 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -29 | - - def import_and_from_imports_module_wrong(value: dict[str, str] = {}): -30 + def import_and_from_imports_module_wrong(value: dict[str, str] = None): +30 ~ def import_and_from_imports_module_wrong(value: dict[str, str] = None): 31 | import os 32 | from sys import version_info 33 + if value is None: 34 + value = {} -35 | | note: This is an unsafe fix and may change runtime behavior @@ -133,14 +115,11 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -34 | - - def import_docstring_module_wrong(value: dict[str, str] = {}): -35 + def import_docstring_module_wrong(value: dict[str, str] = None): +35 ~ def import_docstring_module_wrong(value: dict[str, str] = None): 36 | """Docstring""" 37 | import os 38 + if value is None: 39 + value = {} -40 | | note: This is an unsafe fix and may change runtime behavior @@ -154,14 +133,11 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -39 | - - def import_module_wrong(value: dict[str, str] = {}): -40 + def import_module_wrong(value: dict[str, str] = None): +40 ~ def import_module_wrong(value: dict[str, str] = None): 41 | """Docstring""" 42 | import os; import sys 43 + if value is None: 44 + value = {} -45 | | note: This is an unsafe fix and may change runtime behavior @@ -175,13 +151,10 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -44 | - - def import_module_wrong(value: dict[str, str] = {}): -45 + def import_module_wrong(value: dict[str, str] = None): +45 ~ def import_module_wrong(value: dict[str, str] = None): 46 | """Docstring""" 47 + if value is None: 48 + value = {} -49 | import os; import sys; x = 1 | note: This is an unsafe fix and may change runtime behavior @@ -195,14 +168,11 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -49 | - - def import_module_wrong(value: dict[str, str] = {}): -50 + def import_module_wrong(value: dict[str, str] = None): +50 ~ def import_module_wrong(value: dict[str, str] = None): 51 | """Docstring""" 52 | import os; import sys 53 + if value is None: 54 + value = {} -55 | | note: This is an unsafe fix and may change runtime behavior @@ -215,13 +185,10 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -54 | - - def import_module_wrong(value: dict[str, str] = {}): -55 + def import_module_wrong(value: dict[str, str] = None): +55 ~ def import_module_wrong(value: dict[str, str] = None): 56 | import os; import sys 57 + if value is None: 58 + value = {} -59 | | note: This is an unsafe fix and may change runtime behavior @@ -234,12 +201,9 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -58 | - - def import_module_wrong(value: dict[str, str] = {}): -59 + def import_module_wrong(value: dict[str, str] = None): +59 ~ def import_module_wrong(value: dict[str, str] = None): 60 + if value is None: 61 + value = {} -62 | import os; import sys; x = 1 | note: This is an unsafe fix and may change runtime behavior @@ -252,13 +216,10 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -62 | - - def import_module_wrong(value: dict[str, str] = {}): -63 + def import_module_wrong(value: dict[str, str] = None): +63 ~ def import_module_wrong(value: dict[str, str] = None): 64 | import os; import sys 65 + if value is None: 66 + value = {} -67 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_6.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_6.py.snap index dad396ffb92a0..c7a3d4eb287a0 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_6.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_6.py.snap @@ -12,11 +12,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -3 | - - def foobar(foor, bar={}): - - import os -4 + def foobar(foor, bar=None): -5 + import os +4 ~ def foobar(foor, bar=None): +5 ~ import os 6 + if bar is None: 7 + bar = {} | diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_7.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_7.py.snap index c2ce88d513beb..5f45c9253c7da 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_7.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_7.py.snap @@ -12,11 +12,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -3 | - - def foobar(foor, bar={}): - - import os -4 + def foobar(foor, bar=None): -5 + import os +4 ~ def foobar(foor, bar=None): +5 ~ import os 6 + if bar is None: 7 + bar = {} | diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_8.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_8.py.snap index 671b25ae3998d..1b67ad7159b3d 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_8.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_8.py.snap @@ -10,9 +10,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | - - def foo(a: list = []): +1 - def foo(a: list = []): 1 + def foo(a: list = None): -2 | raise NotImplementedError("") | note: This is an unsafe fix and may change runtime behavior @@ -26,10 +25,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -4 | - - def bar(a: dict = {}): +5 - def bar(a: dict = {}): 5 + def bar(a: dict = None): -6 | """ This one also has a docstring""" | note: This is an unsafe fix and may change runtime behavior @@ -43,13 +40,10 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -9 | - - def baz(a: list = []): -10 + def baz(a: list = None): +10 ~ def baz(a: list = None): 11 | """This one raises a different exception""" 12 + if a is None: 13 + a = [] -14 | raise IndexError() | note: This is an unsafe fix and may change runtime behavior @@ -62,10 +56,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -14 | - - def qux(a: list = []): +15 - def qux(a: list = []): 15 + def qux(a: list = None): -16 | raise NotImplementedError | note: This is an unsafe fix and may change runtime behavior @@ -78,9 +70,7 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -18 | - - def quux(a: list = []): +19 - def quux(a: list = []): 19 + def quux(a: list = None): -20 | raise NotImplemented | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_9.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_9.py.snap index 861688fd66562..d5537af5dcff7 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_9.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_9.py.snap @@ -10,11 +10,9 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | - - def f1(x=([],)): -1 + def f1(x=None): +1 ~ def f1(x=None): 2 + if x is None: 3 + x = ([],) -4 | print(x) | note: This is an unsafe fix and may change runtime behavior @@ -27,12 +25,9 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -4 | - - def f2(x=(x for x in "x")): -5 + def f2(x=None): +5 ~ def f2(x=None): 6 + if x is None: 7 + x = (x for x in "x") -8 | print(x) | note: This is an unsafe fix and may change runtime behavior @@ -45,12 +40,9 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -8 | - - def f3(x=((x for x in "x"),)): -9 + def f3(x=None): + 9 ~ def f3(x=None): 10 + if x is None: 11 + x = ((x for x in "x"),) -12 | print(x) | note: This is an unsafe fix and may change runtime behavior @@ -63,12 +55,9 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -12 | - - def f4(x=(z := [1, ])): -13 + def f4(x=None): +13 ~ def f4(x=None): 14 + if x is None: 15 + x = (z := [1, ]) -16 | print(x) | note: This is an unsafe fix and may change runtime behavior @@ -81,11 +70,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -16 | - - def f5(x=([1, ])): -17 + def f5(x=None): +17 ~ def f5(x=None): 18 + if x is None: 19 + x = ([1, ]) -20 | print(x) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_B008.py.snap b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_B008.py.snap index d4e71b5232f58..8e9bd409fcecb 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_B008.py.snap +++ b/crates/ruff_linter/src/rules/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__preview__B006_B006_B008.py.snap @@ -10,10 +10,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -62 | - - def this_is_wrong(value=[1, 2, 3]): +63 - def this_is_wrong(value=[1, 2, 3]): 63 + def this_is_wrong(value=None): -64 | ... | note: This is an unsafe fix and may change runtime behavior @@ -26,10 +24,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -66 | - - def this_is_also_wrong(value={}): +67 - def this_is_also_wrong(value={}): 67 + def this_is_also_wrong(value=None): -68 | ... | note: This is an unsafe fix and may change runtime behavior @@ -44,10 +40,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -72 | @staticmethod - - def this_is_also_wrong_and_more_indented(value={}): +73 - def this_is_also_wrong_and_more_indented(value={}): 73 + def this_is_also_wrong_and_more_indented(value=None): -74 | pass | note: This is an unsafe fix and may change runtime behavior @@ -63,12 +57,10 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -76 | - - def multiline_arg_wrong(value={ - - - - }): +77 - def multiline_arg_wrong(value={ +78 - +79 - }): 77 + def multiline_arg_wrong(value=None): -78 | ... | note: This is an unsafe fix and may change runtime behavior @@ -90,10 +82,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -84 | - - def and_this(value=set()): +85 - def and_this(value=set()): 85 + def and_this(value=None): -86 | ... | note: This is an unsafe fix and may change runtime behavior @@ -106,10 +96,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -88 | - - def this_too(value=collections.OrderedDict()): +89 - def this_too(value=collections.OrderedDict()): 89 + def this_too(value=None): -90 | ... | note: This is an unsafe fix and may change runtime behavior @@ -122,10 +110,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -92 | - - async def async_this_too(value=collections.defaultdict()): +93 - async def async_this_too(value=collections.defaultdict()): 93 + async def async_this_too(value=None): -94 | ... | note: This is an unsafe fix and may change runtime behavior @@ -138,10 +124,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -96 | - - def dont_forget_me(value=collections.deque()): +97 - def dont_forget_me(value=collections.deque()): 97 + def dont_forget_me(value=None): -98 | ... | note: This is an unsafe fix and may change runtime behavior @@ -155,10 +139,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -101 | # B006 still flags mutable comprehension defaults. - - def list_comprehension_also_not_okay(default=[i**2 for i in range(3)]): +102 - def list_comprehension_also_not_okay(default=[i**2 for i in range(3)]): 102 + def list_comprehension_also_not_okay(default=None): -103 | pass | note: This is an unsafe fix and may change runtime behavior @@ -171,10 +153,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -105 | - - def dict_comprehension_also_not_okay(default={i: i**2 for i in range(3)}): +106 - def dict_comprehension_also_not_okay(default={i: i**2 for i in range(3)}): 106 + def dict_comprehension_also_not_okay(default=None): -107 | pass | note: This is an unsafe fix and may change runtime behavior @@ -187,10 +167,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -109 | - - def set_comprehension_also_not_okay(default={i**2 for i in range(3)}): +110 - def set_comprehension_also_not_okay(default={i**2 for i in range(3)}): 110 + def set_comprehension_also_not_okay(default=None): -111 | pass | note: This is an unsafe fix and may change runtime behavior @@ -203,10 +181,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -113 | - - def kwonlyargs_mutable(*, value=[]): +114 - def kwonlyargs_mutable(*, value=[]): 114 + def kwonlyargs_mutable(*, value=None): -115 | ... | note: This is an unsafe fix and may change runtime behavior @@ -221,10 +197,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -241 | # We should handle arbitrary nesting of these B008. - - def nested_combo(a=[float(3), dt.datetime.now()]): +242 - def nested_combo(a=[float(3), dt.datetime.now()]): 242 + def nested_combo(a=None): -243 | pass | note: This is an unsafe fix and may change runtime behavior @@ -239,10 +213,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -278 | def mutable_annotations( - - a: list[int] | None = [], +279 - a: list[int] | None = [], 279 + a: list[int] | None = None, -280 | b: Optional[Dict[int, int]] = {}, | note: This is an unsafe fix and may change runtime behavior @@ -258,10 +230,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -279 | a: list[int] | None = [], - - b: Optional[Dict[int, int]] = {}, +280 - b: Optional[Dict[int, int]] = {}, 280 + b: Optional[Dict[int, int]] = None, -281 | c: Annotated[Union[Set[str], abc.Sized], "annotation"] = set(), | note: This is an unsafe fix and may change runtime behavior @@ -277,10 +247,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -280 | b: Optional[Dict[int, int]] = {}, - - c: Annotated[Union[Set[str], abc.Sized], "annotation"] = set(), +281 - c: Annotated[Union[Set[str], abc.Sized], "annotation"] = set(), 281 + c: Annotated[Union[Set[str], abc.Sized], "annotation"] = None, -282 | d: typing_extensions.Annotated[Union[Set[str], abc.Sized], "annotation"] = set(), | note: This is an unsafe fix and may change runtime behavior @@ -296,10 +264,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -281 | c: Annotated[Union[Set[str], abc.Sized], "annotation"] = set(), - - d: typing_extensions.Annotated[Union[Set[str], abc.Sized], "annotation"] = set(), +282 - d: typing_extensions.Annotated[Union[Set[str], abc.Sized], "annotation"] = set(), 282 + d: typing_extensions.Annotated[Union[Set[str], abc.Sized], "annotation"] = None, -283 | ): | note: This is an unsafe fix and may change runtime behavior @@ -312,10 +278,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -286 | - - def single_line_func_wrong(value: dict[str, str] = {}): +287 - def single_line_func_wrong(value: dict[str, str] = {}): 287 + def single_line_func_wrong(value: dict[str, str] = None): -288 | """Docstring""" | note: This is an unsafe fix and may change runtime behavior @@ -329,10 +293,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -290 | - - def single_line_func_wrong(value: dict[str, str] = {}): +291 - def single_line_func_wrong(value: dict[str, str] = {}): 291 + def single_line_func_wrong(value: dict[str, str] = None): -292 | """Docstring""" | note: This is an unsafe fix and may change runtime behavior @@ -345,10 +307,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -295 | - - def single_line_func_wrong(value: dict[str, str] = {}): +296 - def single_line_func_wrong(value: dict[str, str] = {}): 296 + def single_line_func_wrong(value: dict[str, str] = None): -297 | """Docstring"""; ... | note: This is an unsafe fix and may change runtime behavior @@ -362,10 +322,8 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -299 | - - def single_line_func_wrong(value: dict[str, str] = {}): +300 - def single_line_func_wrong(value: dict[str, str] = {}): 300 + def single_line_func_wrong(value: dict[str, str] = None): -301 | """Docstring"""; \ | note: This is an unsafe fix and may change runtime behavior @@ -381,12 +339,10 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -304 | - - def single_line_func_wrong(value: dict[str, str] = { - - # This is a comment - - }): +305 - def single_line_func_wrong(value: dict[str, str] = { +306 - # This is a comment +307 - }): 305 + def single_line_func_wrong(value: dict[str, str] = None): -306 | """Docstring""" | note: This is an unsafe fix and may change runtime behavior @@ -409,9 +365,7 @@ B006 [*] Do not use mutable data structures for argument defaults | help: Replace with `None`; initialize within function | -315 | - - def single_line_func_wrong(value: dict[str, str] = {}): +316 - def single_line_func_wrong(value: dict[str, str] = {}): 316 + def single_line_func_wrong(value: dict[str, str] = None): -317 | """Docstring without newline""" | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_commas/snapshots/ruff_linter__rules__flake8_commas__tests__COM81.py.snap b/crates/ruff_linter/src/rules/flake8_commas/snapshots/ruff_linter__rules__flake8_commas__tests__COM81.py.snap index dab988936c0af..116171563d556 100644 --- a/crates/ruff_linter/src/rules/flake8_commas/snapshots/ruff_linter__rules__flake8_commas__tests__COM81.py.snap +++ b/crates/ruff_linter/src/rules/flake8_commas/snapshots/ruff_linter__rules__flake8_commas__tests__COM81.py.snap @@ -13,11 +13,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -3 | param1='test', - - param2='test' -4 + param2='test', -5 | ) - | +4 | param2='test', + | + COM812 [*] Trailing comma missing --> COM81.py:10:6 @@ -30,11 +27,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -9 | 2, - - 3 -10 + 3, -11 | ] - | +10 | 3, + | + COM812 [*] Trailing comma missing --> COM81.py:16:6 @@ -48,11 +42,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -15 | 2, - - 3 -16 + 3, -17 | # still needs a comma! - | +16 | 3, + | + COM812 [*] Trailing comma missing --> COM81.py:23:6 @@ -63,11 +54,8 @@ COM812 [*] Trailing comma missing | ^ help: Add trailing comma | -22 | 2, - - 3 -23 + 3, -24 | - | +23 | 3, + | + COM818 Trailing comma on bare tuple prohibited --> COM81.py:36:8 @@ -154,11 +142,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -69 | {'foo': foo}['foo']( - - bar -70 + bar, -71 | ) - | +70 | bar, + | + COM812 [*] Trailing comma missing --> COM81.py:78:8 @@ -170,11 +155,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -77 | (foo)( - - bar -78 + bar, -79 | ) - | +78 | bar, + | + COM812 [*] Trailing comma missing --> COM81.py:86:8 @@ -186,11 +168,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -85 | [foo][0]( - - bar -86 + bar, -87 | ) - | +86 | bar, + | + COM812 [*] Trailing comma missing --> COM81.py:152:6 @@ -203,11 +182,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -151 | from x import ( - - y -152 + y, -153 | ) - | +152 | y, + | + COM812 [*] Trailing comma missing --> COM81.py:158:11 @@ -220,11 +196,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -157 | ThrownHere, - - Anyway -158 + Anyway, -159 | ) - | +158 | Anyway, + | + COM812 [*] Trailing comma missing --> COM81.py:293:15 @@ -238,11 +211,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -292 | multiline_bad_dict = { - - "bad": 123 -293 + "bad": 123, -294 | } - | +293 | "bad": 123, + | + COM812 [*] Trailing comma missing --> COM81.py:304:14 @@ -256,11 +226,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -303 | a = 3, - - b = 2 -304 + b = 2, -305 | ): - | +304 | b = 2, + | + COM812 [*] Trailing comma missing --> COM81.py:310:14 @@ -274,11 +241,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -309 | def func( - - a = 3 -310 + a = 3, -311 | ): - | +310 | a = 3, + | + COM812 [*] Trailing comma missing --> COM81.py:316:10 @@ -290,11 +254,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -315 | func( - - a = 3 -316 + a = 3, -317 | ) - | +316 | a = 3, + | + COM812 [*] Trailing comma missing --> COM81.py:322:15 @@ -307,11 +268,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -321 | "good": True or False, - - "bad": 123 -322 + "bad": 123, -323 | } - | +322 | "bad": 123, + | + COM812 [*] Trailing comma missing --> COM81.py:368:15 @@ -324,11 +282,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -367 | "probably fine", - - "not good" -368 + "not good", -369 | ] - | +368 | "not good", + | + COM812 [*] Trailing comma missing --> COM81.py:375:15 @@ -341,11 +296,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -374 | : - - "not good" -375 + "not good", -376 | ] - | +375 | "not good", + | + COM812 [*] Trailing comma missing --> COM81.py:404:15 @@ -358,11 +310,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -403 | : - - "not fine" -404 + "not fine", -405 | ] - | +404 | "not fine", + | + COM812 [*] Trailing comma missing --> COM81.py:432:15 @@ -375,11 +324,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -431 | "fine", - - "not fine" -432 + "not fine", -433 | ] - | +432 | "not fine", + | + COM819 [*] Trailing comma prohibited --> COM81.py:485:21 @@ -392,10 +338,8 @@ COM819 [*] Trailing comma prohibited | help: Remove trailing comma | -484 | # ==> prohibited.py <== - - foo = ['a', 'b', 'c',] +485 - foo = ['a', 'b', 'c',] 485 + foo = ['a', 'b', 'c'] -486 | | COM819 [*] Trailing comma prohibited @@ -410,10 +354,8 @@ COM819 [*] Trailing comma prohibited | help: Remove trailing comma | -486 | - - bar = { a: b,} +487 - bar = { a: b,} 487 + bar = { a: b} -488 | | COM819 [*] Trailing comma prohibited @@ -427,10 +369,8 @@ COM819 [*] Trailing comma prohibited | help: Remove trailing comma | -488 | - - def bah(ham, spam,): +489 - def bah(ham, spam,): 489 + def bah(ham, spam): -490 | pass | COM819 [*] Trailing comma prohibited @@ -445,10 +385,8 @@ COM819 [*] Trailing comma prohibited | help: Remove trailing comma | -493 | - - (0, 1,) +494 - (0, 1,) 494 + (0, 1) -495 | | COM819 [*] Trailing comma prohibited @@ -463,10 +401,8 @@ COM819 [*] Trailing comma prohibited | help: Remove trailing comma | -495 | - - foo = ['a', 'b', 'c', ] +496 - foo = ['a', 'b', 'c', ] 496 + foo = ['a', 'b', 'c' ] -497 | | COM819 [*] Trailing comma prohibited @@ -481,10 +417,8 @@ COM819 [*] Trailing comma prohibited | help: Remove trailing comma | -497 | - - bar = { a: b, } +498 - bar = { a: b, } 498 + bar = { a: b } -499 | | COM819 [*] Trailing comma prohibited @@ -498,10 +432,8 @@ COM819 [*] Trailing comma prohibited | help: Remove trailing comma | -499 | - - def bah(ham, spam, ): +500 - def bah(ham, spam, ): 500 + def bah(ham, spam ): -501 | pass | COM819 [*] Trailing comma prohibited @@ -516,10 +448,8 @@ COM819 [*] Trailing comma prohibited | help: Remove trailing comma | -504 | - - (0, 1, ) +505 - (0, 1, ) 505 + (0, 1 ) -506 | | COM819 [*] Trailing comma prohibited @@ -534,10 +464,8 @@ COM819 [*] Trailing comma prohibited | help: Remove trailing comma | -510 | - - image[:,:,] +511 - image[:,:,] 511 + image[:,:] -512 | | COM819 [*] Trailing comma prohibited @@ -552,10 +480,8 @@ COM819 [*] Trailing comma prohibited | help: Remove trailing comma | -512 | - - lambda x, : x +513 - lambda x, : x 513 + lambda x : x -514 | | COM812 [*] Trailing comma missing @@ -570,11 +496,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -518 | bar, - - **kwargs -519 + **kwargs, -520 | ): - | +519 | **kwargs, + | + COM812 [*] Trailing comma missing --> COM81.py:526:10 @@ -588,11 +511,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -525 | bar, - - *args -526 + *args, -527 | ): - | +526 | *args, + | + COM812 [*] Trailing comma missing --> COM81.py:534:16 @@ -606,11 +526,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -533 | *args, - - extra_kwarg -534 + extra_kwarg, -535 | ): - | +534 | extra_kwarg, + | + COM812 [*] Trailing comma missing --> COM81.py:541:13 @@ -623,11 +540,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -540 | bar, - - **kwargs -541 + **kwargs, -542 | ) - | +541 | **kwargs, + | + COM812 [*] Trailing comma missing --> COM81.py:547:24 @@ -640,11 +554,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -546 | bar, - - **not_called_kwargs -547 + **not_called_kwargs, -548 | ) - | +547 | **not_called_kwargs, + | + COM812 [*] Trailing comma missing --> COM81.py:554:15 @@ -658,11 +569,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -553 | *args, - - kwarg_only -554 + kwarg_only, -555 | ): - | +554 | kwarg_only, + | + COM812 [*] Trailing comma missing --> COM81.py:561:13 @@ -674,11 +582,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -560 | foo( - - **kwargs -561 + **kwargs, -562 | ) - | +561 | **kwargs, + | + COM812 [*] Trailing comma missing --> COM81.py:565:13 @@ -690,11 +595,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -564 | { - - **kwargs -565 + **kwargs, -566 | } - | +565 | **kwargs, + | + COM812 [*] Trailing comma missing --> COM81.py:569:10 @@ -706,11 +608,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -568 | { - - *args -569 + *args, -570 | } - | +569 | *args, + | + COM812 [*] Trailing comma missing --> COM81.py:573:10 @@ -722,11 +621,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -572 | [ - - *args -573 + *args, -574 | ] - | +573 | *args, + | + COM812 [*] Trailing comma missing --> COM81.py:579:10 @@ -740,11 +636,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -578 | spam, - - *args -579 + *args, -580 | ): - | +579 | *args, + | + COM812 [*] Trailing comma missing --> COM81.py:586:13 @@ -758,11 +651,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -585 | spam, - - **kwargs -586 + **kwargs, -587 | ): - | +586 | **kwargs, + | + COM812 [*] Trailing comma missing --> COM81.py:594:15 @@ -776,11 +666,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -593 | *args, - - kwarg_only -594 + kwarg_only, -595 | ): - | +594 | kwarg_only, + | + COM812 [*] Trailing comma missing --> COM81.py:623:20 @@ -793,11 +680,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -622 | bar, - - **{'ham': spam} -623 + **{'ham': spam}, -624 | ) - | +623 | **{'ham': spam}, + | + COM812 [*] Trailing comma missing --> COM81.py:628:42 @@ -810,11 +694,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -627 | the_first_one = next( - - (i for i in range(10) if i // 2 == 0) # COM812 fix should include the final bracket -628 + (i for i in range(10) if i // 2 == 0), # COM812 fix should include the final bracket -629 | ) - | +628 | (i for i in range(10) if i // 2 == 0), # COM812 fix should include the final bracket + | + COM819 [*] Trailing comma prohibited --> COM81.py:640:46 @@ -827,10 +708,8 @@ COM819 [*] Trailing comma prohibited | help: Remove trailing comma | -639 | # F-strings - - kwargs.pop("remove", f"this {trailing_comma}",) +640 - kwargs.pop("remove", f"this {trailing_comma}",) 640 + kwargs.pop("remove", f"this {trailing_comma}") -641 | | COM812 [*] Trailing comma missing @@ -843,11 +722,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -642 | raise Exception( - - "first", extra=f"Add trailing comma here ->" -643 + "first", extra=f"Add trailing comma here ->", -644 | ) - | +643 | "first", extra=f"Add trailing comma here ->", + | + COM812 [*] Trailing comma missing --> COM81.py:655:6 @@ -860,11 +736,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -654 | type X[ - - T -655 + T, -656 | ] = T - | +655 | T, + | + COM812 [*] Trailing comma missing --> COM81.py:658:6 @@ -878,11 +751,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -657 | def f[ - - T -658 + T, -659 | ](): pass - | +658 | T, + | + COM812 [*] Trailing comma missing --> COM81.py:661:6 @@ -895,11 +765,8 @@ COM812 [*] Trailing comma missing | help: Add trailing comma | -660 | class C[ - - T -661 + T, -662 | ]: pass - | +661 | T, + | + COM819 [*] Trailing comma prohibited --> COM81.py:664:9 @@ -913,10 +780,8 @@ COM819 [*] Trailing comma prohibited | help: Remove trailing comma | -663 | - - type X[T,] = T +664 - type X[T,] = T 664 + type X[T] = T -665 | def f[T,](): pass | COM819 [*] Trailing comma prohibited @@ -929,10 +794,8 @@ COM819 [*] Trailing comma prohibited | help: Remove trailing comma | -664 | type X[T,] = T - - def f[T,](): pass +665 - def f[T,](): pass 665 + def f[T](): pass -666 | class C[T,]: pass | COM819 [*] Trailing comma prohibited @@ -947,10 +810,8 @@ COM819 [*] Trailing comma prohibited | help: Remove trailing comma | -665 | def f[T,](): pass - - class C[T,]: pass +666 - class C[T,]: pass 666 + class C[T]: pass -667 | | COM819 [*] Trailing comma prohibited @@ -963,10 +824,8 @@ COM819 [*] Trailing comma prohibited | help: Remove trailing comma | -668 | # t-string examples - - kwargs.pop("remove", t"this {trailing_comma}",) +669 - kwargs.pop("remove", t"this {trailing_comma}",) 669 + kwargs.pop("remove", t"this {trailing_comma}") -670 | kwargs.pop("remove", t"this {f"{trailing_comma}"}",) | COM819 [*] Trailing comma prohibited @@ -981,8 +840,6 @@ COM819 [*] Trailing comma prohibited | help: Remove trailing comma | -669 | kwargs.pop("remove", t"this {trailing_comma}",) - - kwargs.pop("remove", t"this {f"{trailing_comma}"}",) +670 - kwargs.pop("remove", t"this {f"{trailing_comma}"}",) 670 + kwargs.pop("remove", t"this {f"{trailing_comma}"}") -671 | | diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C400_C400.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C400_C400.py.snap index 702b707c455e9..fb597c8044ab4 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C400_C400.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C400_C400.py.snap @@ -12,10 +12,8 @@ C400 [*] Unnecessary generator (rewrite as a list comprehension) | help: Rewrite as a list comprehension | -1 | # Cannot combine with C416. Should use list comprehension here. - - even_nums = list(2 * x for x in range(3)) +2 - even_nums = list(2 * x for x in range(3)) 2 + even_nums = [2 * x for x in range(3)] -3 | odd_nums = list( | note: This is an unsafe fix and may change runtime behavior @@ -31,13 +29,9 @@ C400 [*] Unnecessary generator (rewrite as a list comprehension) | |_^ help: Rewrite as a list comprehension | -2 | even_nums = list(2 * x for x in range(3)) - - odd_nums = list( -3 + odd_nums = [ +3 ~ odd_nums = [ 4 | 2 * x + 1 for x in range(3) - - ) 5 + ] -6 | | note: This is an unsafe fix and may change runtime behavior @@ -51,12 +45,10 @@ C400 [*] Unnecessary generator (rewrite using `list()`) 11 | x for x in range(3) | help: Rewrite using `list()` - | -8 | # Short-circuit case, combine with C416 and should produce x = list(range(3)) - - x = list(x for x in range(3)) -9 + x = list(range(3)) -10 | x = list( - | + | +9 - x = list(x for x in range(3)) +9 + x = list(range(3)) + | note: This is an unsafe fix and may change runtime behavior C400 [*] Unnecessary generator (rewrite using `list()`) @@ -74,12 +66,10 @@ C400 [*] Unnecessary generator (rewrite using `list()`) | help: Rewrite using `list()` | -9 | x = list(x for x in range(3)) - - x = list( - - x for x in range(3) - - ) +10 - x = list( +11 - x for x in range(3) +12 - ) 10 + x = list(range(3)) -11 | | note: This is an unsafe fix and may change runtime behavior @@ -94,10 +84,8 @@ C400 [*] Unnecessary generator (rewrite as a list comprehension) | help: Rewrite as a list comprehension | -14 | # Strip parentheses from inner generators. - - list((2 * x for x in range(3))) +15 - list((2 * x for x in range(3))) 15 + [2 * x for x in range(3)] -16 | list(((2 * x for x in range(3)))) | note: This is an unsafe fix and may change runtime behavior @@ -112,10 +100,8 @@ C400 [*] Unnecessary generator (rewrite as a list comprehension) | help: Rewrite as a list comprehension | -15 | list((2 * x for x in range(3))) - - list(((2 * x for x in range(3)))) +16 - list(((2 * x for x in range(3)))) 16 + [2 * x for x in range(3)] -17 | list((((2 * x for x in range(3))))) | note: This is an unsafe fix and may change runtime behavior @@ -131,10 +117,8 @@ C400 [*] Unnecessary generator (rewrite as a list comprehension) | help: Rewrite as a list comprehension | -16 | list(((2 * x for x in range(3)))) - - list((((2 * x for x in range(3))))) +17 - list((((2 * x for x in range(3))))) 17 + [2 * x for x in range(3)] -18 | | note: This is an unsafe fix and may change runtime behavior @@ -150,10 +134,8 @@ C400 [*] Unnecessary generator (rewrite as a list comprehension) | help: Rewrite as a list comprehension | -20 | # See https://github.com/astral-sh/ruff/issues/15852 - - list((0 for _ in []),) +21 - list((0 for _ in []),) 21 + [0 for _ in []] -22 | list( | note: This is an unsafe fix and may change runtime behavior @@ -171,16 +153,9 @@ C400 [*] Unnecessary generator (rewrite as a list comprehension) | |__^ help: Rewrite as a list comprehension | -21 | list((0 for _ in []),) - - list( - - (0 for _ in []) 22 + [ -23 + 0 for _ in [] +23 ~ 0 for _ in [] 24 | # some comments - - , - - # some more - - ) -25 + ] -26 | +25 ~ ] | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C400_C400_py315.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C400_C400_py315.py.snap index b3f136505c18f..4585f764ad1b9 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C400_C400_py315.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C400_C400_py315.py.snap @@ -10,8 +10,7 @@ C400 [*] Unnecessary generator (rewrite as a list comprehension) | ^^^^^^^^^^^^^^^^^^^^ help: Rewrite as a list comprehension | -2 | - - list(*x for x in xs) +3 - list(*x for x in xs) 3 + [*x for x in xs] | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C401_C401.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C401_C401.py.snap index 28dffa3bc545f..0e17df4ce68dd 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C401_C401.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C401_C401.py.snap @@ -12,10 +12,8 @@ C401 [*] Unnecessary generator (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -1 | # Cannot combine with C416. Should use set comprehension here. - - even_nums = set(2 * x for x in range(3)) +2 - even_nums = set(2 * x for x in range(3)) 2 + even_nums = {2 * x for x in range(3)} -3 | odd_nums = set( | note: This is an unsafe fix and may change runtime behavior @@ -33,13 +31,9 @@ C401 [*] Unnecessary generator (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -2 | even_nums = set(2 * x for x in range(3)) - - odd_nums = set( -3 + odd_nums = { +3 ~ odd_nums = { 4 | 2 * x + 1 for x in range(3) - - ) 5 + } -6 | small_nums = f"{set(a if a < 6 else 0 for a in range(3))}" | note: This is an unsafe fix and may change runtime behavior @@ -55,10 +49,8 @@ C401 [*] Unnecessary generator (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -5 | ) - - small_nums = f"{set(a if a < 6 else 0 for a in range(3))}" +6 - small_nums = f"{set(a if a < 6 else 0 for a in range(3))}" 6 + small_nums = f"{ {a if a < 6 else 0 for a in range(3)} }" -7 | | note: This is an unsafe fix and may change runtime behavior @@ -73,10 +65,8 @@ C401 [*] Unnecessary generator (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -10 | - - print(f"Hello {set(f(a) for a in 'abc')} World") +11 - print(f"Hello {set(f(a) for a in 'abc')} World") 11 + print(f"Hello { {f(a) for a in 'abc'} } World") -12 | print(f"Hello { set(f(a) for a in 'abc') } World") | note: This is an unsafe fix and may change runtime behavior @@ -88,10 +78,8 @@ C401 [*] Unnecessary generator (rewrite as a set comprehension) | ^^^^^^^^^^^^^^^^^^^^^^^^ help: Rewrite as a set comprehension | -11 | print(f"Hello {set(f(a) for a in 'abc')} World") - - print(f"Hello { set(f(a) for a in 'abc') } World") +12 - print(f"Hello { set(f(a) for a in 'abc') } World") 12 + print(f"Hello { {f(a) for a in 'abc'} } World") -13 | | note: This is an unsafe fix and may change runtime behavior @@ -106,10 +94,8 @@ C401 [*] Unnecessary generator (rewrite using `set()`) | help: Rewrite using `set()` | -15 | # Short-circuit case, combine with C416 and should produce x = set(range(3)) - - x = set(x for x in range(3)) +16 - x = set(x for x in range(3)) 16 + x = set(range(3)) -17 | x = set( | note: This is an unsafe fix and may change runtime behavior @@ -128,12 +114,10 @@ C401 [*] Unnecessary generator (rewrite using `set()`) | help: Rewrite using `set()` | -16 | x = set(x for x in range(3)) - - x = set( - - x for x in range(3) - - ) +17 - x = set( +18 - x for x in range(3) +19 - ) 17 + x = set(range(3)) -18 | print(f"Hello {set(a for a in range(3))} World") | note: This is an unsafe fix and may change runtime behavior @@ -149,10 +133,8 @@ C401 [*] Unnecessary generator (rewrite using `set()`) | help: Rewrite using `set()` | -19 | ) - - print(f"Hello {set(a for a in range(3))} World") +20 - print(f"Hello {set(a for a in range(3))} World") 20 + print(f"Hello {set(range(3))} World") -21 | print(f"{set(a for a in 'abc') - set(a for a in 'ab')}") | note: This is an unsafe fix and may change runtime behavior @@ -167,10 +149,8 @@ C401 [*] Unnecessary generator (rewrite using `set()`) | help: Rewrite using `set()` | -20 | print(f"Hello {set(a for a in range(3))} World") - - print(f"{set(a for a in 'abc') - set(a for a in 'ab')}") +21 - print(f"{set(a for a in 'abc') - set(a for a in 'ab')}") 21 + print(f"{set('abc') - set(a for a in 'ab')}") -22 | print(f"{ set(a for a in 'abc') - set(a for a in 'ab') }") | note: This is an unsafe fix and may change runtime behavior @@ -185,10 +165,8 @@ C401 [*] Unnecessary generator (rewrite using `set()`) | help: Rewrite using `set()` | -20 | print(f"Hello {set(a for a in range(3))} World") - - print(f"{set(a for a in 'abc') - set(a for a in 'ab')}") +21 - print(f"{set(a for a in 'abc') - set(a for a in 'ab')}") 21 + print(f"{set(a for a in 'abc') - set('ab')}") -22 | print(f"{ set(a for a in 'abc') - set(a for a in 'ab') }") | note: This is an unsafe fix and may change runtime behavior @@ -204,10 +182,8 @@ C401 [*] Unnecessary generator (rewrite using `set()`) | help: Rewrite using `set()` | -21 | print(f"{set(a for a in 'abc') - set(a for a in 'ab')}") - - print(f"{ set(a for a in 'abc') - set(a for a in 'ab') }") +22 - print(f"{ set(a for a in 'abc') - set(a for a in 'ab') }") 22 + print(f"{ set('abc') - set(a for a in 'ab') }") -23 | | note: This is an unsafe fix and may change runtime behavior @@ -223,10 +199,8 @@ C401 [*] Unnecessary generator (rewrite using `set()`) | help: Rewrite using `set()` | -21 | print(f"{set(a for a in 'abc') - set(a for a in 'ab')}") - - print(f"{ set(a for a in 'abc') - set(a for a in 'ab') }") +22 - print(f"{ set(a for a in 'abc') - set(a for a in 'ab') }") 22 + print(f"{ set(a for a in 'abc') - set('ab') }") -23 | | note: This is an unsafe fix and may change runtime behavior @@ -241,10 +215,8 @@ C401 [*] Unnecessary generator (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -24 | # Strip parentheses from inner generators. - - set((2 * x for x in range(3))) +25 - set((2 * x for x in range(3))) 25 + {2 * x for x in range(3)} -26 | set(((2 * x for x in range(3)))) | note: This is an unsafe fix and may change runtime behavior @@ -259,10 +231,8 @@ C401 [*] Unnecessary generator (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -25 | set((2 * x for x in range(3))) - - set(((2 * x for x in range(3)))) +26 - set(((2 * x for x in range(3)))) 26 + {2 * x for x in range(3)} -27 | set((((2 * x for x in range(3))))) | note: This is an unsafe fix and may change runtime behavior @@ -278,10 +248,8 @@ C401 [*] Unnecessary generator (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -26 | set(((2 * x for x in range(3)))) - - set((((2 * x for x in range(3))))) +27 - set((((2 * x for x in range(3))))) 27 + {2 * x for x in range(3)} -28 | | note: This is an unsafe fix and may change runtime behavior @@ -297,10 +265,8 @@ C401 [*] Unnecessary generator (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -30 | # See https://github.com/astral-sh/ruff/issues/15852 - - set((0 for _ in []),) +31 - set((0 for _ in []),) 31 + {0 for _ in []} -32 | set( | note: This is an unsafe fix and may change runtime behavior @@ -321,17 +287,10 @@ C401 [*] Unnecessary generator (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -31 | set((0 for _ in []),) - - set( - - (0 for _ in []) 32 + { -33 + 0 for _ in [] +33 ~ 0 for _ in [] 34 | # some comments - - , - - # some more - - ) -35 + } -36 | +35 ~ } | note: This is an unsafe fix and may change runtime behavior @@ -346,10 +305,8 @@ C401 [*] Unnecessary generator (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -39 | # t-strings - - print(t"Hello {set(f(a) for a in 'abc')} World") +40 - print(t"Hello {set(f(a) for a in 'abc')} World") 40 + print(t"Hello { {f(a) for a in 'abc'} } World") -41 | print(t"Hello { set(f(a) for a in 'abc') } World") | note: This is an unsafe fix and may change runtime behavior @@ -365,10 +322,8 @@ C401 [*] Unnecessary generator (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -40 | print(t"Hello {set(f(a) for a in 'abc')} World") - - print(t"Hello { set(f(a) for a in 'abc') } World") +41 - print(t"Hello { set(f(a) for a in 'abc') } World") 41 + print(t"Hello { {f(a) for a in 'abc'} } World") -42 | small_nums = t"{set(a if a < 6 else 0 for a in range(3))}" | note: This is an unsafe fix and may change runtime behavior @@ -384,10 +339,8 @@ C401 [*] Unnecessary generator (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -41 | print(t"Hello { set(f(a) for a in 'abc') } World") - - small_nums = t"{set(a if a < 6 else 0 for a in range(3))}" +42 - small_nums = t"{set(a if a < 6 else 0 for a in range(3))}" 42 + small_nums = t"{ {a if a < 6 else 0 for a in range(3)} }" -43 | print(t"Hello {set(a for a in range(3))} World") | note: This is an unsafe fix and may change runtime behavior @@ -403,10 +356,8 @@ C401 [*] Unnecessary generator (rewrite using `set()`) | help: Rewrite using `set()` | -42 | small_nums = t"{set(a if a < 6 else 0 for a in range(3))}" - - print(t"Hello {set(a for a in range(3))} World") +43 - print(t"Hello {set(a for a in range(3))} World") 43 + print(t"Hello {set(range(3))} World") -44 | print(t"{set(a for a in 'abc') - set(a for a in 'ab')}") | note: This is an unsafe fix and may change runtime behavior @@ -421,10 +372,8 @@ C401 [*] Unnecessary generator (rewrite using `set()`) | help: Rewrite using `set()` | -43 | print(t"Hello {set(a for a in range(3))} World") - - print(t"{set(a for a in 'abc') - set(a for a in 'ab')}") +44 - print(t"{set(a for a in 'abc') - set(a for a in 'ab')}") 44 + print(t"{set('abc') - set(a for a in 'ab')}") -45 | print(t"{ set(a for a in 'abc') - set(a for a in 'ab') }") | note: This is an unsafe fix and may change runtime behavior @@ -439,10 +388,8 @@ C401 [*] Unnecessary generator (rewrite using `set()`) | help: Rewrite using `set()` | -43 | print(t"Hello {set(a for a in range(3))} World") - - print(t"{set(a for a in 'abc') - set(a for a in 'ab')}") +44 - print(t"{set(a for a in 'abc') - set(a for a in 'ab')}") 44 + print(t"{set(a for a in 'abc') - set('ab')}") -45 | print(t"{ set(a for a in 'abc') - set(a for a in 'ab') }") | note: This is an unsafe fix and may change runtime behavior @@ -455,10 +402,8 @@ C401 [*] Unnecessary generator (rewrite using `set()`) | ^^^^^^^^^^^^^^^^^^^^^ help: Rewrite using `set()` | -44 | print(t"{set(a for a in 'abc') - set(a for a in 'ab')}") - - print(t"{ set(a for a in 'abc') - set(a for a in 'ab') }") +45 - print(t"{ set(a for a in 'abc') - set(a for a in 'ab') }") 45 + print(t"{ set('abc') - set(a for a in 'ab') }") -46 | | note: This is an unsafe fix and may change runtime behavior @@ -471,9 +416,7 @@ C401 [*] Unnecessary generator (rewrite using `set()`) | ^^^^^^^^^^^^^^^^^^^^ help: Rewrite using `set()` | -44 | print(t"{set(a for a in 'abc') - set(a for a in 'ab')}") - - print(t"{ set(a for a in 'abc') - set(a for a in 'ab') }") +45 - print(t"{ set(a for a in 'abc') - set(a for a in 'ab') }") 45 + print(t"{ set(a for a in 'abc') - set('ab') }") -46 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C401_C401_py315.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C401_C401_py315.py.snap index e7972d0580172..28dc8f45cc5a4 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C401_C401_py315.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C401_C401_py315.py.snap @@ -10,8 +10,7 @@ C401 [*] Unnecessary generator (rewrite as a set comprehension) | ^^^^^^^^^^^^^^^^^^^ help: Rewrite as a set comprehension | -2 | - - set(*x for x in xs) +3 - set(*x for x in xs) 3 + {*x for x in xs} | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C402_C402.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C402_C402.py.snap index 2bd00f5d71db0..c25016824e5cf 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C402_C402.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C402_C402.py.snap @@ -11,9 +11,8 @@ C402 [*] Unnecessary generator (rewrite as a dict comprehension) | help: Rewrite as a dict comprehension | - - dict((x, x) for x in range(3)) +1 - dict((x, x) for x in range(3)) 1 + {x: x for x in range(3)} -2 | dict( | note: This is an unsafe fix and may change runtime behavior @@ -30,14 +29,9 @@ C402 [*] Unnecessary generator (rewrite as a dict comprehension) | help: Rewrite as a dict comprehension | -1 | dict((x, x) for x in range(3)) - - dict( - - (x, x) for x in range(3) - - ) 2 + { 3 + x: x for x in range(3) 4 + } -5 | dict(((x, x) for x in range(3)), z=3) | note: This is an unsafe fix and may change runtime behavior @@ -53,10 +47,8 @@ C402 [*] Unnecessary generator (rewrite as a dict comprehension) | help: Rewrite as a dict comprehension | -5 | dict(((x, x) for x in range(3)), z=3) - - y = f'{dict((x, x) for x in range(3))}' +6 - y = f'{dict((x, x) for x in range(3))}' 6 + y = f'{ {x: x for x in range(3)} }' -7 | print(f'Hello {dict((x, x) for x in range(3))} World') | note: This is an unsafe fix and may change runtime behavior @@ -72,10 +64,8 @@ C402 [*] Unnecessary generator (rewrite as a dict comprehension) | help: Rewrite as a dict comprehension | -6 | y = f'{dict((x, x) for x in range(3))}' - - print(f'Hello {dict((x, x) for x in range(3))} World') +7 - print(f'Hello {dict((x, x) for x in range(3))} World') 7 + print(f'Hello { {x: x for x in range(3)} } World') -8 | print(f"Hello {dict((x, x) for x in 'abc')} World") | note: This is an unsafe fix and may change runtime behavior @@ -91,10 +81,8 @@ C402 [*] Unnecessary generator (rewrite as a dict comprehension) | help: Rewrite as a dict comprehension | -7 | print(f'Hello {dict((x, x) for x in range(3))} World') - - print(f"Hello {dict((x, x) for x in 'abc')} World") +8 - print(f"Hello {dict((x, x) for x in 'abc')} World") 8 + print(f"Hello { {x: x for x in 'abc'} } World") -9 | print(f'Hello {dict((x, x) for x in "abc")} World') | note: This is an unsafe fix and may change runtime behavior @@ -108,12 +96,10 @@ C402 [*] Unnecessary generator (rewrite as a dict comprehension) 10 | print(f'Hello {dict((x,x) for x in "abc")} World') | help: Rewrite as a dict comprehension - | -8 | print(f"Hello {dict((x, x) for x in 'abc')} World") - - print(f'Hello {dict((x, x) for x in "abc")} World') -9 + print(f'Hello { {x: x for x in "abc"} } World') -10 | print(f'Hello {dict((x,x) for x in "abc")} World') - | + | +9 - print(f'Hello {dict((x, x) for x in "abc")} World') +9 + print(f'Hello { {x: x for x in "abc"} } World') + | note: This is an unsafe fix and may change runtime behavior C402 [*] Unnecessary generator (rewrite as a dict comprehension) @@ -128,10 +114,8 @@ C402 [*] Unnecessary generator (rewrite as a dict comprehension) | help: Rewrite as a dict comprehension | -9 | print(f'Hello {dict((x, x) for x in "abc")} World') - - print(f'Hello {dict((x,x) for x in "abc")} World') +10 - print(f'Hello {dict((x,x) for x in "abc")} World') 10 + print(f'Hello { {x: x for x in "abc"} } World') -11 | | note: This is an unsafe fix and may change runtime behavior @@ -146,10 +130,8 @@ C402 [*] Unnecessary generator (rewrite as a dict comprehension) | help: Rewrite as a dict comprehension | -11 | - - f'{dict((x, x) for x in range(3)) | dict((x, x) for x in range(3))}' +12 - f'{dict((x, x) for x in range(3)) | dict((x, x) for x in range(3))}' 12 + f'{ {x: x for x in range(3)} | dict((x, x) for x in range(3))}' -13 | f'{ dict((x, x) for x in range(3)) | dict((x, x) for x in range(3)) }' | note: This is an unsafe fix and may change runtime behavior @@ -164,10 +146,8 @@ C402 [*] Unnecessary generator (rewrite as a dict comprehension) | help: Rewrite as a dict comprehension | -11 | - - f'{dict((x, x) for x in range(3)) | dict((x, x) for x in range(3))}' +12 - f'{dict((x, x) for x in range(3)) | dict((x, x) for x in range(3))}' 12 + f'{dict((x, x) for x in range(3)) | {x: x for x in range(3)} }' -13 | f'{ dict((x, x) for x in range(3)) | dict((x, x) for x in range(3)) }' | note: This is an unsafe fix and may change runtime behavior @@ -182,10 +162,8 @@ C402 [*] Unnecessary generator (rewrite as a dict comprehension) | help: Rewrite as a dict comprehension | -12 | f'{dict((x, x) for x in range(3)) | dict((x, x) for x in range(3))}' - - f'{ dict((x, x) for x in range(3)) | dict((x, x) for x in range(3)) }' +13 - f'{ dict((x, x) for x in range(3)) | dict((x, x) for x in range(3)) }' 13 + f'{ {x: x for x in range(3)} | dict((x, x) for x in range(3)) }' -14 | | note: This is an unsafe fix and may change runtime behavior @@ -200,10 +178,8 @@ C402 [*] Unnecessary generator (rewrite as a dict comprehension) | help: Rewrite as a dict comprehension | -12 | f'{dict((x, x) for x in range(3)) | dict((x, x) for x in range(3))}' - - f'{ dict((x, x) for x in range(3)) | dict((x, x) for x in range(3)) }' +13 - f'{ dict((x, x) for x in range(3)) | dict((x, x) for x in range(3)) }' 13 + f'{ dict((x, x) for x in range(3)) | {x: x for x in range(3)} }' -14 | | note: This is an unsafe fix and may change runtime behavior @@ -219,10 +195,8 @@ C402 [*] Unnecessary generator (rewrite as a dict comprehension) | help: Rewrite as a dict comprehension | -17 | - - print(f'Hello {dict((x,f(x)) for x in "abc")} World') +18 - print(f'Hello {dict((x,f(x)) for x in "abc")} World') 18 + print(f'Hello { {x: f(x) for x in "abc"} } World') -19 | | note: This is an unsafe fix and may change runtime behavior @@ -237,9 +211,7 @@ C402 [*] Unnecessary generator (rewrite as a dict comprehension) | help: Rewrite as a dict comprehension | -20 | # Regression test for: https://github.com/astral-sh/ruff/issues/7086 - - dict((k,v)for k,v in d.iteritems() if k in only_args) +21 - dict((k,v)for k,v in d.iteritems() if k in only_args) 21 + {k: v for k,v in d.iteritems() if k in only_args} -22 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C403_C403.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C403_C403.py.snap index e6dcb05b14a6c..7337a171a7df7 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C403_C403.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C403_C403.py.snap @@ -11,9 +11,8 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | help: Rewrite as a set comprehension | - - s = set([x for x in range(3)]) +1 - s = set([x for x in range(3)]) 1 + s = {x for x in range(3)} -2 | s = set( | note: This is an unsafe fix and may change runtime behavior @@ -31,14 +30,9 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -1 | s = set([x for x in range(3)]) - - s = set( - - [x for x in range(3)] - - ) -2 + s = { -3 + x for x in range(3) +2 ~ s = { +3 ~ x for x in range(3) 4 + } -5 | | note: This is an unsafe fix and may change runtime behavior @@ -53,10 +47,8 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -5 | - - s = f"{set([x for x in 'ab'])}" +6 - s = f"{set([x for x in 'ab'])}" 6 + s = f"{ {x for x in 'ab'} }" -7 | s = f'{set([x for x in "ab"])}' | note: This is an unsafe fix and may change runtime behavior @@ -71,10 +63,8 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -6 | s = f"{set([x for x in 'ab'])}" - - s = f'{set([x for x in "ab"])}' +7 - s = f'{set([x for x in "ab"])}' 7 + s = f'{ {x for x in "ab"} }' -8 | | note: This is an unsafe fix and may change runtime behavior @@ -90,10 +80,8 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -11 | - - s = f"{set([f(x) for x in 'ab'])}" +12 - s = f"{set([f(x) for x in 'ab'])}" 12 + s = f"{ {f(x) for x in 'ab'} }" -13 | | note: This is an unsafe fix and may change runtime behavior @@ -108,10 +96,8 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -13 | - - s = f"{ set([x for x in 'ab']) | set([x for x in 'ab']) }" +14 - s = f"{ set([x for x in 'ab']) | set([x for x in 'ab']) }" 14 + s = f"{ {x for x in 'ab'} | set([x for x in 'ab']) }" -15 | s = f"{set([x for x in 'ab']) | set([x for x in 'ab'])}" | note: This is an unsafe fix and may change runtime behavior @@ -126,10 +112,8 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -13 | - - s = f"{ set([x for x in 'ab']) | set([x for x in 'ab']) }" +14 - s = f"{ set([x for x in 'ab']) | set([x for x in 'ab']) }" 14 + s = f"{ set([x for x in 'ab']) | {x for x in 'ab'} }" -15 | s = f"{set([x for x in 'ab']) | set([x for x in 'ab'])}" | note: This is an unsafe fix and may change runtime behavior @@ -144,10 +128,8 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -14 | s = f"{ set([x for x in 'ab']) | set([x for x in 'ab']) }" - - s = f"{set([x for x in 'ab']) | set([x for x in 'ab'])}" +15 - s = f"{set([x for x in 'ab']) | set([x for x in 'ab'])}" 15 + s = f"{ {x for x in 'ab'} | set([x for x in 'ab'])}" -16 | | note: This is an unsafe fix and may change runtime behavior @@ -162,10 +144,8 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -14 | s = f"{ set([x for x in 'ab']) | set([x for x in 'ab']) }" - - s = f"{set([x for x in 'ab']) | set([x for x in 'ab'])}" +15 - s = f"{set([x for x in 'ab']) | set([x for x in 'ab'])}" 15 + s = f"{set([x for x in 'ab']) | {x for x in 'ab'} }" -16 | | note: This is an unsafe fix and may change runtime behavior @@ -184,14 +164,9 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -16 | - - s = set( # comment - - [x for x in range(3)] - - ) -17 + s = { # comment -18 + x for x in range(3) +17 ~ s = { # comment +18 ~ x for x in range(3) 19 + } -20 | | note: This is an unsafe fix and may change runtime behavior @@ -210,13 +185,9 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -20 | - - s = set([ # comment -21 + s = { # comment -22 | x for x in range(3) - - ]) -23 + } -24 | +21 ~ s = { # comment +22 + x for x in range(3) +23 ~ } | note: This is an unsafe fix and may change runtime behavior @@ -232,10 +203,8 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -24 | - - s = set(([x for x in range(3)])) +25 - s = set(([x for x in range(3)])) 25 + s = {x for x in range(3)} -26 | | note: This is an unsafe fix and may change runtime behavior @@ -251,10 +220,8 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -26 | - - s = set(((([x for x in range(3)])))) +27 - s = set(((([x for x in range(3)])))) 27 + s = {x for x in range(3)} -28 | | note: This is an unsafe fix and may change runtime behavior @@ -276,17 +243,9 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -28 | - - s = set( # outer set comment - - ( # inner paren comment - not preserved - - (( - - [ # comprehension comment - - x for x in range(3)] - - )))) -29 + s = { # outer set comment +29 ~ s = { # outer set comment 30 + # comprehension comment -31 + x for x in range(3)} -32 | +31 ~ x for x in range(3)} | note: This is an unsafe fix and may change runtime behavior @@ -301,10 +260,8 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -36 | # Test trailing comma case - - s = set([x for x in range(3)],) +37 - s = set([x for x in range(3)],) 37 + s = {x for x in range(3)} -38 | | note: This is an unsafe fix and may change runtime behavior @@ -319,10 +276,8 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -38 | - - s = t"{set([x for x in 'ab'])}" +39 - s = t"{set([x for x in 'ab'])}" 39 + s = t"{ {x for x in 'ab'} }" -40 | s = t'{set([x for x in "ab"])}' | note: This is an unsafe fix and may change runtime behavior @@ -337,10 +292,8 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -39 | s = t"{set([x for x in 'ab'])}" - - s = t'{set([x for x in "ab"])}' +40 - s = t'{set([x for x in "ab"])}' 40 + s = t'{ {x for x in "ab"} }' -41 | | note: This is an unsafe fix and may change runtime behavior @@ -356,10 +309,8 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -44 | - - s = t"{set([f(x) for x in 'ab'])}" +45 - s = t"{set([f(x) for x in 'ab'])}" 45 + s = t"{ {f(x) for x in 'ab'} }" -46 | | note: This is an unsafe fix and may change runtime behavior @@ -374,10 +325,8 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -46 | - - s = t"{ set([x for x in 'ab']) | set([x for x in 'ab']) }" +47 - s = t"{ set([x for x in 'ab']) | set([x for x in 'ab']) }" 47 + s = t"{ {x for x in 'ab'} | set([x for x in 'ab']) }" -48 | s = t"{set([x for x in 'ab']) | set([x for x in 'ab'])}" | note: This is an unsafe fix and may change runtime behavior @@ -392,10 +341,8 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | help: Rewrite as a set comprehension | -46 | - - s = t"{ set([x for x in 'ab']) | set([x for x in 'ab']) }" +47 - s = t"{ set([x for x in 'ab']) | set([x for x in 'ab']) }" 47 + s = t"{ set([x for x in 'ab']) | {x for x in 'ab'} }" -48 | s = t"{set([x for x in 'ab']) | set([x for x in 'ab'])}" | note: This is an unsafe fix and may change runtime behavior @@ -407,10 +354,8 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | ^^^^^^^^^^^^^^^^^^^^^^ help: Rewrite as a set comprehension | -47 | s = t"{ set([x for x in 'ab']) | set([x for x in 'ab']) }" - - s = t"{set([x for x in 'ab']) | set([x for x in 'ab'])}" +48 - s = t"{set([x for x in 'ab']) | set([x for x in 'ab'])}" 48 + s = t"{ {x for x in 'ab'} | set([x for x in 'ab'])}" -49 | | note: This is an unsafe fix and may change runtime behavior @@ -422,9 +367,7 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | ^^^^^^^^^^^^^^^^^^^^^^ help: Rewrite as a set comprehension | -47 | s = t"{ set([x for x in 'ab']) | set([x for x in 'ab']) }" - - s = t"{set([x for x in 'ab']) | set([x for x in 'ab'])}" +48 - s = t"{set([x for x in 'ab']) | set([x for x in 'ab'])}" 48 + s = t"{set([x for x in 'ab']) | {x for x in 'ab'} }" -49 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C403_C403_py315.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C403_C403_py315.py.snap index 2231cf55865c9..8ff7ecf225c69 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C403_C403_py315.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C403_C403_py315.py.snap @@ -10,8 +10,7 @@ C403 [*] Unnecessary list comprehension (rewrite as a set comprehension) | ^^^^^^^^^^^^^^^^^^^^^ help: Rewrite as a set comprehension | -2 | - - set([*x for x in xs]) +3 - set([*x for x in xs]) 3 + {*x for x in xs} | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C404_C404.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C404_C404.py.snap index 8f46f7a7f01cd..32039723a279f 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C404_C404.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C404_C404.py.snap @@ -10,9 +10,8 @@ C404 [*] Unnecessary list comprehension (rewrite as a dict comprehension) | help: Rewrite as a dict comprehension | - - dict([(i, i) for i in range(3)]) +1 - dict([(i, i) for i in range(3)]) 1 + {i: i for i in range(3)} -2 | dict([(i, i) for i in range(3)], z=4) | note: This is an unsafe fix and may change runtime behavior @@ -28,10 +27,8 @@ C404 [*] Unnecessary list comprehension (rewrite as a dict comprehension) | help: Rewrite as a dict comprehension | -6 | - - f'{dict([(s,s) for s in "ab"])}' +7 - f'{dict([(s,s) for s in "ab"])}' 7 + f'{ {s: s for s in "ab"} }' -8 | f"{dict([(s,s) for s in 'ab'])}" | note: This is an unsafe fix and may change runtime behavior @@ -46,10 +43,8 @@ C404 [*] Unnecessary list comprehension (rewrite as a dict comprehension) | help: Rewrite as a dict comprehension | -7 | f'{dict([(s,s) for s in "ab"])}' - - f"{dict([(s,s) for s in 'ab'])}" +8 - f"{dict([(s,s) for s in 'ab'])}" 8 + f"{ {s: s for s in 'ab'} }" -9 | f"{dict([(s, s) for s in 'ab'])}" | note: This is an unsafe fix and may change runtime behavior @@ -63,12 +58,10 @@ C404 [*] Unnecessary list comprehension (rewrite as a dict comprehension) 10 | f"{dict([(s,f(s)) for s in 'ab'])}" | help: Rewrite as a dict comprehension - | -8 | f"{dict([(s,s) for s in 'ab'])}" - - f"{dict([(s, s) for s in 'ab'])}" -9 + f"{ {s: s for s in 'ab'} }" -10 | f"{dict([(s,f(s)) for s in 'ab'])}" - | + | +9 - f"{dict([(s, s) for s in 'ab'])}" +9 + f"{ {s: s for s in 'ab'} }" + | note: This is an unsafe fix and may change runtime behavior C404 [*] Unnecessary list comprehension (rewrite as a dict comprehension) @@ -83,10 +76,8 @@ C404 [*] Unnecessary list comprehension (rewrite as a dict comprehension) | help: Rewrite as a dict comprehension | -9 | f"{dict([(s, s) for s in 'ab'])}" - - f"{dict([(s,f(s)) for s in 'ab'])}" +10 - f"{dict([(s,f(s)) for s in 'ab'])}" 10 + f"{ {s: f(s) for s in 'ab'} }" -11 | | note: This is an unsafe fix and may change runtime behavior @@ -101,10 +92,8 @@ C404 [*] Unnecessary list comprehension (rewrite as a dict comprehension) | help: Rewrite as a dict comprehension | -11 | - - f'{dict([(s,s) for s in "ab"]) | dict([(s,s) for s in "ab"])}' +12 - f'{dict([(s,s) for s in "ab"]) | dict([(s,s) for s in "ab"])}' 12 + f'{ {s: s for s in "ab"} | dict([(s,s) for s in "ab"])}' -13 | f'{ dict([(s,s) for s in "ab"]) | dict([(s,s) for s in "ab"]) }' | note: This is an unsafe fix and may change runtime behavior @@ -119,10 +108,8 @@ C404 [*] Unnecessary list comprehension (rewrite as a dict comprehension) | help: Rewrite as a dict comprehension | -11 | - - f'{dict([(s,s) for s in "ab"]) | dict([(s,s) for s in "ab"])}' +12 - f'{dict([(s,s) for s in "ab"]) | dict([(s,s) for s in "ab"])}' 12 + f'{dict([(s,s) for s in "ab"]) | {s: s for s in "ab"} }' -13 | f'{ dict([(s,s) for s in "ab"]) | dict([(s,s) for s in "ab"]) }' | note: This is an unsafe fix and may change runtime behavior @@ -137,10 +124,8 @@ C404 [*] Unnecessary list comprehension (rewrite as a dict comprehension) | help: Rewrite as a dict comprehension | -12 | f'{dict([(s,s) for s in "ab"]) | dict([(s,s) for s in "ab"])}' - - f'{ dict([(s,s) for s in "ab"]) | dict([(s,s) for s in "ab"]) }' +13 - f'{ dict([(s,s) for s in "ab"]) | dict([(s,s) for s in "ab"]) }' 13 + f'{ {s: s for s in "ab"} | dict([(s,s) for s in "ab"]) }' -14 | | note: This is an unsafe fix and may change runtime behavior @@ -155,10 +140,8 @@ C404 [*] Unnecessary list comprehension (rewrite as a dict comprehension) | help: Rewrite as a dict comprehension | -12 | f'{dict([(s,s) for s in "ab"]) | dict([(s,s) for s in "ab"])}' - - f'{ dict([(s,s) for s in "ab"]) | dict([(s,s) for s in "ab"]) }' +13 - f'{ dict([(s,s) for s in "ab"]) | dict([(s,s) for s in "ab"]) }' 13 + f'{ dict([(s,s) for s in "ab"]) | {s: s for s in "ab"} }' -14 | | note: This is an unsafe fix and may change runtime behavior @@ -170,8 +153,7 @@ C404 [*] Unnecessary list comprehension (rewrite as a dict comprehension) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Rewrite as a dict comprehension | -15 | # Regression test for: https://github.com/astral-sh/ruff/issues/7087 - - saved.append(dict([(k, v)for k,v in list(unique_instance.__dict__.items()) if k in [f.name for f in unique_instance._meta.fields]])) +16 - saved.append(dict([(k, v)for k,v in list(unique_instance.__dict__.items()) if k in [f.name for f in unique_instance._meta.fields]])) 16 + saved.append({k: v for k,v in list(unique_instance.__dict__.items()) if k in [f.name for f in unique_instance._meta.fields]}) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C405_C405.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C405_C405.py.snap index d8e9ff2ba17c9..5a4c65699e21d 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C405_C405.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C405_C405.py.snap @@ -11,9 +11,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | - - set([1, 2]) +1 - set([1, 2]) 1 + {1, 2} -2 | set((1, 2)) | note: This is an unsafe fix and may change runtime behavior @@ -28,10 +27,8 @@ C405 [*] Unnecessary tuple literal (rewrite as a set literal) | help: Rewrite as a set literal | -1 | set([1, 2]) - - set((1, 2)) +2 - set((1, 2)) 2 + {1, 2} -3 | set([]) | note: This is an unsafe fix and may change runtime behavior @@ -47,10 +44,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -2 | set((1, 2)) - - set([]) +3 - set([]) 3 + set() -4 | set(()) | note: This is an unsafe fix and may change runtime behavior @@ -66,11 +61,8 @@ C405 [*] Unnecessary tuple literal (rewrite as a set literal) | help: Rewrite as a set literal | -3 | set([]) - - set(()) -4 | set() -5 + set() -6 | set((1,)) +4 - set(()) +4 + set() | note: This is an unsafe fix and may change runtime behavior @@ -86,10 +78,8 @@ C405 [*] Unnecessary tuple literal (rewrite as a set literal) | help: Rewrite as a set literal | -5 | set() - - set((1,)) +6 - set((1,)) 6 + {1} -7 | set(( | note: This is an unsafe fix and may change runtime behavior @@ -106,15 +96,11 @@ C405 [*] Unnecessary tuple literal (rewrite as a set literal) 11 | 1, | help: Rewrite as a set literal - | -6 | set((1,)) - - set(( -7 + { -8 | 1, - - )) -9 + } -10 | set([ - | + | +7 + { +8 | 1, +9 + } + | note: This is an unsafe fix and may change runtime behavior C405 [*] Unnecessary list literal (rewrite as a set literal) @@ -131,13 +117,9 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -9 | )) - - set([ 10 + { 11 | 1, - - ]) 12 + } -13 | set( | note: This is an unsafe fix and may change runtime behavior @@ -155,12 +137,10 @@ C405 [*] Unnecessary tuple literal (rewrite as a set literal) | help: Rewrite as a set literal | -12 | ]) - - set( - - (1,) - - ) +13 - set( +14 - (1,) +15 - ) 13 + {1} -14 | set( | note: This is an unsafe fix and may change runtime behavior @@ -178,12 +158,10 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -15 | ) - - set( - - [1,] - - ) +16 - set( +17 - [1,] +18 - ) 16 + {1,} -17 | f"{set([1,2,3])}" | note: This is an unsafe fix and may change runtime behavior @@ -199,10 +177,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -18 | ) - - f"{set([1,2,3])}" +19 - f"{set([1,2,3])}" 19 + f"{ {1,2,3} }" -20 | f"{set(['a', 'b'])}" | note: This is an unsafe fix and may change runtime behavior @@ -217,10 +193,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -19 | f"{set([1,2,3])}" - - f"{set(['a', 'b'])}" +20 - f"{set(['a', 'b'])}" 20 + f"{ {'a', 'b'} }" -21 | f'{set(["a", "b"])}' | note: This is an unsafe fix and may change runtime behavior @@ -236,10 +210,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -20 | f"{set(['a', 'b'])}" - - f'{set(["a", "b"])}' +21 - f'{set(["a", "b"])}' 21 + f'{ {"a", "b"} }' -22 | | note: This is an unsafe fix and may change runtime behavior @@ -255,10 +227,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -22 | - - f"{set(['a', 'b']) - set(['a'])}" +23 - f"{set(['a', 'b']) - set(['a'])}" 23 + f"{ {'a', 'b'} - set(['a'])}" -24 | f"{ set(['a', 'b']) - set(['a']) }" | note: This is an unsafe fix and may change runtime behavior @@ -274,10 +244,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -22 | - - f"{set(['a', 'b']) - set(['a'])}" +23 - f"{set(['a', 'b']) - set(['a'])}" 23 + f"{set(['a', 'b']) - {'a'} }" -24 | f"{ set(['a', 'b']) - set(['a']) }" | note: This is an unsafe fix and may change runtime behavior @@ -292,10 +260,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -23 | f"{set(['a', 'b']) - set(['a'])}" - - f"{ set(['a', 'b']) - set(['a']) }" +24 - f"{ set(['a', 'b']) - set(['a']) }" 24 + f"{ {'a', 'b'} - set(['a']) }" -25 | f"a {set(['a', 'b']) - set(['a'])} b" | note: This is an unsafe fix and may change runtime behavior @@ -310,10 +276,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -23 | f"{set(['a', 'b']) - set(['a'])}" - - f"{ set(['a', 'b']) - set(['a']) }" +24 - f"{ set(['a', 'b']) - set(['a']) }" 24 + f"{ set(['a', 'b']) - {'a'} }" -25 | f"a {set(['a', 'b']) - set(['a'])} b" | note: This is an unsafe fix and may change runtime behavior @@ -328,10 +292,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -24 | f"{ set(['a', 'b']) - set(['a']) }" - - f"a {set(['a', 'b']) - set(['a'])} b" +25 - f"a {set(['a', 'b']) - set(['a'])} b" 25 + f"a { {'a', 'b'} - set(['a'])} b" -26 | f"a { set(['a', 'b']) - set(['a']) } b" | note: This is an unsafe fix and may change runtime behavior @@ -346,10 +308,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -24 | f"{ set(['a', 'b']) - set(['a']) }" - - f"a {set(['a', 'b']) - set(['a'])} b" +25 - f"a {set(['a', 'b']) - set(['a'])} b" 25 + f"a {set(['a', 'b']) - {'a'} } b" -26 | f"a { set(['a', 'b']) - set(['a']) } b" | note: This is an unsafe fix and may change runtime behavior @@ -365,10 +325,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -25 | f"a {set(['a', 'b']) - set(['a'])} b" - - f"a { set(['a', 'b']) - set(['a']) } b" +26 - f"a { set(['a', 'b']) - set(['a']) } b" 26 + f"a { {'a', 'b'} - set(['a']) } b" -27 | | note: This is an unsafe fix and may change runtime behavior @@ -384,10 +342,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -25 | f"a {set(['a', 'b']) - set(['a'])} b" - - f"a { set(['a', 'b']) - set(['a']) } b" +26 - f"a { set(['a', 'b']) - set(['a']) } b" 26 + f"a { set(['a', 'b']) - {'a'} } b" -27 | | note: This is an unsafe fix and may change runtime behavior @@ -403,10 +359,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -27 | - - t"{set([1,2,3])}" +28 - t"{set([1,2,3])}" 28 + t"{ {1,2,3} }" -29 | t"{set(['a', 'b'])}" | note: This is an unsafe fix and may change runtime behavior @@ -420,10 +374,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -28 | t"{set([1,2,3])}" - - t"{set(['a', 'b'])}" +29 - t"{set(['a', 'b'])}" 29 + t"{ {'a', 'b'} }" -30 | t'{set(["a", "b"])}' | note: This is an unsafe fix and may change runtime behavior @@ -439,10 +391,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -29 | t"{set(['a', 'b'])}" - - t'{set(["a", "b"])}' +30 - t'{set(["a", "b"])}' 30 + t'{ {"a", "b"} }' -31 | | note: This is an unsafe fix and may change runtime behavior @@ -458,10 +408,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -31 | - - t"{set(['a', 'b']) - set(['a'])}" +32 - t"{set(['a', 'b']) - set(['a'])}" 32 + t"{ {'a', 'b'} - set(['a'])}" -33 | t"{ set(['a', 'b']) - set(['a']) }" | note: This is an unsafe fix and may change runtime behavior @@ -477,10 +425,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -31 | - - t"{set(['a', 'b']) - set(['a'])}" +32 - t"{set(['a', 'b']) - set(['a'])}" 32 + t"{set(['a', 'b']) - {'a'} }" -33 | t"{ set(['a', 'b']) - set(['a']) }" | note: This is an unsafe fix and may change runtime behavior @@ -495,10 +441,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -32 | t"{set(['a', 'b']) - set(['a'])}" - - t"{ set(['a', 'b']) - set(['a']) }" +33 - t"{ set(['a', 'b']) - set(['a']) }" 33 + t"{ {'a', 'b'} - set(['a']) }" -34 | t"a {set(['a', 'b']) - set(['a'])} b" | note: This is an unsafe fix and may change runtime behavior @@ -513,10 +457,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -32 | t"{set(['a', 'b']) - set(['a'])}" - - t"{ set(['a', 'b']) - set(['a']) }" +33 - t"{ set(['a', 'b']) - set(['a']) }" 33 + t"{ set(['a', 'b']) - {'a'} }" -34 | t"a {set(['a', 'b']) - set(['a'])} b" | note: This is an unsafe fix and may change runtime behavior @@ -531,10 +473,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -33 | t"{ set(['a', 'b']) - set(['a']) }" - - t"a {set(['a', 'b']) - set(['a'])} b" +34 - t"a {set(['a', 'b']) - set(['a'])} b" 34 + t"a { {'a', 'b'} - set(['a'])} b" -35 | t"a { set(['a', 'b']) - set(['a']) } b" | note: This is an unsafe fix and may change runtime behavior @@ -549,10 +489,8 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | help: Rewrite as a set literal | -33 | t"{ set(['a', 'b']) - set(['a']) }" - - t"a {set(['a', 'b']) - set(['a'])} b" +34 - t"a {set(['a', 'b']) - set(['a'])} b" 34 + t"a {set(['a', 'b']) - {'a'} } b" -35 | t"a { set(['a', 'b']) - set(['a']) } b" | note: This is an unsafe fix and may change runtime behavior @@ -565,8 +503,7 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | ^^^^^^^^^^^^^^^ help: Rewrite as a set literal | -34 | t"a {set(['a', 'b']) - set(['a'])} b" - - t"a { set(['a', 'b']) - set(['a']) } b" +35 - t"a { set(['a', 'b']) - set(['a']) } b" 35 + t"a { {'a', 'b'} - set(['a']) } b" | note: This is an unsafe fix and may change runtime behavior @@ -580,8 +517,7 @@ C405 [*] Unnecessary list literal (rewrite as a set literal) | ^^^^^^^^^^ help: Rewrite as a set literal | -34 | t"a {set(['a', 'b']) - set(['a'])} b" - - t"a { set(['a', 'b']) - set(['a']) } b" +35 - t"a { set(['a', 'b']) - set(['a']) } b" 35 + t"a { set(['a', 'b']) - {'a'} } b" | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C406_C406.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C406_C406.py.snap index 56a35d67ec906..2122c0e1725fc 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C406_C406.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C406_C406.py.snap @@ -11,9 +11,8 @@ C406 [*] Unnecessary list literal (rewrite as a dict literal) | help: Rewrite as a dict literal | - - d1 = dict([(1, 2)]) +1 - d1 = dict([(1, 2)]) 1 + d1 = {1: 2} -2 | d2 = dict(((1, 2),)) | note: This is an unsafe fix and may change runtime behavior @@ -28,10 +27,8 @@ C406 [*] Unnecessary tuple literal (rewrite as a dict literal) | help: Rewrite as a dict literal | -1 | d1 = dict([(1, 2)]) - - d2 = dict(((1, 2),)) +2 - d2 = dict(((1, 2),)) 2 + d2 = {1: 2,} -3 | d3 = dict([]) | note: This is an unsafe fix and may change runtime behavior @@ -47,10 +44,8 @@ C406 [*] Unnecessary list literal (rewrite as a dict literal) | help: Rewrite as a dict literal | -2 | d2 = dict(((1, 2),)) - - d3 = dict([]) +3 - d3 = dict([]) 3 + d3 = {} -4 | d4 = dict(()) | note: This is an unsafe fix and may change runtime behavior @@ -65,9 +60,7 @@ C406 [*] Unnecessary tuple literal (rewrite as a dict literal) | help: Rewrite as a dict literal | -3 | d3 = dict([]) - - d4 = dict(()) +4 - d4 = dict(()) 4 + d4 = {} -5 | d5 = dict() | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C408_C408.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C408_C408.py.snap index 0fea149499c56..23a84f64cb2fc 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C408_C408.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C408_C408.py.snap @@ -11,9 +11,8 @@ C408 [*] Unnecessary `tuple()` call (rewrite as a literal) | help: Rewrite as a literal | - - t = tuple() +1 - t = tuple() 1 + t = () -2 | l = list() | note: This is an unsafe fix and may change runtime behavior @@ -28,10 +27,8 @@ C408 [*] Unnecessary `list()` call (rewrite as a literal) | help: Rewrite as a literal | -1 | t = tuple() - - l = list() +2 - l = list() 2 + l = [] -3 | d1 = dict() | note: This is an unsafe fix and may change runtime behavior @@ -47,10 +44,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -2 | l = list() - - d1 = dict() +3 - d1 = dict() 3 + d1 = {} -4 | d2 = dict(a=1) | note: This is an unsafe fix and may change runtime behavior @@ -65,10 +60,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -3 | d1 = dict() - - d2 = dict(a=1) +4 - d2 = dict(a=1) 4 + d2 = {"a": 1} -5 | d3 = dict(**d2) | note: This is an unsafe fix and may change runtime behavior @@ -84,10 +77,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -13 | - - f"{dict(x='y')}" +14 - f"{dict(x='y')}" 14 + f"{ {'x': 'y'} }" -15 | f'{dict(x="y")}' | note: This is an unsafe fix and may change runtime behavior @@ -102,10 +93,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -14 | f"{dict(x='y')}" - - f'{dict(x="y")}' +15 - f'{dict(x="y")}' 15 + f'{ {"x": "y"} }' -16 | f"{dict()}" | note: This is an unsafe fix and may change runtime behavior @@ -120,10 +109,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -15 | f'{dict(x="y")}' - - f"{dict()}" +16 - f"{dict()}" 16 + f"{ {} }" -17 | f"a {dict()} b" | note: This is an unsafe fix and may change runtime behavior @@ -139,10 +126,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -16 | f"{dict()}" - - f"a {dict()} b" +17 - f"a {dict()} b" 17 + f"a { {} } b" -18 | | note: This is an unsafe fix and may change runtime behavior @@ -158,10 +143,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -18 | - - f"{dict(x='y') | dict(y='z')}" +19 - f"{dict(x='y') | dict(y='z')}" 19 + f"{ {'x': 'y'} | dict(y='z')}" -20 | f"{ dict(x='y') | dict(y='z') }" | note: This is an unsafe fix and may change runtime behavior @@ -177,10 +160,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -18 | - - f"{dict(x='y') | dict(y='z')}" +19 - f"{dict(x='y') | dict(y='z')}" 19 + f"{dict(x='y') | {'y': 'z'} }" -20 | f"{ dict(x='y') | dict(y='z') }" | note: This is an unsafe fix and may change runtime behavior @@ -195,10 +176,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -19 | f"{dict(x='y') | dict(y='z')}" - - f"{ dict(x='y') | dict(y='z') }" +20 - f"{ dict(x='y') | dict(y='z') }" 20 + f"{ {'x': 'y'} | dict(y='z') }" -21 | f"a {dict(x='y') | dict(y='z')} b" | note: This is an unsafe fix and may change runtime behavior @@ -213,10 +192,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -19 | f"{dict(x='y') | dict(y='z')}" - - f"{ dict(x='y') | dict(y='z') }" +20 - f"{ dict(x='y') | dict(y='z') }" 20 + f"{ dict(x='y') | {'y': 'z'} }" -21 | f"a {dict(x='y') | dict(y='z')} b" | note: This is an unsafe fix and may change runtime behavior @@ -231,10 +208,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -20 | f"{ dict(x='y') | dict(y='z') }" - - f"a {dict(x='y') | dict(y='z')} b" +21 - f"a {dict(x='y') | dict(y='z')} b" 21 + f"a { {'x': 'y'} | dict(y='z')} b" -22 | f"a { dict(x='y') | dict(y='z') } b" | note: This is an unsafe fix and may change runtime behavior @@ -249,10 +224,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -20 | f"{ dict(x='y') | dict(y='z') }" - - f"a {dict(x='y') | dict(y='z')} b" +21 - f"a {dict(x='y') | dict(y='z')} b" 21 + f"a {dict(x='y') | {'y': 'z'} } b" -22 | f"a { dict(x='y') | dict(y='z') } b" | note: This is an unsafe fix and may change runtime behavior @@ -268,10 +241,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -21 | f"a {dict(x='y') | dict(y='z')} b" - - f"a { dict(x='y') | dict(y='z') } b" +22 - f"a { dict(x='y') | dict(y='z') } b" 22 + f"a { {'x': 'y'} | dict(y='z') } b" -23 | | note: This is an unsafe fix and may change runtime behavior @@ -287,10 +258,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -21 | f"a {dict(x='y') | dict(y='z')} b" - - f"a { dict(x='y') | dict(y='z') } b" +22 - f"a { dict(x='y') | dict(y='z') } b" 22 + f"a { dict(x='y') | {'y': 'z'} } b" -23 | | note: This is an unsafe fix and may change runtime behavior @@ -308,13 +277,9 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -23 | - - dict( 24 + { 25 | # comment - - ) 26 + } -27 | | note: This is an unsafe fix and may change runtime behavior @@ -331,10 +296,8 @@ C408 [*] Unnecessary `tuple()` call (rewrite as a literal) | help: Rewrite as a literal | -27 | - - tuple( # comment -28 + ( # comment -29 | ) +28 ~ ( # comment +29 ~ ) | note: This is an unsafe fix and may change runtime behavior @@ -350,10 +313,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -30 | - - t"{dict(x='y')}" +31 - t"{dict(x='y')}" 31 + t"{ {'x': 'y'} }" -32 | t'{dict(x="y")}' | note: This is an unsafe fix and may change runtime behavior @@ -368,10 +329,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -31 | t"{dict(x='y')}" - - t'{dict(x="y")}' +32 - t'{dict(x="y")}' 32 + t'{ {"x": "y"} }' -33 | t"{dict()}" | note: This is an unsafe fix and may change runtime behavior @@ -386,10 +345,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -32 | t'{dict(x="y")}' - - t"{dict()}" +33 - t"{dict()}" 33 + t"{ {} }" -34 | t"a {dict()} b" | note: This is an unsafe fix and may change runtime behavior @@ -405,10 +362,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -33 | t"{dict()}" - - t"a {dict()} b" +34 - t"a {dict()} b" 34 + t"a { {} } b" -35 | | note: This is an unsafe fix and may change runtime behavior @@ -424,10 +379,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -35 | - - t"{dict(x='y') | dict(y='z')}" +36 - t"{dict(x='y') | dict(y='z')}" 36 + t"{ {'x': 'y'} | dict(y='z')}" -37 | t"{ dict(x='y') | dict(y='z') }" | note: This is an unsafe fix and may change runtime behavior @@ -443,10 +396,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -35 | - - t"{dict(x='y') | dict(y='z')}" +36 - t"{dict(x='y') | dict(y='z')}" 36 + t"{dict(x='y') | {'y': 'z'} }" -37 | t"{ dict(x='y') | dict(y='z') }" | note: This is an unsafe fix and may change runtime behavior @@ -461,10 +412,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -36 | t"{dict(x='y') | dict(y='z')}" - - t"{ dict(x='y') | dict(y='z') }" +37 - t"{ dict(x='y') | dict(y='z') }" 37 + t"{ {'x': 'y'} | dict(y='z') }" -38 | t"a {dict(x='y') | dict(y='z')} b" | note: This is an unsafe fix and may change runtime behavior @@ -479,10 +428,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -36 | t"{dict(x='y') | dict(y='z')}" - - t"{ dict(x='y') | dict(y='z') }" +37 - t"{ dict(x='y') | dict(y='z') }" 37 + t"{ dict(x='y') | {'y': 'z'} }" -38 | t"a {dict(x='y') | dict(y='z')} b" | note: This is an unsafe fix and may change runtime behavior @@ -497,10 +444,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -37 | t"{ dict(x='y') | dict(y='z') }" - - t"a {dict(x='y') | dict(y='z')} b" +38 - t"a {dict(x='y') | dict(y='z')} b" 38 + t"a { {'x': 'y'} | dict(y='z')} b" -39 | t"a { dict(x='y') | dict(y='z') } b" | note: This is an unsafe fix and may change runtime behavior @@ -515,10 +460,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -37 | t"{ dict(x='y') | dict(y='z') }" - - t"a {dict(x='y') | dict(y='z')} b" +38 - t"a {dict(x='y') | dict(y='z')} b" 38 + t"a {dict(x='y') | {'y': 'z'} } b" -39 | t"a { dict(x='y') | dict(y='z') } b" | note: This is an unsafe fix and may change runtime behavior @@ -534,10 +477,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -38 | t"a {dict(x='y') | dict(y='z')} b" - - t"a { dict(x='y') | dict(y='z') } b" +39 - t"a { dict(x='y') | dict(y='z') } b" 39 + t"a { {'x': 'y'} | dict(y='z') } b" -40 | | note: This is an unsafe fix and may change runtime behavior @@ -553,10 +494,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -38 | t"a {dict(x='y') | dict(y='z')} b" - - t"a { dict(x='y') | dict(y='z') } b" +39 - t"a { dict(x='y') | dict(y='z') } b" 39 + t"a { dict(x='y') | {'y': 'z'} } b" -40 | | note: This is an unsafe fix and may change runtime behavior @@ -572,10 +511,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -44 | # to "π", and "ſ" normalizes to "s". - - dict(ℼ=3.14) +45 - dict(ℼ=3.14) 45 + {"π": 3.14} -46 | dict(ſ=1) | note: This is an unsafe fix and may change runtime behavior @@ -591,10 +528,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -45 | dict(ℼ=3.14) - - dict(ſ=1) +46 - dict(ſ=1) 46 + {"s": 1} -47 | dict(𝕒=1, b=2) | note: This is an unsafe fix and may change runtime behavior @@ -609,10 +544,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -46 | dict(ſ=1) - - dict(𝕒=1, b=2) +47 - dict(𝕒=1, b=2) 47 + {"a": 1, "b": 2} -48 | dict(a=1, b=2) # already NFKC-normalized: unchanged | note: This is an unsafe fix and may change runtime behavior @@ -625,8 +558,7 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | ^^^^^^^^^^^^^^ help: Rewrite as a literal | -47 | dict(𝕒=1, b=2) - - dict(a=1, b=2) # already NFKC-normalized: unchanged +48 - dict(a=1, b=2) # already NFKC-normalized: unchanged 48 + {"a": 1, "b": 2} # already NFKC-normalized: unchanged | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C408_C408.py_allow_dict_calls_with_keyword_arguments.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C408_C408.py_allow_dict_calls_with_keyword_arguments.snap index 3b6bc65b38d59..f95c59c5fddb8 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C408_C408.py_allow_dict_calls_with_keyword_arguments.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C408_C408.py_allow_dict_calls_with_keyword_arguments.snap @@ -11,9 +11,8 @@ C408 [*] Unnecessary `tuple()` call (rewrite as a literal) | help: Rewrite as a literal | - - t = tuple() +1 - t = tuple() 1 + t = () -2 | l = list() | note: This is an unsafe fix and may change runtime behavior @@ -28,10 +27,8 @@ C408 [*] Unnecessary `list()` call (rewrite as a literal) | help: Rewrite as a literal | -1 | t = tuple() - - l = list() +2 - l = list() 2 + l = [] -3 | d1 = dict() | note: This is an unsafe fix and may change runtime behavior @@ -47,10 +44,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -2 | l = list() - - d1 = dict() +3 - d1 = dict() 3 + d1 = {} -4 | d2 = dict(a=1) | note: This is an unsafe fix and may change runtime behavior @@ -65,10 +60,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -15 | f'{dict(x="y")}' - - f"{dict()}" +16 - f"{dict()}" 16 + f"{ {} }" -17 | f"a {dict()} b" | note: This is an unsafe fix and may change runtime behavior @@ -84,10 +77,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -16 | f"{dict()}" - - f"a {dict()} b" +17 - f"a {dict()} b" 17 + f"a { {} } b" -18 | | note: This is an unsafe fix and may change runtime behavior @@ -105,13 +96,9 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -23 | - - dict( 24 + { 25 | # comment - - ) 26 + } -27 | | note: This is an unsafe fix and may change runtime behavior @@ -128,10 +115,8 @@ C408 [*] Unnecessary `tuple()` call (rewrite as a literal) | help: Rewrite as a literal | -27 | - - tuple( # comment -28 + ( # comment -29 | ) +28 ~ ( # comment +29 ~ ) | note: This is an unsafe fix and may change runtime behavior @@ -146,10 +131,8 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -32 | t'{dict(x="y")}' - - t"{dict()}" +33 - t"{dict()}" 33 + t"{ {} }" -34 | t"a {dict()} b" | note: This is an unsafe fix and may change runtime behavior @@ -165,9 +148,7 @@ C408 [*] Unnecessary `dict()` call (rewrite as a literal) | help: Rewrite as a literal | -33 | t"{dict()}" - - t"a {dict()} b" +34 - t"a {dict()} b" 34 + t"a { {} } b" -35 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C409_C409.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C409_C409.py.snap index 96fb283588631..1052eabe26fab 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C409_C409.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C409_C409.py.snap @@ -11,9 +11,8 @@ C409 [*] Unnecessary list literal passed to `tuple()` (rewrite as a tuple litera | help: Rewrite as a tuple literal | - - t1 = tuple([]) +1 - t1 = tuple([]) 1 + t1 = () -2 | t2 = tuple([1, 2]) | note: This is an unsafe fix and may change runtime behavior @@ -28,10 +27,8 @@ C409 [*] Unnecessary list literal passed to `tuple()` (rewrite as a tuple litera | help: Rewrite as a tuple literal | -1 | t1 = tuple([]) - - t2 = tuple([1, 2]) +2 - t2 = tuple([1, 2]) 2 + t2 = (1, 2) -3 | t3 = tuple((1, 2)) | note: This is an unsafe fix and may change runtime behavior @@ -47,10 +44,8 @@ C409 [*] Unnecessary tuple literal passed to `tuple()` (remove the outer call to | help: Remove the outer call to `tuple()` | -2 | t2 = tuple([1, 2]) - - t3 = tuple((1, 2)) +3 - t3 = tuple((1, 2)) 3 + t3 = (1, 2) -4 | t4 = tuple([ | note: This is an unsafe fix and may change runtime behavior @@ -70,14 +65,10 @@ C409 [*] Unnecessary list literal passed to `tuple()` (rewrite as a tuple litera | help: Rewrite as a tuple literal | -3 | t3 = tuple((1, 2)) - - t4 = tuple([ -4 + t4 = ( +4 ~ t4 = ( 5 | 1, 6 | 2 - - ]) 7 + ) -8 | t5 = tuple( | note: This is an unsafe fix and may change runtime behavior @@ -96,12 +87,10 @@ C409 [*] Unnecessary tuple literal passed to `tuple()` (remove the outer call to | help: Remove the outer call to `tuple()` | -7 | ]) - - t5 = tuple( - - (1, 2) - - ) +8 - t5 = tuple( +9 - (1, 2) +10- ) 8 + t5 = (1, 2) -9 | | note: This is an unsafe fix and may change runtime behavior @@ -119,12 +108,10 @@ C409 [*] Unnecessary list literal passed to `tuple()` (rewrite as a tuple litera | help: Rewrite as a tuple literal | -11 | - - tuple( # comment - - [1, 2] - - ) +12 - tuple( # comment +13 - [1, 2] +14 - ) 12 + (1, 2) -13 | | note: This is an unsafe fix and may change runtime behavior @@ -142,13 +129,9 @@ C409 [*] Unnecessary list literal passed to `tuple()` (rewrite as a tuple litera | help: Rewrite as a tuple literal | -15 | - - tuple([ # comment -16 + ( # comment +16 ~ ( # comment 17 | 1, 2 - - ]) 18 + ) -19 | | note: This is an unsafe fix and may change runtime behavior @@ -166,13 +149,9 @@ C409 [*] Unnecessary tuple literal passed to `tuple()` (remove the outer call to | help: Remove the outer call to `tuple()` | -19 | - - tuple(( 20 + ( 21 | 1, - - )) 22 + ) -23 | | note: This is an unsafe fix and may change runtime behavior @@ -188,10 +167,8 @@ C409 [*] Unnecessary list literal passed to `tuple()` (rewrite as a tuple litera | help: Rewrite as a tuple literal | -23 | - - t6 = tuple([1]) +24 - t6 = tuple([1]) 24 + t6 = (1,) -25 | t7 = tuple((1,)) | note: This is an unsafe fix and may change runtime behavior @@ -205,10 +182,8 @@ C409 [*] Unnecessary tuple literal passed to `tuple()` (remove the outer call to | help: Remove the outer call to `tuple()` | -24 | t6 = tuple([1]) - - t7 = tuple((1,)) +25 - t7 = tuple((1,)) 25 + t7 = (1,) -26 | t8 = tuple([1,]) | note: This is an unsafe fix and may change runtime behavior @@ -224,10 +199,8 @@ C409 [*] Unnecessary list literal passed to `tuple()` (rewrite as a tuple litera | help: Rewrite as a tuple literal | -25 | t7 = tuple((1,)) - - t8 = tuple([1,]) +26 - t8 = tuple([1,]) 26 + t8 = (1,) -27 | | note: This is an unsafe fix and may change runtime behavior @@ -242,10 +215,8 @@ C409 [*] Unnecessary list literal passed to `tuple()` (rewrite as a tuple litera | help: Rewrite as a tuple literal | -45 | - - t9 = tuple([1],) +46 - t9 = tuple([1],) 46 + t9 = (1,) -47 | t10 = tuple([1, 2],) | note: This is an unsafe fix and may change runtime behavior @@ -257,8 +228,7 @@ C409 [*] Unnecessary list literal passed to `tuple()` (rewrite as a tuple litera | ^^^^^^^^^^^^^^ help: Rewrite as a tuple literal | -46 | t9 = tuple([1],) - - t10 = tuple([1, 2],) +47 - t10 = tuple([1, 2],) 47 + t10 = (1, 2) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C410_C410.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C410_C410.py.snap index 9e3043db41a48..ed1003db86da8 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C410_C410.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C410_C410.py.snap @@ -11,9 +11,8 @@ C410 [*] Unnecessary list literal passed to `list()` (remove the outer call to ` | help: Remove outer `list()` call | - - l1 = list([1, 2]) +1 - l1 = list([1, 2]) 1 + l1 = [1, 2] -2 | l2 = list((1, 2)) | note: This is an unsafe fix and may change runtime behavior @@ -28,10 +27,8 @@ C410 [*] Unnecessary tuple literal passed to `list()` (rewrite as a single list | help: Rewrite as a single list literal | -1 | l1 = list([1, 2]) - - l2 = list((1, 2)) +2 - l2 = list((1, 2)) 2 + l2 = [1, 2] -3 | l3 = list([]) | note: This is an unsafe fix and may change runtime behavior @@ -46,10 +43,8 @@ C410 [*] Unnecessary list literal passed to `list()` (remove the outer call to ` | help: Remove outer `list()` call | -2 | l2 = list((1, 2)) - - l3 = list([]) +3 - l3 = list([]) 3 + l3 = [] -4 | l4 = list(()) | note: This is an unsafe fix and may change runtime behavior @@ -62,10 +57,8 @@ C410 [*] Unnecessary tuple literal passed to `list()` (rewrite as a single list | ^^^^^^^^ help: Rewrite as a single list literal | -3 | l3 = list([]) - - l4 = list(()) +4 - l4 = list(()) 4 + l4 = [] -5 | | note: This is an unsafe fix and may change runtime behavior @@ -81,12 +74,10 @@ C410 [*] Unnecessary list literal passed to `list()` (remove the outer call to ` | help: Remove outer `list()` call | -6 | - - list( # comment - - [1, 2] - - ) +7 - list( # comment +8 - [1, 2] +9 - ) 7 + [1, 2] -8 | | note: This is an unsafe fix and may change runtime behavior @@ -104,12 +95,8 @@ C410 [*] Unnecessary list literal passed to `list()` (remove the outer call to ` | help: Remove outer `list()` call | -10 | - - list([ # comment -11 + [ # comment +11 | [ # comment 12 | 1, 2 - - ]) -13 + ] -14 | +13 ~ ] | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C411_C411.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C411_C411.py.snap index e1e3cd9678220..b45091b2a3c27 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C411_C411.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C411_C411.py.snap @@ -12,9 +12,7 @@ C411 [*] Unnecessary `list()` call (remove the outer call to `list()`) | help: Remove outer `list()` call | -1 | x = [1, 2, 3] - - list([i for i in x]) +2 - list([i for i in x]) 2 + [i for i in x] -3 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C413_C413.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C413_C413.py.snap index 4acd1d7baeda7..eee08b1ebc9fb 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C413_C413.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C413_C413.py.snap @@ -13,10 +13,8 @@ C413 [*] Unnecessary `list()` call around `sorted()` | help: Remove unnecessary `list()` call | -2 | list(x) - - list(sorted(x)) +3 - list(sorted(x)) 3 + sorted(x) -4 | reversed(sorted(x)) | C413 [*] Unnecessary `reversed()` call around `sorted()` @@ -31,10 +29,8 @@ C413 [*] Unnecessary `reversed()` call around `sorted()` | help: Remove unnecessary `reversed()` call | -3 | list(sorted(x)) - - reversed(sorted(x)) +4 - reversed(sorted(x)) 4 + sorted(x, reverse=True) -5 | reversed(sorted(x, key=lambda e: e)) | note: This is an unsafe fix and may change runtime behavior @@ -50,10 +46,8 @@ C413 [*] Unnecessary `reversed()` call around `sorted()` | help: Remove unnecessary `reversed()` call | -4 | reversed(sorted(x)) - - reversed(sorted(x, key=lambda e: e)) +5 - reversed(sorted(x, key=lambda e: e)) 5 + sorted(x, key=lambda e: e, reverse=True) -6 | reversed(sorted(x, reverse=True)) | note: This is an unsafe fix and may change runtime behavior @@ -69,10 +63,8 @@ C413 [*] Unnecessary `reversed()` call around `sorted()` | help: Remove unnecessary `reversed()` call | -5 | reversed(sorted(x, key=lambda e: e)) - - reversed(sorted(x, reverse=True)) +6 - reversed(sorted(x, reverse=True)) 6 + sorted(x, reverse=False) -7 | reversed(sorted(x, key=lambda e: e, reverse=True)) | note: This is an unsafe fix and may change runtime behavior @@ -88,10 +80,8 @@ C413 [*] Unnecessary `reversed()` call around `sorted()` | help: Remove unnecessary `reversed()` call | -6 | reversed(sorted(x, reverse=True)) - - reversed(sorted(x, key=lambda e: e, reverse=True)) +7 - reversed(sorted(x, key=lambda e: e, reverse=True)) 7 + sorted(x, key=lambda e: e, reverse=False) -8 | reversed(sorted(x, reverse=True, key=lambda e: e)) | note: This is an unsafe fix and may change runtime behavior @@ -107,10 +97,8 @@ C413 [*] Unnecessary `reversed()` call around `sorted()` | help: Remove unnecessary `reversed()` call | -7 | reversed(sorted(x, key=lambda e: e, reverse=True)) - - reversed(sorted(x, reverse=True, key=lambda e: e)) +8 - reversed(sorted(x, reverse=True, key=lambda e: e)) 8 + sorted(x, reverse=False, key=lambda e: e) -9 | reversed(sorted(x, reverse=False)) | note: This is an unsafe fix and may change runtime behavior @@ -125,12 +113,10 @@ C413 [*] Unnecessary `reversed()` call around `sorted()` 11 | reversed(sorted(x, reverse=not x)) | help: Remove unnecessary `reversed()` call - | -8 | reversed(sorted(x, reverse=True, key=lambda e: e)) - - reversed(sorted(x, reverse=False)) -9 + sorted(x, reverse=True) -10 | reversed(sorted(x, reverse=x)) - | + | +9 - reversed(sorted(x, reverse=False)) +9 + sorted(x, reverse=True) + | note: This is an unsafe fix and may change runtime behavior C413 [*] Unnecessary `reversed()` call around `sorted()` @@ -144,10 +130,8 @@ C413 [*] Unnecessary `reversed()` call around `sorted()` | help: Remove unnecessary `reversed()` call | -9 | reversed(sorted(x, reverse=False)) - - reversed(sorted(x, reverse=x)) +10 - reversed(sorted(x, reverse=x)) 10 + sorted(x, reverse=not x) -11 | reversed(sorted(x, reverse=not x)) | note: This is an unsafe fix and may change runtime behavior @@ -163,10 +147,8 @@ C413 [*] Unnecessary `reversed()` call around `sorted()` | help: Remove unnecessary `reversed()` call | -10 | reversed(sorted(x, reverse=x)) - - reversed(sorted(x, reverse=not x)) +11 - reversed(sorted(x, reverse=not x)) 11 + sorted(x, reverse=x) -12 | | note: This is an unsafe fix and may change runtime behavior @@ -180,10 +162,8 @@ C413 [*] Unnecessary `reversed()` call around `sorted()` | help: Remove unnecessary `reversed()` call | -13 | # Regression test for: https://github.com/astral-sh/ruff/issues/7289 - - reversed(sorted(i for i in range(42))) +14 - reversed(sorted(i for i in range(42))) 14 + sorted((i for i in range(42)), reverse=True) -15 | reversed(sorted((i for i in range(42)), reverse=True)) | note: This is an unsafe fix and may change runtime behavior @@ -199,10 +179,8 @@ C413 [*] Unnecessary `reversed()` call around `sorted()` | help: Remove unnecessary `reversed()` call | -14 | reversed(sorted(i for i in range(42))) - - reversed(sorted((i for i in range(42)), reverse=True)) +15 - reversed(sorted((i for i in range(42)), reverse=True)) 15 + sorted((i for i in range(42)), reverse=False) -16 | | note: This is an unsafe fix and may change runtime behavior @@ -216,10 +194,8 @@ C413 [*] Unnecessary `reversed()` call around `sorted()` | help: Remove unnecessary `reversed()` call | -17 | # Regression test for: https://github.com/astral-sh/ruff/issues/10335 - - reversed(sorted([1, 2, 3], reverse=False or True)) +18 - reversed(sorted([1, 2, 3], reverse=False or True)) 18 + sorted([1, 2, 3], reverse=not (False or True)) -19 | reversed(sorted([1, 2, 3], reverse=(False or True))) | note: This is an unsafe fix and may change runtime behavior @@ -235,10 +211,8 @@ C413 [*] Unnecessary `reversed()` call around `sorted()` | help: Remove unnecessary `reversed()` call | -18 | reversed(sorted([1, 2, 3], reverse=False or True)) - - reversed(sorted([1, 2, 3], reverse=(False or True))) +19 - reversed(sorted([1, 2, 3], reverse=(False or True))) 19 + sorted([1, 2, 3], reverse=not (False or True)) -20 | | note: This is an unsafe fix and may change runtime behavior @@ -255,12 +229,8 @@ C413 [*] Unnecessary `reversed()` call around `sorted()` | help: Remove unnecessary `reversed()` call | -23 | # See https://github.com/astral-sh/ruff/issues/15789 - - reversed(sorted - - ("")) 24 + (sorted 25 + ("", reverse=True)) -26 | list(sorted | note: This is an unsafe fix and may change runtime behavior @@ -277,10 +247,8 @@ C413 [*] Unnecessary `list()` call around `sorted()` | help: Remove unnecessary `list()` call | -25 | ("")) - - list(sorted 26 + (sorted -27 | ("")) +27 + ("")) | C413 [*] Unnecessary `list()` call around `sorted()` @@ -293,8 +261,6 @@ C413 [*] Unnecessary `list()` call around `sorted()` | |_______^ help: Remove unnecessary `list()` call | -27 | ("")) - - list(sorted 28 + (sorted -29 | ("xy")) +29 + ("xy")) | diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C414_C414.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C414_C414.py.snap index c2cf4caba8390..b31e540b590cc 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C414_C414.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C414_C414.py.snap @@ -12,10 +12,8 @@ C414 [*] Unnecessary `list()` call within `list()` | help: Remove the inner `list()` call | -1 | x = [1, 2, 3] - - list(list(x)) +2 - list(list(x)) 2 + list(x) -3 | list(tuple(x)) | note: This is an unsafe fix and may change runtime behavior @@ -31,10 +29,8 @@ C414 [*] Unnecessary `tuple()` call within `list()` | help: Remove the inner `tuple()` call | -2 | list(list(x)) - - list(tuple(x)) +3 - list(tuple(x)) 3 + list(x) -4 | tuple(list(x)) | note: This is an unsafe fix and may change runtime behavior @@ -50,10 +46,8 @@ C414 [*] Unnecessary `list()` call within `tuple()` | help: Remove the inner `list()` call | -3 | list(tuple(x)) - - tuple(list(x)) +4 - tuple(list(x)) 4 + tuple(x) -5 | tuple(tuple(x)) | note: This is an unsafe fix and may change runtime behavior @@ -69,10 +63,8 @@ C414 [*] Unnecessary `tuple()` call within `tuple()` | help: Remove the inner `tuple()` call | -4 | tuple(list(x)) - - tuple(tuple(x)) +5 - tuple(tuple(x)) 5 + tuple(x) -6 | set(set(x)) | note: This is an unsafe fix and may change runtime behavior @@ -88,10 +80,8 @@ C414 [*] Unnecessary `set()` call within `set()` | help: Remove the inner `set()` call | -5 | tuple(tuple(x)) - - set(set(x)) +6 - set(set(x)) 6 + set(x) -7 | set(list(x)) | note: This is an unsafe fix and may change runtime behavior @@ -107,10 +97,8 @@ C414 [*] Unnecessary `list()` call within `set()` | help: Remove the inner `list()` call | -6 | set(set(x)) - - set(list(x)) +7 - set(list(x)) 7 + set(x) -8 | set(tuple(x)) | note: This is an unsafe fix and may change runtime behavior @@ -126,10 +114,8 @@ C414 [*] Unnecessary `tuple()` call within `set()` | help: Remove the inner `tuple()` call | -7 | set(list(x)) - - set(tuple(x)) +8 - set(tuple(x)) 8 + set(x) -9 | set(sorted(x)) | note: This is an unsafe fix and may change runtime behavior @@ -144,12 +130,10 @@ C414 [*] Unnecessary `sorted()` call within `set()` 11 | set(reversed(x)) | help: Remove the inner `sorted()` call - | -8 | set(tuple(x)) - - set(sorted(x)) -9 + set(x) -10 | set(sorted(x, key=lambda y: y)) - | + | +9 - set(sorted(x)) +9 + set(x) + | note: This is an unsafe fix and may change runtime behavior C414 [*] Unnecessary `sorted()` call within `set()` @@ -164,10 +148,8 @@ C414 [*] Unnecessary `sorted()` call within `set()` | help: Remove the inner `sorted()` call | -9 | set(sorted(x)) - - set(sorted(x, key=lambda y: y)) +10 - set(sorted(x, key=lambda y: y)) 10 + set(x) -11 | set(reversed(x)) | note: This is an unsafe fix and may change runtime behavior @@ -183,10 +165,8 @@ C414 [*] Unnecessary `reversed()` call within `set()` | help: Remove the inner `reversed()` call | -10 | set(sorted(x, key=lambda y: y)) - - set(reversed(x)) +11 - set(reversed(x)) 11 + set(x) -12 | sorted(list(x)) | note: This is an unsafe fix and may change runtime behavior @@ -202,10 +182,8 @@ C414 [*] Unnecessary `list()` call within `sorted()` | help: Remove the inner `list()` call | -11 | set(reversed(x)) - - sorted(list(x)) +12 - sorted(list(x)) 12 + sorted(x) -13 | sorted(tuple(x)) | note: This is an unsafe fix and may change runtime behavior @@ -221,10 +199,8 @@ C414 [*] Unnecessary `tuple()` call within `sorted()` | help: Remove the inner `tuple()` call | -12 | sorted(list(x)) - - sorted(tuple(x)) +13 - sorted(tuple(x)) 13 + sorted(x) -14 | sorted(sorted(x)) | note: This is an unsafe fix and may change runtime behavior @@ -240,10 +216,8 @@ C414 [*] Unnecessary `sorted()` call within `sorted()` | help: Remove the inner `sorted()` call | -13 | sorted(tuple(x)) - - sorted(sorted(x)) +14 - sorted(sorted(x)) 14 + sorted(x) -15 | sorted(sorted(x, key=foo, reverse=False), reverse=False, key=foo) | note: This is an unsafe fix and may change runtime behavior @@ -259,10 +233,8 @@ C414 [*] Unnecessary `sorted()` call within `sorted()` | help: Remove the inner `sorted()` call | -14 | sorted(sorted(x)) - - sorted(sorted(x, key=foo, reverse=False), reverse=False, key=foo) +15 - sorted(sorted(x, key=foo, reverse=False), reverse=False, key=foo) 15 + sorted(x, reverse=False, key=foo) -16 | sorted(sorted(x, reverse=True), reverse=True) | note: This is an unsafe fix and may change runtime behavior @@ -278,10 +250,8 @@ C414 [*] Unnecessary `sorted()` call within `sorted()` | help: Remove the inner `sorted()` call | -15 | sorted(sorted(x, key=foo, reverse=False), reverse=False, key=foo) - - sorted(sorted(x, reverse=True), reverse=True) +16 - sorted(sorted(x, reverse=True), reverse=True) 16 + sorted(x, reverse=True) -17 | sorted(reversed(x)) | note: This is an unsafe fix and may change runtime behavior @@ -297,10 +267,8 @@ C414 [*] Unnecessary `reversed()` call within `sorted()` | help: Remove the inner `reversed()` call | -16 | sorted(sorted(x, reverse=True), reverse=True) - - sorted(reversed(x)) +17 - sorted(reversed(x)) 17 + sorted(x) -18 | sorted(list(x), key=lambda y: y) | note: This is an unsafe fix and may change runtime behavior @@ -316,10 +284,8 @@ C414 [*] Unnecessary `list()` call within `sorted()` | help: Remove the inner `list()` call | -17 | sorted(reversed(x)) - - sorted(list(x), key=lambda y: y) +18 - sorted(list(x), key=lambda y: y) 18 + sorted(x, key=lambda y: y) -19 | tuple( | note: This is an unsafe fix and may change runtime behavior @@ -340,13 +306,10 @@ C414 [*] Unnecessary `list()` call within `tuple()` | help: Remove the inner `list()` call | -19 | tuple( - - list( - - [x, 3, "hell"\ +19 + tuple( 20 + [x, 3, "hell"\ -21 | "o"] - - ) -22 | ) +21 + "o"] +22 + ) | note: This is an unsafe fix and may change runtime behavior @@ -362,10 +325,8 @@ C414 [*] Unnecessary `set()` call within `set()` | help: Remove the inner `set()` call | -24 | ) - - set(set()) +25 - set(set()) 25 + set() -26 | set(list()) | note: This is an unsafe fix and may change runtime behavior @@ -381,10 +342,8 @@ C414 [*] Unnecessary `list()` call within `set()` | help: Remove the inner `list()` call | -25 | set(set()) - - set(list()) +26 - set(list()) 26 + set() -27 | set(tuple()) | note: This is an unsafe fix and may change runtime behavior @@ -399,10 +358,8 @@ C414 [*] Unnecessary `tuple()` call within `set()` | help: Remove the inner `tuple()` call | -26 | set(list()) - - set(tuple()) +27 - set(tuple()) 27 + set() -28 | sorted(reversed()) | note: This is an unsafe fix and may change runtime behavior @@ -418,10 +375,8 @@ C414 [*] Unnecessary `reversed()` call within `sorted()` | help: Remove the inner `reversed()` call | -27 | set(tuple()) - - sorted(reversed()) +28 - sorted(reversed()) 28 + sorted() -29 | | note: This is an unsafe fix and may change runtime behavior @@ -442,10 +397,12 @@ C414 [*] Unnecessary `list()` call within `sorted()` | help: Remove the inner `list()` call | -37 | xxxxxxxxxxx_xxxxx_xxxxx = sorted( - - list(x_xxxx_xxxxxxxxxxx_xxxxx.xxxx()), +37 ~ xxxxxxxxxxx_xxxxx_xxxxx = sorted( 38 + x_xxxx_xxxxxxxxxxx_xxxxx.xxxx(), -39 | # xxxxxxxxxxx xxxxx xxxx xxx xx Nxxx, xxx xxxxxx3 xxxxxxxxx xx +39 + # xxxxxxxxxxx xxxxx xxxx xxx xx Nxxx, xxx xxxxxx3 xxxxxxxxx xx +40 + # xx xxxx xxxxxxx xxxx xxx xxxxxxxx Nxxx +41 + key=lambda xxxxx: xxxxx or "", +42 + ) | note: This is an unsafe fix and may change runtime behavior @@ -462,9 +419,9 @@ C414 [*] Unnecessary `list()` call within `sorted()` | |_^ help: Remove the inner `list()` call | -44 | xxxxxxxxxxx_xxxxx_xxxxx = sorted( - - list(x_xxxx_xxxxxxxxxxx_xxxxx.xxxx()), # xxxxxxxxxxx xxxxx xxxx xxx xx Nxxx +44 ~ xxxxxxxxxxx_xxxxx_xxxxx = sorted( 45 + x_xxxx_xxxxxxxxxxx_xxxxx.xxxx(), # xxxxxxxxxxx xxxxx xxxx xxx xx Nxxx -46 | key=lambda xxxxx: xxxxx or "", +46 + key=lambda xxxxx: xxxxx or "", +47 + ) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C416_C416.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C416_C416.py.snap index 288387b5a0f24..0296bfb04e178 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C416_C416.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C416_C416.py.snap @@ -13,10 +13,8 @@ C416 [*] Unnecessary list comprehension (rewrite using `list()`) | help: Rewrite using `list()` | -5 | - - [i for i in x] +6 - [i for i in x] 6 + list(x) -7 | {i for i in x} | note: This is an unsafe fix and may change runtime behavior @@ -31,10 +29,8 @@ C416 [*] Unnecessary set comprehension (rewrite using `set()`) | help: Rewrite using `set()` | -6 | [i for i in x] - - {i for i in x} +7 - {i for i in x} 7 + set(x) -8 | {k: v for k, v in y} | note: This is an unsafe fix and may change runtime behavior @@ -50,10 +46,8 @@ C416 [*] Unnecessary dict comprehension (rewrite using `dict()`) | help: Rewrite using `dict()` | -7 | {i for i in x} - - {k: v for k, v in y} +8 - {k: v for k, v in y} 8 + dict(y) -9 | {k: v for k, v in d.items()} | note: This is an unsafe fix and may change runtime behavior @@ -68,12 +62,10 @@ C416 [*] Unnecessary dict comprehension (rewrite using `dict()`) 11 | [(k, v) for [k, v] in d.items()] | help: Rewrite using `dict()` - | -8 | {k: v for k, v in y} - - {k: v for k, v in d.items()} -9 + dict(d.items()) -10 | [(k, v) for k, v in d.items()] - | + | +9 - {k: v for k, v in d.items()} +9 + dict(d.items()) + | note: This is an unsafe fix and may change runtime behavior C416 [*] Unnecessary list comprehension (rewrite using `list()`) @@ -88,10 +80,8 @@ C416 [*] Unnecessary list comprehension (rewrite using `list()`) | help: Rewrite using `list()` | -9 | {k: v for k, v in d.items()} - - [(k, v) for k, v in d.items()] +10 - [(k, v) for k, v in d.items()] 10 + list(d.items()) -11 | [(k, v) for [k, v] in d.items()] | note: This is an unsafe fix and may change runtime behavior @@ -106,10 +96,8 @@ C416 [*] Unnecessary list comprehension (rewrite using `list()`) | help: Rewrite using `list()` | -10 | [(k, v) for k, v in d.items()] - - [(k, v) for [k, v] in d.items()] +11 - [(k, v) for [k, v] in d.items()] 11 + list(d.items()) -12 | {k: (a, b) for k, (a, b) in d.items()} | note: This is an unsafe fix and may change runtime behavior @@ -124,9 +112,7 @@ C416 [*] Unnecessary list comprehension (rewrite using `list()`) | help: Rewrite using `list()` | -24 | # Regression test for: https://github.com/astral-sh/ruff/issues/7196 - - any(len(symbol_table.get_by_type(symbol_type)) > 0 for symbol_type in[t for t in SymbolType]) +25 - any(len(symbol_table.get_by_type(symbol_type)) > 0 for symbol_type in[t for t in SymbolType]) 25 + any(len(symbol_table.get_by_type(symbol_type)) > 0 for symbol_type in list(SymbolType)) -26 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C417_C417.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C417_C417.py.snap index 26214dbd82064..32adac8876ed7 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C417_C417.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C417_C417.py.snap @@ -13,10 +13,8 @@ C417 [*] Unnecessary `map()` usage (rewrite using a generator expression) | help: Replace `map()` with a generator expression | -2 | nums = [1, 2, 3] - - map(lambda x: x + 1, nums) +3 - map(lambda x: x + 1, nums) 3 + (x + 1 for x in nums) -4 | map(lambda x: str(x), nums) | note: This is an unsafe fix and may change runtime behavior @@ -32,10 +30,8 @@ C417 [*] Unnecessary `map()` usage (rewrite using a generator expression) | help: Replace `map()` with a generator expression | -3 | map(lambda x: x + 1, nums) - - map(lambda x: str(x), nums) +4 - map(lambda x: str(x), nums) 4 + (str(x) for x in nums) -5 | list(map(lambda x: x * 2, nums)) | note: This is an unsafe fix and may change runtime behavior @@ -51,10 +47,8 @@ C417 [*] Unnecessary `map()` usage (rewrite using a list comprehension) | help: Replace `map()` with a list comprehension | -4 | map(lambda x: str(x), nums) - - list(map(lambda x: x * 2, nums)) +5 - list(map(lambda x: x * 2, nums)) 5 + [x * 2 for x in nums] -6 | set(map(lambda x: x % 2 == 0, nums)) | note: This is an unsafe fix and may change runtime behavior @@ -70,10 +64,8 @@ C417 [*] Unnecessary `map()` usage (rewrite using a set comprehension) | help: Replace `map()` with a set comprehension | -5 | list(map(lambda x: x * 2, nums)) - - set(map(lambda x: x % 2 == 0, nums)) +6 - set(map(lambda x: x % 2 == 0, nums)) 6 + {x % 2 == 0 for x in nums} -7 | dict(map(lambda v: (v, v**2), nums)) | note: This is an unsafe fix and may change runtime behavior @@ -88,10 +80,8 @@ C417 [*] Unnecessary `map()` usage (rewrite using a dict comprehension) | help: Replace `map()` with a dict comprehension | -6 | set(map(lambda x: x % 2 == 0, nums)) - - dict(map(lambda v: (v, v**2), nums)) +7 - dict(map(lambda v: (v, v**2), nums)) 7 + {v: v**2 for v in nums} -8 | dict(map(lambda v: [v, v**2], nums)) | note: This is an unsafe fix and may change runtime behavior @@ -107,10 +97,8 @@ C417 [*] Unnecessary `map()` usage (rewrite using a dict comprehension) | help: Replace `map()` with a dict comprehension | -7 | dict(map(lambda v: (v, v**2), nums)) - - dict(map(lambda v: [v, v**2], nums)) +8 - dict(map(lambda v: [v, v**2], nums)) 8 + {v: v**2 for v in nums} -9 | | note: This is an unsafe fix and may change runtime behavior @@ -126,10 +114,8 @@ C417 [*] Unnecessary `map()` usage (rewrite using a generator expression) | help: Replace `map()` with a generator expression | -9 | - - map(lambda _: 3.0, nums) +10 - map(lambda _: 3.0, nums) 10 + (3.0 for _ in nums) -11 | _ = "".join(map(lambda x: x in nums and "1" or "0", range(123))) | note: This is an unsafe fix and may change runtime behavior @@ -144,10 +130,8 @@ C417 [*] Unnecessary `map()` usage (rewrite using a generator expression) | help: Replace `map()` with a generator expression | -10 | map(lambda _: 3.0, nums) - - _ = "".join(map(lambda x: x in nums and "1" or "0", range(123))) +11 - _ = "".join(map(lambda x: x in nums and "1" or "0", range(123))) 11 + _ = "".join((x in nums and "1" or "0" for x in range(123))) -12 | all(map(lambda v: isinstance(v, dict), nums)) | note: This is an unsafe fix and may change runtime behavior @@ -162,10 +146,8 @@ C417 [*] Unnecessary `map()` usage (rewrite using a generator expression) | help: Replace `map()` with a generator expression | -11 | _ = "".join(map(lambda x: x in nums and "1" or "0", range(123))) - - all(map(lambda v: isinstance(v, dict), nums)) +12 - all(map(lambda v: isinstance(v, dict), nums)) 12 + all((isinstance(v, dict) for v in nums)) -13 | filter(func, map(lambda v: v, nums)) | note: This is an unsafe fix and may change runtime behavior @@ -178,10 +160,8 @@ C417 [*] Unnecessary `map()` usage (rewrite using a generator expression) | ^^^^^^^^^^^^^^^^^^^^^^ help: Replace `map()` with a generator expression | -12 | all(map(lambda v: isinstance(v, dict), nums)) - - filter(func, map(lambda v: v, nums)) +13 - filter(func, map(lambda v: v, nums)) 13 + filter(func, (v for v in nums)) -14 | | note: This is an unsafe fix and may change runtime behavior @@ -195,10 +175,8 @@ C417 [*] Unnecessary `map()` usage (rewrite using a set comprehension) | help: Replace `map()` with a set comprehension | -16 | # When inside f-string, then the fix should be surrounded by whitespace - - _ = f"{set(map(lambda x: x % 2 == 0, nums))}" +17 - _ = f"{set(map(lambda x: x % 2 == 0, nums))}" 17 + _ = f"{ {x % 2 == 0 for x in nums} }" -18 | _ = f"{dict(map(lambda v: (v, v**2), nums))}" | note: This is an unsafe fix and may change runtime behavior @@ -214,10 +192,8 @@ C417 [*] Unnecessary `map()` usage (rewrite using a dict comprehension) | help: Replace `map()` with a dict comprehension | -17 | _ = f"{set(map(lambda x: x % 2 == 0, nums))}" - - _ = f"{dict(map(lambda v: (v, v**2), nums))}" +18 - _ = f"{dict(map(lambda v: (v, v**2), nums))}" 18 + _ = f"{ {v: v**2 for v in nums} }" -19 | | note: This is an unsafe fix and may change runtime behavior @@ -232,10 +208,8 @@ C417 [*] Unnecessary `map()` usage (rewrite using a generator expression) | help: Replace `map()` with a generator expression | -35 | # Error: the `x` is overridden by the inner lambda. - - map(lambda x: lambda x: x, range(4)) +36 - map(lambda x: lambda x: x, range(4)) 36 + (lambda x: x for x in range(4)) -37 | | note: This is an unsafe fix and may change runtime behavior @@ -250,10 +224,8 @@ C417 [*] Unnecessary `map()` usage (rewrite using a generator expression) | help: Replace `map()` with a generator expression | -46 | # Regression test for: https://github.com/astral-sh/ruff/issues/7121 - - map(lambda x: x, y if y else z) +47 - map(lambda x: x, y if y else z) 47 + (x for x in (y if y else z)) -48 | map(lambda x: x, (y if y else z)) | note: This is an unsafe fix and may change runtime behavior @@ -268,10 +240,8 @@ C417 [*] Unnecessary `map()` usage (rewrite using a generator expression) | help: Replace `map()` with a generator expression | -47 | map(lambda x: x, y if y else z) - - map(lambda x: x, (y if y else z)) +48 - map(lambda x: x, (y if y else z)) 48 + (x for x in (y if y else z)) -49 | map(lambda x: x, (x, y, z)) | note: This is an unsafe fix and may change runtime behavior @@ -287,10 +257,8 @@ C417 [*] Unnecessary `map()` usage (rewrite using a generator expression) | help: Replace `map()` with a generator expression | -48 | map(lambda x: x, (y if y else z)) - - map(lambda x: x, (x, y, z)) +49 - map(lambda x: x, (x, y, z)) 49 + (x for x in (x, y, z)) -50 | | note: This is an unsafe fix and may change runtime behavior @@ -304,10 +272,8 @@ C417 [*] Unnecessary `map()` usage (rewrite using a set comprehension) | help: Replace `map()` with a set comprehension | -74 | # When inside t-string, then the fix should be surrounded by whitespace - - _ = t"{set(map(lambda x: x % 2 == 0, nums))}" +75 - _ = t"{set(map(lambda x: x % 2 == 0, nums))}" 75 + _ = t"{ {x % 2 == 0 for x in nums} }" -76 | _ = t"{dict(map(lambda v: (v, v**2), nums))}" | note: This is an unsafe fix and may change runtime behavior @@ -320,9 +286,7 @@ C417 [*] Unnecessary `map()` usage (rewrite using a dict comprehension) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace `map()` with a dict comprehension | -75 | _ = t"{set(map(lambda x: x % 2 == 0, nums))}" - - _ = t"{dict(map(lambda v: (v, v**2), nums))}" +76 - _ = t"{dict(map(lambda v: (v, v**2), nums))}" 76 + _ = t"{ {v: v**2 for v in nums} }" -77 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C417_C417_1.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C417_C417_1.py.snap index bf25050df0615..da34dbd2046f8 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C417_C417_1.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C417_C417_1.py.snap @@ -10,9 +10,7 @@ C417 [*] Unnecessary `map()` usage (rewrite using a generator expression) | ^^^^^^^^^^^^^^^^^^^^ help: Replace `map()` with a generator expression | -6 | list = ... - - list(map(lambda x: x, [])) +7 - list(map(lambda x: x, [])) 7 + list((x for x in [])) -8 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C418_C418.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C418_C418.py.snap index 06e4846d5a216..e1919d8adc00d 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C418_C418.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C418_C418.py.snap @@ -11,9 +11,8 @@ C418 [*] Unnecessary dict literal passed to `dict()` (remove the outer call to ` | help: Remove outer `dict()` call | - - dict({}) +1 - dict({}) 1 + {} -2 | dict({'a': 1}) | note: This is an unsafe fix and may change runtime behavior @@ -28,10 +27,8 @@ C418 [*] Unnecessary dict literal passed to `dict()` (remove the outer call to ` | help: Remove outer `dict()` call | -1 | dict({}) - - dict({'a': 1}) +2 - dict({'a': 1}) 2 + {'a': 1} -3 | dict({'x': 1 for x in range(10)}) | note: This is an unsafe fix and may change runtime behavior @@ -47,10 +44,8 @@ C418 [*] Unnecessary dict comprehension passed to `dict()` (remove the outer cal | help: Remove outer `dict()` call | -2 | dict({'a': 1}) - - dict({'x': 1 for x in range(10)}) +3 - dict({'x': 1 for x in range(10)}) 3 + {'x': 1 for x in range(10)} -4 | dict( | note: This is an unsafe fix and may change runtime behavior @@ -68,11 +63,9 @@ C418 [*] Unnecessary dict comprehension passed to `dict()` (remove the outer cal | help: Remove outer `dict()` call | -3 | dict({'x': 1 for x in range(10)}) - - dict( - - {'x': 1 for x in range(10)} - - ) +4 - dict( +5 - {'x': 1 for x in range(10)} +6 - ) 4 + {'x': 1 for x in range(10)} -5 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C419_C419.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C419_C419.py.snap index 37bcb8a49ff16..098f2e0590f0a 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C419_C419.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C419_C419.py.snap @@ -11,9 +11,8 @@ C419 [*] Unnecessary list comprehension | help: Remove unnecessary comprehension | - - any([x.id for x in bar]) +1 - any([x.id for x in bar]) 1 + any(x.id for x in bar) -2 | all([x.id for x in bar]) | note: This is an unsafe fix and may change runtime behavior @@ -28,10 +27,8 @@ C419 [*] Unnecessary list comprehension | help: Remove unnecessary comprehension | -1 | any([x.id for x in bar]) - - all([x.id for x in bar]) +2 - all([x.id for x in bar]) 2 + all(x.id for x in bar) -3 | any( # first comment | note: This is an unsafe fix and may change runtime behavior @@ -47,10 +44,9 @@ C419 [*] Unnecessary list comprehension | help: Remove unnecessary comprehension | -3 | any( # first comment - - [x.id for x in bar], # second comment +3 + any( # first comment 4 + x.id for x in bar # second comment -5 | ) # third comment +5 ~ ) # third comment | note: This is an unsafe fix and may change runtime behavior @@ -66,10 +62,9 @@ C419 [*] Unnecessary list comprehension | help: Remove unnecessary comprehension | -6 | all( # first comment - - [x.id for x in bar], # second comment +6 + all( # first comment 7 + x.id for x in bar # second comment -8 | ) # third comment +8 ~ ) # third comment | note: This is an unsafe fix and may change runtime behavior @@ -84,12 +79,10 @@ C419 [*] Unnecessary set comprehension 11 | # OK | help: Remove unnecessary comprehension - | -8 | ) # third comment - - any({x.id for x in bar}) -9 + any(x.id for x in bar) -10 | - | + | +9 - any({x.id for x in bar}) +9 + any(x.id for x in bar) + | note: This is an unsafe fix and may change runtime behavior C419 [*] Unnecessary list comprehension @@ -109,18 +102,14 @@ C419 [*] Unnecessary list comprehension | help: Remove unnecessary comprehension | -27 | any( - - [ # lbracket comment - - # second line comment - - i.bit_count() +27 + any( 28 + # lbracket comment 29 + # second line comment 30 + i.bit_count() -31 | # random middle comment - - for i in range(5) # rbracket comment - - ] # rpar comment +31 + # random middle comment 32 + for i in range(5) # rbracket comment # rpar comment -33 | # trailing comment +33 + # trailing comment +34 + ) | note: This is an unsafe fix and may change runtime behavior @@ -139,16 +128,11 @@ C419 [*] Unnecessary list comprehension | help: Remove unnecessary comprehension | -38 | # on the same line. - - any([ # lbracket comment - - # second line comment - - i.bit_count() for i in range(5) # rbracket comment - - ] # rpar comment 39 + any( 40 + # lbracket comment 41 + # second line comment 42 + i.bit_count() for i in range(5) # rbracket comment # rpar comment -43 | ) +43 + ) | note: This is an unsafe fix and may change runtime behavior @@ -162,10 +146,8 @@ C419 [*] Unnecessary set comprehension | help: Remove unnecessary comprehension | -48 | # should be linted... - - any({x.id for x in bar}) +49 - any({x.id for x in bar}) 49 + any(x.id for x in bar) -50 | all({x.id for x in bar}) | note: This is an unsafe fix and may change runtime behavior @@ -181,9 +163,7 @@ C419 [*] Unnecessary set comprehension | help: Remove unnecessary comprehension | -49 | any({x.id for x in bar}) - - all({x.id for x in bar}) +50 - all({x.id for x in bar}) 50 + all(x.id for x in bar) -51 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C420_C420.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C420_C420.py.snap index a851b26c1f851..bc65244adb9b9 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C420_C420.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C420_C420.py.snap @@ -10,10 +10,8 @@ C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instea | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `dict.fromkeys(iterable, value)`) | -5 | numbers = [1, 2, 3] - - {n: None for n in numbers} # RUF025 +6 - {n: None for n in numbers} # RUF025 6 + dict.fromkeys(numbers) # RUF025 -7 | | C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instead @@ -26,10 +24,8 @@ C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instea | help: Replace with `dict.fromkeys(iterable)`) | -9 | def func(): - - for key, value in {n: 1 for n in [1, 2, 3]}.items(): # RUF025 +10 - for key, value in {n: 1 for n in [1, 2, 3]}.items(): # RUF025 10 + for key, value in dict.fromkeys([1, 2, 3], 1).items(): # RUF025 -11 | pass | C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instead @@ -40,10 +36,8 @@ C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instea | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `dict.fromkeys(iterable)`) | -14 | def func(): - - {n: 1.1 for n in [1, 2, 3]} # RUF025 +15 - {n: 1.1 for n in [1, 2, 3]} # RUF025 15 + dict.fromkeys([1, 2, 3], 1.1) # RUF025 -16 | | C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instead @@ -55,10 +49,8 @@ C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instea | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `dict.fromkeys(iterable)`) | -25 | - - f({c: "a" for c in "12345"}) # RUF025 +26 - f({c: "a" for c in "12345"}) # RUF025 26 + f(dict.fromkeys("12345", "a")) # RUF025 -27 | | C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instead @@ -69,10 +61,8 @@ C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instea | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `dict.fromkeys(iterable)`) | -29 | def func(): - - {n: True for n in [1, 2, 2]} # RUF025 +30 - {n: True for n in [1, 2, 2]} # RUF025 30 + dict.fromkeys([1, 2, 2], True) # RUF025 -31 | | C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instead @@ -83,10 +73,8 @@ C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instea | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `dict.fromkeys(iterable)`) | -33 | def func(): - - {n: b"hello" for n in (1, 2, 2)} # RUF025 +34 - {n: b"hello" for n in (1, 2, 2)} # RUF025 34 + dict.fromkeys((1, 2, 2), b"hello") # RUF025 -35 | | C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instead @@ -97,10 +85,8 @@ C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instea | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `dict.fromkeys(iterable)`) | -37 | def func(): - - {n: ... for n in [1, 2, 3]} # RUF025 +38 - {n: ... for n in [1, 2, 3]} # RUF025 38 + dict.fromkeys([1, 2, 3], ...) # RUF025 -39 | | C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instead @@ -111,10 +97,8 @@ C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instea | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `dict.fromkeys(iterable)`) | -41 | def func(): - - {n: False for n in {1: "a", 2: "b"}} # RUF025 +42 - {n: False for n in {1: "a", 2: "b"}} # RUF025 42 + dict.fromkeys({1: "a", 2: "b"}, False) # RUF025 -43 | | C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instead @@ -125,10 +109,8 @@ C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instea | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `dict.fromkeys(iterable)`) | -45 | def func(): - - {(a, b): 1 for (a, b) in [(1, 2), (3, 4)]} # RUF025 +46 - {(a, b): 1 for (a, b) in [(1, 2), (3, 4)]} # RUF025 46 + dict.fromkeys([(1, 2), (3, 4)], 1) # RUF025 -47 | | C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instead @@ -139,10 +121,8 @@ C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instea | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `dict.fromkeys(iterable)`) | -53 | a = f() - - {n: a for n in [1, 2, 3]} # RUF025 +54 - {n: a for n in [1, 2, 3]} # RUF025 54 + dict.fromkeys([1, 2, 3], a) # RUF025 -55 | | C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instead @@ -154,10 +134,8 @@ C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instea | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `dict.fromkeys(iterable)`) | -58 | values = ["a", "b", "c"] - - [{n: values for n in [1, 2, 3]}] # RUF025 +59 - [{n: values for n in [1, 2, 3]}] # RUF025 59 + [dict.fromkeys([1, 2, 3], values)] # RUF025 -60 | | C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instead @@ -175,17 +153,16 @@ C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instea 103 | | } # 9 | |_^ help: Replace with `dict.fromkeys(iterable, value)`) - | -94 | # https://github.com/astral-sh/ruff/issues/18764 - - { # 1 - - a # 2 - - : # 3 - - None # 4 - - for # 5 - - a # 6 - - in # 7 - - iterable # 8 - - } # 9 -95 + dict.fromkeys(iterable) # 9 - | + | + 95 - { # 1 + 96 - a # 2 + 97 - : # 3 + 98 - None # 4 + 99 - for # 5 +100 - a # 6 +101 - in # 7 +102 - iterable # 8 +103 - } # 9 + 95 + dict.fromkeys(iterable) # 9 + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C420_C420_1.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C420_C420_1.py.snap index e979590b6e839..afbe4d620780b 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C420_C420_1.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C420_C420_1.py.snap @@ -8,7 +8,6 @@ C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instea | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `dict.fromkeys(iterable)`) | - - {x: NotImplemented for x in "XY"} +1 - {x: NotImplemented for x in "XY"} 1 + dict.fromkeys("XY", NotImplemented) -2 | | diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C420_C420_2.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C420_C420_2.py.snap index 76e3b9d9f5249..814401e078f72 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C420_C420_2.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__C420_C420_2.py.snap @@ -8,7 +8,6 @@ C420 [*] Unnecessary dict comprehension for iterable; use `dict.fromkeys` instea | ^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `dict.fromkeys(iterable, value)`) | - - foo or{x: None for x in bar} +1 - foo or{x: None for x in bar} 1 + foo or dict.fromkeys(bar) -2 | | diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__preview__C419_C419_1.py.snap b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__preview__C419_C419_1.py.snap index c56d82cc8a3a2..c2cdc006ab8e9 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__preview__C419_C419_1.py.snap +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/snapshots/ruff_linter__rules__flake8_comprehensions__tests__preview__C419_C419_1.py.snap @@ -11,9 +11,8 @@ C419 [*] Unnecessary list comprehension | help: Remove unnecessary comprehension | - - sum([x.val for x in bar]) +1 - sum([x.val for x in bar]) 1 + sum(x.val for x in bar) -2 | min([x.val for x in bar]) | note: This is an unsafe fix and may change runtime behavior @@ -28,10 +27,8 @@ C419 [*] Unnecessary list comprehension | help: Remove unnecessary comprehension | -1 | sum([x.val for x in bar]) - - min([x.val for x in bar]) +2 - min([x.val for x in bar]) 2 + min(x.val for x in bar) -3 | max([x.val for x in bar]) | note: This is an unsafe fix and may change runtime behavior @@ -46,10 +43,8 @@ C419 [*] Unnecessary list comprehension | help: Remove unnecessary comprehension | -2 | min([x.val for x in bar]) - - max([x.val for x in bar]) +3 - max([x.val for x in bar]) 3 + max(x.val for x in bar) -4 | sum([x.val for x in bar], 0) | note: This is an unsafe fix and may change runtime behavior @@ -65,10 +60,8 @@ C419 [*] Unnecessary list comprehension | help: Remove unnecessary comprehension | -3 | max([x.val for x in bar]) - - sum([x.val for x in bar], 0) +4 - sum([x.val for x in bar], 0) 4 + sum((x.val for x in bar), 0) -5 | | note: This is an unsafe fix and may change runtime behavior @@ -88,14 +81,10 @@ C419 [*] Unnecessary list comprehension | help: Remove unnecessary comprehension | -13 | sum( - - [ -14 + ( +14 ~ ( 15 | delta 16 | for delta in timedelta_list 17 | if delta - - ], -18 + ), -19 | dt.timedelta(), +18 ~ ), | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_errmsg/snapshots/ruff_linter__rules__flake8_errmsg__tests__custom.snap b/crates/ruff_linter/src/rules/flake8_errmsg/snapshots/ruff_linter__rules__flake8_errmsg__tests__custom.snap index 845ebe42ea5bb..91dd45c050efd 100644 --- a/crates/ruff_linter/src/rules/flake8_errmsg/snapshots/ruff_linter__rules__flake8_errmsg__tests__custom.snap +++ b/crates/ruff_linter/src/rules/flake8_errmsg/snapshots/ruff_linter__rules__flake8_errmsg__tests__custom.snap @@ -9,11 +9,8 @@ EM101 [*] Exception must not use a string literal, assign to variable first | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Assign to variable; remove string literal | -4 | def f_a(): - - raise RuntimeError("This is an example exception") -5 + msg = "This is an example exception" -6 + raise RuntimeError(msg) -7 | +5 ~ msg = "This is an example exception" +6 ~ raise RuntimeError(msg) | note: This is an unsafe fix and may change runtime behavior @@ -26,11 +23,8 @@ EM102 [*] Exception must not use an f-string literal, assign to variable first | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Assign to variable; remove f-string literal | -17 | example = "example" - - raise RuntimeError(f"This is an {example} exception") -18 + msg = f"This is an {example} exception" -19 + raise RuntimeError(msg) -20 | +18 ~ msg = f"This is an {example} exception" +19 ~ raise RuntimeError(msg) | note: This is an unsafe fix and may change runtime behavior @@ -42,11 +36,8 @@ EM103 [*] Exception must not use a `.format()` string directly, assign to variab | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Assign to variable; remove `.format()` string | -21 | def f_c(): - - raise RuntimeError("This is an {example} exception".format(example="example")) -22 + msg = "This is an {example} exception".format(example="example") -23 + raise RuntimeError(msg) -24 | +22 ~ msg = "This is an {example} exception".format(example="example") +23 ~ raise RuntimeError(msg) | note: This is an unsafe fix and may change runtime behavior @@ -59,11 +50,8 @@ EM101 [*] Exception must not use a string literal, assign to variable first | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Assign to variable; remove string literal | -31 | msg = "hello" - - raise RuntimeError("This is an example exception") -32 + msg_0 = "This is an example exception" -33 + raise RuntimeError(msg_0) -34 | +32 ~ msg_0 = "This is an example exception" +33 ~ raise RuntimeError(msg_0) | note: This is an unsafe fix and may change runtime behavior @@ -76,11 +64,8 @@ EM101 [*] Exception must not use a string literal, assign to variable first | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Assign to variable; remove string literal | -38 | - - raise RuntimeError("This is an example exception") -39 + msg = "This is an example exception" -40 + raise RuntimeError(msg) -41 | +39 ~ msg = "This is an example exception" +40 ~ raise RuntimeError(msg) | note: This is an unsafe fix and may change runtime behavior @@ -92,11 +77,8 @@ EM101 [*] Exception must not use a string literal, assign to variable first | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Assign to variable; remove string literal | -45 | def nested(): - - raise RuntimeError("This is an example exception") -46 + msg_0 = "This is an example exception" -47 + raise RuntimeError(msg_0) -48 | +46 ~ msg_0 = "This is an example exception" +47 ~ raise RuntimeError(msg_0) | note: This is an unsafe fix and may change runtime behavior @@ -112,11 +94,8 @@ EM101 [*] Exception must not use a string literal, assign to variable first | help: Assign to variable; remove string literal | -50 | if foo: - - raise RuntimeError("This is an example exception") -51 + msg = "This is an example exception" -52 + raise RuntimeError(msg) -53 | else: +51 ~ msg = "This is an example exception" +52 ~ raise RuntimeError(msg) | note: This is an unsafe fix and may change runtime behavior @@ -131,11 +110,8 @@ EM102 [*] Exception must not use an f-string literal, assign to variable first | help: Assign to variable; remove f-string literal | -53 | if foo == "foo": - - raise RuntimeError(f"This is an exception: {foo}") -54 + msg = f"This is an exception: {foo}" -55 + raise RuntimeError(msg) -56 | raise RuntimeError("This is an exception: {}".format(foo)) +54 ~ msg = f"This is an exception: {foo}" +55 ~ raise RuntimeError(msg) | note: This is an unsafe fix and may change runtime behavior @@ -148,11 +124,8 @@ EM103 [*] Exception must not use a `.format()` string directly, assign to variab | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Assign to variable; remove `.format()` string | -54 | raise RuntimeError(f"This is an exception: {foo}") - - raise RuntimeError("This is an exception: {}".format(foo)) -55 + msg = "This is an exception: {}".format(foo) -56 + raise RuntimeError(msg) -57 | +55 ~ msg = "This is an exception: {}".format(foo) +56 ~ raise RuntimeError(msg) | note: This is an unsafe fix and may change runtime behavior @@ -183,11 +156,8 @@ EM102 [*] Exception must not use an f-string literal, assign to variable first | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Assign to variable; remove f-string literal | -63 | def f_triple_quoted_string(): - - raise RuntimeError(f"""This is an {"example"} exception""") -64 + msg = f"""This is an {"example"} exception""" -65 + raise RuntimeError(msg) -66 | +64 ~ msg = f"""This is an {"example"} exception""" +65 ~ raise RuntimeError(msg) | note: This is an unsafe fix and may change runtime behavior @@ -204,17 +174,13 @@ EM103 [*] Exception must not use a `.format()` string directly, assign to variab | help: Assign to variable; remove `.format()` string | -74 | def f_multi_line_string2(): - - raise RuntimeError( -75 + msg = ( -76 | "This is an {example} exception".format( -77 | example="example" -78 | ) -79 | ) -80 + raise RuntimeError( -81 + msg -82 + ) -83 | +75 ~ msg = ( +76 + "This is an {example} exception".format( +77 + example="example" +78 + ) +79 + ) +80 ~ raise RuntimeError( +81 ~ msg | note: This is an unsafe fix and may change runtime behavior @@ -234,15 +200,15 @@ EM103 [*] Exception must not use a `.format()` string directly, assign to variab | help: Assign to variable; remove `.format()` string | -82 | def f_multi_line_string2(): - - raise RuntimeError( -83 + msg = ( -84 | ( --------------------------------------------------------------------------------- -90 | ) -91 + raise RuntimeError( -92 + msg -93 + ) -94 | +83 ~ msg = ( +84 + ( +85 + "This is an " +86 + "{example} exception" +87 + ).format( +88 + example="example" +89 + ) +90 + ) +91 ~ raise RuntimeError( +92 ~ msg | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_errmsg/snapshots/ruff_linter__rules__flake8_errmsg__tests__defaults.snap b/crates/ruff_linter/src/rules/flake8_errmsg/snapshots/ruff_linter__rules__flake8_errmsg__tests__defaults.snap index a4d86c3aa72a3..9207755e73be1 100644 --- a/crates/ruff_linter/src/rules/flake8_errmsg/snapshots/ruff_linter__rules__flake8_errmsg__tests__defaults.snap +++ b/crates/ruff_linter/src/rules/flake8_errmsg/snapshots/ruff_linter__rules__flake8_errmsg__tests__defaults.snap @@ -9,11 +9,8 @@ EM101 [*] Exception must not use a string literal, assign to variable first | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Assign to variable; remove string literal | -4 | def f_a(): - - raise RuntimeError("This is an example exception") -5 + msg = "This is an example exception" -6 + raise RuntimeError(msg) -7 | +5 ~ msg = "This is an example exception" +6 ~ raise RuntimeError(msg) | note: This is an unsafe fix and may change runtime behavior @@ -25,11 +22,8 @@ EM101 [*] Exception must not use a string literal, assign to variable first | ^^^^^^^ help: Assign to variable; remove string literal | -8 | def f_a_short(): - - raise RuntimeError("Error") -9 + msg = "Error" -10 + raise RuntimeError(msg) -11 | + 9 ~ msg = "Error" +10 ~ raise RuntimeError(msg) | note: This is an unsafe fix and may change runtime behavior @@ -41,11 +35,8 @@ EM101 [*] Exception must not use a string literal, assign to variable first | ^^ help: Assign to variable; remove string literal | -12 | def f_a_empty(): - - raise RuntimeError("") -13 + msg = "" -14 + raise RuntimeError(msg) -15 | +13 ~ msg = "" +14 ~ raise RuntimeError(msg) | note: This is an unsafe fix and may change runtime behavior @@ -58,11 +49,8 @@ EM102 [*] Exception must not use an f-string literal, assign to variable first | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Assign to variable; remove f-string literal | -17 | example = "example" - - raise RuntimeError(f"This is an {example} exception") -18 + msg = f"This is an {example} exception" -19 + raise RuntimeError(msg) -20 | +18 ~ msg = f"This is an {example} exception" +19 ~ raise RuntimeError(msg) | note: This is an unsafe fix and may change runtime behavior @@ -74,11 +62,8 @@ EM103 [*] Exception must not use a `.format()` string directly, assign to variab | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Assign to variable; remove `.format()` string | -21 | def f_c(): - - raise RuntimeError("This is an {example} exception".format(example="example")) -22 + msg = "This is an {example} exception".format(example="example") -23 + raise RuntimeError(msg) -24 | +22 ~ msg = "This is an {example} exception".format(example="example") +23 ~ raise RuntimeError(msg) | note: This is an unsafe fix and may change runtime behavior @@ -91,11 +76,8 @@ EM101 [*] Exception must not use a string literal, assign to variable first | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Assign to variable; remove string literal | -31 | msg = "hello" - - raise RuntimeError("This is an example exception") -32 + msg_0 = "This is an example exception" -33 + raise RuntimeError(msg_0) -34 | +32 ~ msg_0 = "This is an example exception" +33 ~ raise RuntimeError(msg_0) | note: This is an unsafe fix and may change runtime behavior @@ -108,11 +90,8 @@ EM101 [*] Exception must not use a string literal, assign to variable first | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Assign to variable; remove string literal | -38 | - - raise RuntimeError("This is an example exception") -39 + msg = "This is an example exception" -40 + raise RuntimeError(msg) -41 | +39 ~ msg = "This is an example exception" +40 ~ raise RuntimeError(msg) | note: This is an unsafe fix and may change runtime behavior @@ -124,11 +103,8 @@ EM101 [*] Exception must not use a string literal, assign to variable first | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Assign to variable; remove string literal | -45 | def nested(): - - raise RuntimeError("This is an example exception") -46 + msg_0 = "This is an example exception" -47 + raise RuntimeError(msg_0) -48 | +46 ~ msg_0 = "This is an example exception" +47 ~ raise RuntimeError(msg_0) | note: This is an unsafe fix and may change runtime behavior @@ -144,11 +120,8 @@ EM101 [*] Exception must not use a string literal, assign to variable first | help: Assign to variable; remove string literal | -50 | if foo: - - raise RuntimeError("This is an example exception") -51 + msg = "This is an example exception" -52 + raise RuntimeError(msg) -53 | else: +51 ~ msg = "This is an example exception" +52 ~ raise RuntimeError(msg) | note: This is an unsafe fix and may change runtime behavior @@ -163,11 +136,8 @@ EM102 [*] Exception must not use an f-string literal, assign to variable first | help: Assign to variable; remove f-string literal | -53 | if foo == "foo": - - raise RuntimeError(f"This is an exception: {foo}") -54 + msg = f"This is an exception: {foo}" -55 + raise RuntimeError(msg) -56 | raise RuntimeError("This is an exception: {}".format(foo)) +54 ~ msg = f"This is an exception: {foo}" +55 ~ raise RuntimeError(msg) | note: This is an unsafe fix and may change runtime behavior @@ -180,11 +150,8 @@ EM103 [*] Exception must not use a `.format()` string directly, assign to variab | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Assign to variable; remove `.format()` string | -54 | raise RuntimeError(f"This is an exception: {foo}") - - raise RuntimeError("This is an exception: {}".format(foo)) -55 + msg = "This is an exception: {}".format(foo) -56 + raise RuntimeError(msg) -57 | +55 ~ msg = "This is an exception: {}".format(foo) +56 ~ raise RuntimeError(msg) | note: This is an unsafe fix and may change runtime behavior @@ -215,11 +182,8 @@ EM102 [*] Exception must not use an f-string literal, assign to variable first | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Assign to variable; remove f-string literal | -63 | def f_triple_quoted_string(): - - raise RuntimeError(f"""This is an {"example"} exception""") -64 + msg = f"""This is an {"example"} exception""" -65 + raise RuntimeError(msg) -66 | +64 ~ msg = f"""This is an {"example"} exception""" +65 ~ raise RuntimeError(msg) | note: This is an unsafe fix and may change runtime behavior @@ -235,16 +199,12 @@ EM101 [*] Exception must not use a string literal, assign to variable first | help: Assign to variable; remove string literal | -67 | def f_multi_line_string(): - - raise RuntimeError( -68 + msg = ( -69 | "first" -70 | "second" -71 | ) -72 + raise RuntimeError( -73 + msg -74 + ) -75 | +68 ~ msg = ( +69 + "first" +70 + "second" +71 + ) +72 ~ raise RuntimeError( +73 ~ msg | note: This is an unsafe fix and may change runtime behavior @@ -261,17 +221,13 @@ EM103 [*] Exception must not use a `.format()` string directly, assign to variab | help: Assign to variable; remove `.format()` string | -74 | def f_multi_line_string2(): - - raise RuntimeError( -75 + msg = ( -76 | "This is an {example} exception".format( -77 | example="example" -78 | ) -79 | ) -80 + raise RuntimeError( -81 + msg -82 + ) -83 | +75 ~ msg = ( +76 + "This is an {example} exception".format( +77 + example="example" +78 + ) +79 + ) +80 ~ raise RuntimeError( +81 ~ msg | note: This is an unsafe fix and may change runtime behavior @@ -291,16 +247,16 @@ EM103 [*] Exception must not use a `.format()` string directly, assign to variab | help: Assign to variable; remove `.format()` string | -82 | def f_multi_line_string2(): - - raise RuntimeError( -83 + msg = ( -84 | ( --------------------------------------------------------------------------------- -90 | ) -91 + raise RuntimeError( -92 + msg -93 + ) -94 | +83 ~ msg = ( +84 + ( +85 + "This is an " +86 + "{example} exception" +87 + ).format( +88 + example="example" +89 + ) +90 + ) +91 ~ raise RuntimeError( +92 ~ msg | note: This is an unsafe fix and may change runtime behavior @@ -316,10 +272,7 @@ EM101 [*] Exception must not use a string literal, assign to variable first | help: Assign to variable; remove string literal | -117 | try: - - raise RuntimeError("!") -118 + msg_0 = "!" -119 + raise RuntimeError(msg_0) -120 | except RuntimeError: +118 ~ msg_0 = "!" +119 ~ raise RuntimeError(msg_0) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_errmsg/snapshots/ruff_linter__rules__flake8_errmsg__tests__string_exception.snap b/crates/ruff_linter/src/rules/flake8_errmsg/snapshots/ruff_linter__rules__flake8_errmsg__tests__string_exception.snap index 1a8001fa15e11..032f202e77f74 100644 --- a/crates/ruff_linter/src/rules/flake8_errmsg/snapshots/ruff_linter__rules__flake8_errmsg__tests__string_exception.snap +++ b/crates/ruff_linter/src/rules/flake8_errmsg/snapshots/ruff_linter__rules__flake8_errmsg__tests__string_exception.snap @@ -9,11 +9,8 @@ EM101 [*] Exception must not use a string literal, assign to variable first | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Assign to variable; remove string literal | -1 | def f_byte(): - - raise RuntimeError(b"This is an example exception") -2 + msg = b"This is an example exception" -3 + raise RuntimeError(msg) -4 | +2 ~ msg = b"This is an example exception" +3 ~ raise RuntimeError(msg) | note: This is an unsafe fix and may change runtime behavior @@ -25,9 +22,7 @@ EM101 [*] Exception must not use a string literal, assign to variable first | ^^^ help: Assign to variable; remove string literal | -5 | def f_byte_empty(): - - raise RuntimeError(b"") -6 + msg = b"" -7 + raise RuntimeError(msg) +6 ~ msg = b"" +7 ~ raise RuntimeError(msg) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_executable/snapshots/ruff_linter__rules__flake8_executable__tests__EXE004_1.py.snap b/crates/ruff_linter/src/rules/flake8_executable/snapshots/ruff_linter__rules__flake8_executable__tests__EXE004_1.py.snap index e311ac219e881..92d3b1a37f270 100644 --- a/crates/ruff_linter/src/rules/flake8_executable/snapshots/ruff_linter__rules__flake8_executable__tests__EXE004_1.py.snap +++ b/crates/ruff_linter/src/rules/flake8_executable/snapshots/ruff_linter__rules__flake8_executable__tests__EXE004_1.py.snap @@ -8,6 +8,5 @@ EXE004 [*] Avoid whitespace before shebang | ^^^^ help: Remove whitespace before shebang | - - #!/usr/bin/python -1 + #!/usr/bin/python +1 | #!/usr/bin/python | diff --git a/crates/ruff_linter/src/rules/flake8_executable/snapshots/ruff_linter__rules__flake8_executable__tests__EXE004_4.py.snap b/crates/ruff_linter/src/rules/flake8_executable/snapshots/ruff_linter__rules__flake8_executable__tests__EXE004_4.py.snap index 49c7601c2a04e..15fb6eafdfdfd 100644 --- a/crates/ruff_linter/src/rules/flake8_executable/snapshots/ruff_linter__rules__flake8_executable__tests__EXE004_4.py.snap +++ b/crates/ruff_linter/src/rules/flake8_executable/snapshots/ruff_linter__rules__flake8_executable__tests__EXE004_4.py.snap @@ -9,8 +9,6 @@ EXE004 [*] Avoid whitespace before shebang | |____^ help: Remove whitespace before shebang | - - - - #!/usr/bin/env python -1 + #!/usr/bin/env python +1 | #!/usr/bin/env python | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__edge_case.py.snap b/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__edge_case.py.snap index 88369729edf16..8f88f6ab42b61 100644 --- a/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__edge_case.py.snap +++ b/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__edge_case.py.snap @@ -12,7 +12,6 @@ FA100 [*] Add `from __future__ import annotations` to simplify `typing.List` help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | from typing import List | note: This is an unsafe fix and may change runtime behavior @@ -27,6 +26,5 @@ FA100 [*] Add `from __future__ import annotations` to simplify `typing.List` help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | from typing import List | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__fa102_no_future_import_uses_lowercase.py.snap b/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__fa102_no_future_import_uses_lowercase.py.snap index 6468c51c8226b..2818fb1fcc3b5 100644 --- a/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__fa102_no_future_import_uses_lowercase.py.snap +++ b/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__fa102_no_future_import_uses_lowercase.py.snap @@ -11,6 +11,5 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | def main() -> None: | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__fa102_no_future_import_uses_preview_generics.py.snap b/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__fa102_no_future_import_uses_preview_generics.py.snap index 24dd3a986be0c..28928377bf715 100644 --- a/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__fa102_no_future_import_uses_preview_generics.py.snap +++ b/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__fa102_no_future_import_uses_preview_generics.py.snap @@ -13,7 +13,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -30,7 +29,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -47,7 +45,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -64,7 +61,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -81,7 +77,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -98,7 +93,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -115,7 +109,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -132,7 +125,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -149,7 +141,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -166,7 +157,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -183,7 +173,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -200,7 +189,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -217,7 +205,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -234,7 +221,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -251,7 +237,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -268,7 +253,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -285,7 +269,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -302,7 +285,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -319,7 +301,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -336,7 +317,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -353,7 +333,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -370,7 +349,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -387,7 +365,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -404,7 +381,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -421,7 +397,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -438,7 +413,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -455,7 +429,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -472,7 +445,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -489,7 +461,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -506,7 +477,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -523,7 +493,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -540,7 +509,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -557,7 +525,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -574,7 +541,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -591,7 +557,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -608,7 +573,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -625,7 +589,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -642,7 +605,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -659,7 +621,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -676,7 +637,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -693,7 +653,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -710,7 +669,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -727,7 +685,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -744,7 +701,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -761,7 +717,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -778,7 +733,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -795,7 +749,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -812,7 +765,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -829,7 +781,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior @@ -846,6 +797,5 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import asyncio | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__fa102_no_future_import_uses_union.py.snap b/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__fa102_no_future_import_uses_union.py.snap index cfbbaaff7d98a..f432ebfb2d319 100644 --- a/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__fa102_no_future_import_uses_union.py.snap +++ b/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__fa102_no_future_import_uses_union.py.snap @@ -11,7 +11,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | def main() -> None: | note: This is an unsafe fix and may change runtime behavior @@ -25,6 +24,5 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 604 union help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | def main() -> None: | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__fa102_no_future_import_uses_union_inner.py.snap b/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__fa102_no_future_import_uses_union_inner.py.snap index 19dc2adbf6820..99531cabbb92d 100644 --- a/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__fa102_no_future_import_uses_union_inner.py.snap +++ b/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__fa102_no_future_import_uses_union_inner.py.snap @@ -12,7 +12,6 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 585 collect help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | def main() -> None: | note: This is an unsafe fix and may change runtime behavior @@ -27,6 +26,5 @@ FA102 [*] Missing `from __future__ import annotations`, but uses PEP 604 union help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | def main() -> None: | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__from_typing_import.py.snap b/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__from_typing_import.py.snap index 416918c763649..cc78ab410bd96 100644 --- a/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__from_typing_import.py.snap +++ b/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__from_typing_import.py.snap @@ -12,6 +12,5 @@ FA100 [*] Add `from __future__ import annotations` to simplify `typing.List` help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | from typing import List | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__from_typing_import_many.py.snap b/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__from_typing_import_many.py.snap index 255bc47abbd76..cc24ee52465f7 100644 --- a/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__from_typing_import_many.py.snap +++ b/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__from_typing_import_many.py.snap @@ -13,7 +13,6 @@ FA100 [*] Add `from __future__ import annotations` to simplify `typing.List` help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | from typing import Dict, List, Optional, Set, Union, cast | note: This is an unsafe fix and may change runtime behavior @@ -29,6 +28,5 @@ FA100 [*] Add `from __future__ import annotations` to simplify `typing.Optional` help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | from typing import Dict, List, Optional, Set, Union, cast | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__import_typing.py.snap b/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__import_typing.py.snap index 3db62b8de6bcd..2b7e454ce1a2c 100644 --- a/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__import_typing.py.snap +++ b/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__import_typing.py.snap @@ -12,6 +12,5 @@ FA100 [*] Add `from __future__ import annotations` to simplify `typing.List` help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import typing | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__import_typing_as.py.snap b/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__import_typing_as.py.snap index b90a75c0d1137..008b777bc7648 100644 --- a/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__import_typing_as.py.snap +++ b/crates/ruff_linter/src/rules/flake8_future_annotations/snapshots/ruff_linter__rules__flake8_future_annotations__tests__import_typing_as.py.snap @@ -12,6 +12,5 @@ FA100 [*] Add `from __future__ import annotations` to simplify `typing.List` help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import typing as t | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_implicit_str_concat/snapshots/ruff_linter__rules__flake8_implicit_str_concat__tests__ISC001_ISC.py.snap b/crates/ruff_linter/src/rules/flake8_implicit_str_concat/snapshots/ruff_linter__rules__flake8_implicit_str_concat__tests__ISC001_ISC.py.snap index 9e98634ba0dba..9afa2a1dd1b0f 100644 --- a/crates/ruff_linter/src/rules/flake8_implicit_str_concat/snapshots/ruff_linter__rules__flake8_implicit_str_concat__tests__ISC001_ISC.py.snap +++ b/crates/ruff_linter/src/rules/flake8_implicit_str_concat/snapshots/ruff_linter__rules__flake8_implicit_str_concat__tests__ISC001_ISC.py.snap @@ -11,9 +11,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | - - _ = "a" "b" "c" +1 - _ = "a" "b" "c" 1 + _ = "ab" "c" -2 | | ISC001 [*] Implicitly concatenated string literals on one line @@ -26,9 +25,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | - - _ = "a" "b" "c" +1 - _ = "a" "b" "c" 1 + _ = "a" "bc" -2 | | ISC001 [*] Implicitly concatenated string literals on one line @@ -43,10 +41,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -37 | - - _ = """a""" """b""" +38 - _ = """a""" """b""" 38 + _ = """ab""" -39 | | ISC001 [*] Implicitly concatenated string literals on one line @@ -64,10 +60,9 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -40 | _ = """a - - b""" """c +40 ~ _ = """a 41 + bc -42 | d""" +42 + d""" | ISC001 [*] Implicitly concatenated string literals on one line @@ -82,10 +77,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -43 | - - _ = f"""a""" f"""b""" +44 - _ = f"""a""" f"""b""" 44 + _ = f"""ab""" -45 | | ISC001 Implicitly concatenated string literals on one line @@ -136,10 +129,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -51 | - - _ = rf"a" rf"b" +52 - _ = rf"a" rf"b" 52 + _ = rf"ab" -53 | | ISC001 [*] Implicitly concatenated string literals on one line @@ -153,10 +144,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -63 | # Multiple strings nested inside a f-string - - _ = f"a {'b' 'c' 'd'} e" +64 - _ = f"a {'b' 'c' 'd'} e" 64 + _ = f"a {'bc' 'd'} e" -65 | _ = f"""abc {"def" "ghi"} jkl""" | ISC001 [*] Implicitly concatenated string literals on one line @@ -170,10 +159,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -63 | # Multiple strings nested inside a f-string - - _ = f"a {'b' 'c' 'd'} e" +64 - _ = f"a {'b' 'c' 'd'} e" 64 + _ = f"a {'b' 'cd'} e" -65 | _ = f"""abc {"def" "ghi"} jkl""" | ISC001 [*] Implicitly concatenated string literals on one line @@ -188,10 +175,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -64 | _ = f"a {'b' 'c' 'd'} e" - - _ = f"""abc {"def" "ghi"} jkl""" +65 - _ = f"""abc {"def" "ghi"} jkl""" 65 + _ = f"""abc {"defghi"} jkl""" -66 | _ = f"""abc { | ISC001 Implicitly concatenated string literals on one line @@ -227,10 +212,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -71 | # Nested f-strings - - _ = "a" f"b {f"c" f"d"} e" "f" +72 - _ = "a" f"b {f"c" f"d"} e" "f" 72 + _ = "a" f"b {f"cd"} e" "f" -73 | _ = f"b {f"c" f"d {f"e" f"f"} g"} h" | ISC001 [*] Implicitly concatenated string literals on one line @@ -245,10 +228,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -72 | _ = "a" f"b {f"c" f"d"} e" "f" - - _ = f"b {f"c" f"d {f"e" f"f"} g"} h" +73 - _ = f"b {f"c" f"d {f"e" f"f"} g"} h" 73 + _ = f"b {f"cd {f"e" f"f"} g"} h" -74 | _ = f"b {f"abc" \ | ISC001 [*] Implicitly concatenated string literals on one line @@ -263,10 +244,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -72 | _ = "a" f"b {f"c" f"d"} e" "f" - - _ = f"b {f"c" f"d {f"e" f"f"} g"} h" +73 - _ = f"b {f"c" f"d {f"e" f"f"} g"} h" 73 + _ = f"b {f"c" f"d {f"ef"} g"} h" -74 | _ = f"b {f"abc" \ | ISC001 [*] Implicitly concatenated string literals on one line @@ -280,10 +259,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -83 | # See https://github.com/astral-sh/ruff/issues/12936 - - _ = "\12""0" # fix should be "\0120" +84 - _ = "\12""0" # fix should be "\0120" 84 + _ = "\0120" # fix should be "\0120" -85 | _ = "\\12""0" # fix should be "\\120" | ISC001 [*] Implicitly concatenated string literals on one line @@ -298,10 +275,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -84 | _ = "\12""0" # fix should be "\0120" - - _ = "\\12""0" # fix should be "\\120" +85 - _ = "\\12""0" # fix should be "\\120" 85 + _ = "\\120" # fix should be "\\120" -86 | _ = "\\\12""0" # fix should be "\\\0120" | ISC001 [*] Implicitly concatenated string literals on one line @@ -316,10 +291,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -85 | _ = "\\12""0" # fix should be "\\120" - - _ = "\\\12""0" # fix should be "\\\0120" +86 - _ = "\\\12""0" # fix should be "\\\0120" 86 + _ = "\\\0120" # fix should be "\\\0120" -87 | _ = "\12 0""0" # fix should be "\12 00" | ISC001 [*] Implicitly concatenated string literals on one line @@ -334,10 +307,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -86 | _ = "\\\12""0" # fix should be "\\\0120" - - _ = "\12 0""0" # fix should be "\12 00" +87 - _ = "\12 0""0" # fix should be "\12 00" 87 + _ = "\12 00" # fix should be "\12 00" -88 | _ = r"\12"r"0" # fix should be r"\120" | ISC001 [*] Implicitly concatenated string literals on one line @@ -352,10 +323,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -87 | _ = "\12 0""0" # fix should be "\12 00" - - _ = r"\12"r"0" # fix should be r"\120" +88 - _ = r"\12"r"0" # fix should be r"\120" 88 + _ = r"\120" # fix should be r"\120" -89 | _ = "\12 and more""0" # fix should be "\12 and more0" | ISC001 [*] Implicitly concatenated string literals on one line @@ -370,10 +339,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -88 | _ = r"\12"r"0" # fix should be r"\120" - - _ = "\12 and more""0" # fix should be "\12 and more0" +89 - _ = "\12 and more""0" # fix should be "\12 and more0" 89 + _ = "\12 and more0" # fix should be "\12 and more0" -90 | _ = "\8""0" # fix should be "\80" | ISC001 [*] Implicitly concatenated string literals on one line @@ -388,10 +355,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -89 | _ = "\12 and more""0" # fix should be "\12 and more0" - - _ = "\8""0" # fix should be "\80" +90 - _ = "\8""0" # fix should be "\80" 90 + _ = "\80" # fix should be "\80" -91 | _ = "\12""8" # fix should be "\128" | ISC001 [*] Implicitly concatenated string literals on one line @@ -406,10 +371,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -90 | _ = "\8""0" # fix should be "\80" - - _ = "\12""8" # fix should be "\128" +91 - _ = "\12""8" # fix should be "\128" 91 + _ = "\128" # fix should be "\128" -92 | _ = "\12""foo" # fix should be "\12foo" | ISC001 [*] Implicitly concatenated string literals on one line @@ -423,10 +386,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -91 | _ = "\12""8" # fix should be "\128" - - _ = "\12""foo" # fix should be "\12foo" +92 - _ = "\12""foo" # fix should be "\12foo" 92 + _ = "\12foo" # fix should be "\12foo" -93 | _ = "\12" "" # fix should be "\12" | ISC001 [*] Implicitly concatenated string literals on one line @@ -438,10 +399,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | ^^^^^^^^ help: Combine string literals | -92 | _ = "\12""foo" # fix should be "\12foo" - - _ = "\12" "" # fix should be "\12" +93 - _ = "\12" "" # fix should be "\12" 93 + _ = "\12" # fix should be "\12" -94 | | ISC001 [*] Implicitly concatenated string literals on one line @@ -456,10 +415,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -192 | # ISC001 - - t"The quick " t"brown fox." +193 - t"The quick " t"brown fox." 193 + t"The quick brown fox." -194 | | ISC001 Implicitly concatenated string literals on one line @@ -495,10 +452,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -205 | # nested examples with both t and f-strings - - _ = "a" f"b {t"c" t"d"} e" "f" +206 - _ = "a" f"b {t"c" t"d"} e" "f" 206 + _ = "a" f"b {t"cd"} e" "f" -207 | _ = t"b {f"c" f"d {t"e" t"f"} g"} h" | ISC001 [*] Implicitly concatenated string literals on one line @@ -513,10 +468,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -206 | _ = "a" f"b {t"c" t"d"} e" "f" - - _ = t"b {f"c" f"d {t"e" t"f"} g"} h" +207 - _ = t"b {f"c" f"d {t"e" t"f"} g"} h" 207 + _ = t"b {f"cd {t"e" t"f"} g"} h" -208 | _ = f"b {t"abc" \ | ISC001 [*] Implicitly concatenated string literals on one line @@ -531,8 +484,6 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -206 | _ = "a" f"b {t"c" t"d"} e" "f" - - _ = t"b {f"c" f"d {t"e" t"f"} g"} h" +207 - _ = t"b {f"c" f"d {t"e" t"f"} g"} h" 207 + _ = t"b {f"c" f"d {t"ef"} g"} h" -208 | _ = f"b {t"abc" \ | diff --git a/crates/ruff_linter/src/rules/flake8_implicit_str_concat/snapshots/ruff_linter__rules__flake8_implicit_str_concat__tests__ISC003_ISC.py.snap b/crates/ruff_linter/src/rules/flake8_implicit_str_concat/snapshots/ruff_linter__rules__flake8_implicit_str_concat__tests__ISC003_ISC.py.snap index aef8d1887a3b5..2f164ea452fdc 100644 --- a/crates/ruff_linter/src/rules/flake8_implicit_str_concat/snapshots/ruff_linter__rules__flake8_implicit_str_concat__tests__ISC003_ISC.py.snap +++ b/crates/ruff_linter/src/rules/flake8_implicit_str_concat/snapshots/ruff_linter__rules__flake8_implicit_str_concat__tests__ISC003_ISC.py.snap @@ -12,10 +12,8 @@ ISC003 [*] Explicitly concatenated string should be implicitly concatenated | help: Remove redundant '+' operator to implicitly concatenate | -8 | _ = ( - - "abc" + -9 + "abc" -10 | "def" + 9 ~ "abc" +10 ~ "def" | ISC003 [*] Explicitly concatenated string should be implicitly concatenated @@ -29,10 +27,8 @@ ISC003 [*] Explicitly concatenated string should be implicitly concatenated | help: Remove redundant '+' operator to implicitly concatenate | -13 | _ = ( - - f"abc" + -14 + f"abc" -15 | "def" +14 ~ f"abc" +15 ~ "def" | ISC003 [*] Explicitly concatenated string should be implicitly concatenated @@ -46,10 +42,8 @@ ISC003 [*] Explicitly concatenated string should be implicitly concatenated | help: Remove redundant '+' operator to implicitly concatenate | -18 | _ = ( - - b"abc" + -19 + b"abc" -20 | b"def" +19 ~ b"abc" +20 ~ b"def" | ISC003 [*] Explicitly concatenated string should be implicitly concatenated @@ -65,10 +59,8 @@ ISC003 [*] Explicitly concatenated string should be implicitly concatenated | help: Remove redundant '+' operator to implicitly concatenate | -78 | _ = f"a {f"first" - - + f"second"} d" -79 + f"second"} d" -80 | _ = f"a {f"first {f"middle"}" +78 ~ _ = f"a {f"first" +79 ~ f"second"} d" | ISC003 [*] Explicitly concatenated string should be implicitly concatenated @@ -85,10 +77,8 @@ ISC003 [*] Explicitly concatenated string should be implicitly concatenated | help: Remove redundant '+' operator to implicitly concatenate | -80 | _ = f"a {f"first {f"middle"}" - - + f"second"} d" -81 + f"second"} d" -82 | +80 ~ _ = f"a {f"first {f"middle"}" +81 ~ f"second"} d" | ISC003 [*] Explicitly concatenated string should be implicitly concatenated @@ -102,10 +92,8 @@ ISC003 [*] Explicitly concatenated string should be implicitly concatenated | help: Remove redundant '+' operator to implicitly concatenate | -109 | _ = ( - - rf"raw_f{x}" + -110 + rf"raw_f{x}" -111 | r"raw_normal" +110 ~ rf"raw_f{x}" +111 ~ r"raw_normal" | ISC003 [*] Explicitly concatenated string should be implicitly concatenated @@ -120,10 +108,8 @@ ISC003 [*] Explicitly concatenated string should be implicitly concatenated | help: Remove redundant '+' operator to implicitly concatenate | -116 | _ = ( - - u"unicode" + -117 + u"unicode" -118 | r"raw" +117 ~ u"unicode" +118 ~ r"raw" | ISC003 [*] Explicitly concatenated string should be implicitly concatenated @@ -137,10 +123,8 @@ ISC003 [*] Explicitly concatenated string should be implicitly concatenated | help: Remove redundant '+' operator to implicitly concatenate | -121 | _ = ( - - rb"raw_bytes" + -122 + rb"raw_bytes" -123 | b"normal_bytes" +122 ~ rb"raw_bytes" +123 ~ b"normal_bytes" | ISC003 [*] Explicitly concatenated string should be implicitly concatenated @@ -154,10 +138,8 @@ ISC003 [*] Explicitly concatenated string should be implicitly concatenated | help: Remove redundant '+' operator to implicitly concatenate | -126 | _ = ( - - b"bytes" + -127 + b"bytes" -128 | b"with_bytes" +127 ~ b"bytes" +128 ~ b"with_bytes" | ISC003 [*] Explicitly concatenated string should be implicitly concatenated @@ -174,10 +156,8 @@ ISC003 [*] Explicitly concatenated string should be implicitly concatenated | help: Remove redundant '+' operator to implicitly concatenate | -132 | - - _ = ("a" + -133 + _ = ("a" -134 | "b" + +133 ~ _ = ("a" +134 ~ "b" + | ISC003 [*] Explicitly concatenated string should be implicitly concatenated @@ -194,10 +174,8 @@ ISC003 [*] Explicitly concatenated string should be implicitly concatenated | help: Remove redundant '+' operator to implicitly concatenate | -139 | _ = ("a" - - + "b" -140 + "b" -141 | + "c" +139 ~ _ = ("a" +140 ~ "b" | ISC003 [*] Explicitly concatenated string should be implicitly concatenated @@ -211,10 +189,8 @@ ISC003 [*] Explicitly concatenated string should be implicitly concatenated | help: Remove redundant '+' operator to implicitly concatenate | -160 | "first" - - + "second" # extra spaces around + -161 + "second" # extra spaces around + -162 | ) +160 ~ "first" +161 ~ "second" # extra spaces around + | ISC003 [*] Explicitly concatenated string should be implicitly concatenated @@ -228,10 +204,8 @@ ISC003 [*] Explicitly concatenated string should be implicitly concatenated | help: Remove redundant '+' operator to implicitly concatenate | -164 | _ = ( - - "first" + # trailing spaces before + -165 + "first" # trailing spaces before + -166 | "second" +165 ~ "first" # trailing spaces before + +166 ~ "second" | ISC003 [*] Explicitly concatenated string should be implicitly concatenated @@ -245,10 +219,8 @@ ISC003 [*] Explicitly concatenated string should be implicitly concatenated | help: Remove redundant '+' operator to implicitly concatenate | -169 | _ = (( - - "deep" + -170 + "deep" -171 | "nesting" +170 ~ "deep" +171 ~ "nesting" | ISC003 [*] Explicitly concatenated string should be implicitly concatenated @@ -262,10 +234,8 @@ ISC003 [*] Explicitly concatenated string should be implicitly concatenated | help: Remove redundant '+' operator to implicitly concatenate | -174 | _ = ( - - "contains + plus" + -175 + "contains + plus" -176 | "another string" +175 ~ "contains + plus" +176 ~ "another string" | ISC003 [*] Explicitly concatenated string should be implicitly concatenated @@ -280,10 +250,9 @@ ISC003 [*] Explicitly concatenated string should be implicitly concatenated | help: Remove redundant '+' operator to implicitly concatenate | -181 | # leading comment - - + "end" -182 + "end" -183 | ) +180 ~ "start" +181 ~ # leading comment +182 ~ "end" | ISC003 [*] Explicitly concatenated string should be implicitly concatenated @@ -298,10 +267,9 @@ ISC003 [*] Explicitly concatenated string should be implicitly concatenated | help: Remove redundant '+' operator to implicitly concatenate | -185 | _ = ( - - "start" + -186 + "start" -187 | # leading comment +186 ~ "start" +187 ~ # leading comment +188 ~ "end" | ISC003 [*] Explicitly concatenated string should be implicitly concatenated @@ -316,10 +284,8 @@ ISC003 [*] Explicitly concatenated string should be implicitly concatenated | help: Remove redundant '+' operator to implicitly concatenate | -201 | t"The quick brown fox jumps over the lazy " - - + t"dog" -202 + t"dog" -203 | ) +201 ~ t"The quick brown fox jumps over the lazy " +202 ~ t"dog" | ISC003 Explicitly concatenated string should be implicitly concatenated @@ -364,8 +330,6 @@ ISC003 [*] Explicitly concatenated string should be implicitly concatenated | help: Remove redundant '+' operator to implicitly concatenate | -229 | "A" # Complains about this: + - - + " broken" -230 + " broken" -231 | + " line" +229 ~ "A" # Complains about this: + +230 ~ " broken" | diff --git a/crates/ruff_linter/src/rules/flake8_implicit_str_concat/snapshots/ruff_linter__rules__flake8_implicit_str_concat__tests__ISC004_ISC004.py.snap b/crates/ruff_linter/src/rules/flake8_implicit_str_concat/snapshots/ruff_linter__rules__flake8_implicit_str_concat__tests__ISC004_ISC004.py.snap index fd85149253371..9146a472e8062 100644 --- a/crates/ruff_linter/src/rules/flake8_implicit_str_concat/snapshots/ruff_linter__rules__flake8_implicit_str_concat__tests__ISC004_ISC004.py.snap +++ b/crates/ruff_linter/src/rules/flake8_implicit_str_concat/snapshots/ruff_linter__rules__flake8_implicit_str_concat__tests__ISC004_ISC004.py.snap @@ -14,12 +14,8 @@ ISC004 [*] Unparenthesized implicit string concatenation in collection help: Did you forget a comma? help: Wrap implicitly concatenated strings in parentheses | -3 | "The liver is the only human organ that can fully regenerate itself.", - - "Clarinets are made almost entirely out of wood from the mpingo tree." - - "In 1971, astronaut Alan Shepard played golf on the moon.", -4 + ("Clarinets are made almost entirely out of wood from the mpingo tree." -5 + "In 1971, astronaut Alan Shepard played golf on the moon."), -6 | ) +4 ~ ("Clarinets are made almost entirely out of wood from the mpingo tree." +5 ~ "In 1971, astronaut Alan Shepard played golf on the moon."), | note: This is an unsafe fix and may change runtime behavior @@ -36,12 +32,8 @@ ISC004 [*] Unparenthesized implicit string concatenation in collection help: Did you forget a comma? help: Wrap implicitly concatenated strings in parentheses | -10 | "The liver is the only human organ that can fully regenerate itself.", - - "Clarinets are made almost entirely out of wood from the mpingo tree." - - "In 1971, astronaut Alan Shepard played golf on the moon.", -11 + ("Clarinets are made almost entirely out of wood from the mpingo tree." -12 + "In 1971, astronaut Alan Shepard played golf on the moon."), -13 | ] +11 ~ ("Clarinets are made almost entirely out of wood from the mpingo tree." +12 ~ "In 1971, astronaut Alan Shepard played golf on the moon."), | note: This is an unsafe fix and may change runtime behavior @@ -58,12 +50,8 @@ ISC004 [*] Unparenthesized implicit string concatenation in collection help: Did you forget a comma? help: Wrap implicitly concatenated strings in parentheses | -17 | "The liver is the only human organ that can fully regenerate itself.", - - "Clarinets are made almost entirely out of wood from the mpingo tree." - - "In 1971, astronaut Alan Shepard played golf on the moon.", -18 + ("Clarinets are made almost entirely out of wood from the mpingo tree." -19 + "In 1971, astronaut Alan Shepard played golf on the moon."), -20 | } +18 ~ ("Clarinets are made almost entirely out of wood from the mpingo tree." +19 ~ "In 1971, astronaut Alan Shepard played golf on the moon."), | note: This is an unsafe fix and may change runtime behavior @@ -80,13 +68,9 @@ ISC004 [*] Unparenthesized implicit string concatenation in collection help: Did you forget a comma? help: Wrap implicitly concatenated strings in parentheses | -29 | facts = ( - - "Octopuses have three hearts." -30 + ("Octopuses have three hearts." +30 ~ ("Octopuses have three hearts." 31 | # Missing comma here. - - "Honey never spoils.", -32 + "Honey never spoils."), -33 | ) +32 ~ "Honey never spoils."), | note: This is an unsafe fix and may change runtime behavior @@ -103,13 +87,9 @@ ISC004 [*] Unparenthesized implicit string concatenation in collection help: Did you forget a comma? help: Wrap implicitly concatenated strings in parentheses | -35 | facts = [ - - "Octopuses have three hearts." -36 + ("Octopuses have three hearts." +36 ~ ("Octopuses have three hearts." 37 | # Missing comma here. - - "Honey never spoils.", -38 + "Honey never spoils."), -39 | ] +38 ~ "Honey never spoils."), | note: This is an unsafe fix and may change runtime behavior @@ -126,12 +106,8 @@ ISC004 [*] Unparenthesized implicit string concatenation in collection help: Did you forget a comma? help: Wrap implicitly concatenated strings in parentheses | -41 | facts = { - - "Octopuses have three hearts." -42 + ("Octopuses have three hearts." +42 ~ ("Octopuses have three hearts." 43 | # Missing comma here. - - "Honey never spoils.", -44 + "Honey never spoils."), -45 | } +44 ~ "Honey never spoils."), | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_implicit_str_concat/snapshots/ruff_linter__rules__flake8_implicit_str_concat__tests__multiline_ISC001_ISC.py.snap b/crates/ruff_linter/src/rules/flake8_implicit_str_concat/snapshots/ruff_linter__rules__flake8_implicit_str_concat__tests__multiline_ISC001_ISC.py.snap index 9e98634ba0dba..9afa2a1dd1b0f 100644 --- a/crates/ruff_linter/src/rules/flake8_implicit_str_concat/snapshots/ruff_linter__rules__flake8_implicit_str_concat__tests__multiline_ISC001_ISC.py.snap +++ b/crates/ruff_linter/src/rules/flake8_implicit_str_concat/snapshots/ruff_linter__rules__flake8_implicit_str_concat__tests__multiline_ISC001_ISC.py.snap @@ -11,9 +11,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | - - _ = "a" "b" "c" +1 - _ = "a" "b" "c" 1 + _ = "ab" "c" -2 | | ISC001 [*] Implicitly concatenated string literals on one line @@ -26,9 +25,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | - - _ = "a" "b" "c" +1 - _ = "a" "b" "c" 1 + _ = "a" "bc" -2 | | ISC001 [*] Implicitly concatenated string literals on one line @@ -43,10 +41,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -37 | - - _ = """a""" """b""" +38 - _ = """a""" """b""" 38 + _ = """ab""" -39 | | ISC001 [*] Implicitly concatenated string literals on one line @@ -64,10 +60,9 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -40 | _ = """a - - b""" """c +40 ~ _ = """a 41 + bc -42 | d""" +42 + d""" | ISC001 [*] Implicitly concatenated string literals on one line @@ -82,10 +77,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -43 | - - _ = f"""a""" f"""b""" +44 - _ = f"""a""" f"""b""" 44 + _ = f"""ab""" -45 | | ISC001 Implicitly concatenated string literals on one line @@ -136,10 +129,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -51 | - - _ = rf"a" rf"b" +52 - _ = rf"a" rf"b" 52 + _ = rf"ab" -53 | | ISC001 [*] Implicitly concatenated string literals on one line @@ -153,10 +144,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -63 | # Multiple strings nested inside a f-string - - _ = f"a {'b' 'c' 'd'} e" +64 - _ = f"a {'b' 'c' 'd'} e" 64 + _ = f"a {'bc' 'd'} e" -65 | _ = f"""abc {"def" "ghi"} jkl""" | ISC001 [*] Implicitly concatenated string literals on one line @@ -170,10 +159,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -63 | # Multiple strings nested inside a f-string - - _ = f"a {'b' 'c' 'd'} e" +64 - _ = f"a {'b' 'c' 'd'} e" 64 + _ = f"a {'b' 'cd'} e" -65 | _ = f"""abc {"def" "ghi"} jkl""" | ISC001 [*] Implicitly concatenated string literals on one line @@ -188,10 +175,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -64 | _ = f"a {'b' 'c' 'd'} e" - - _ = f"""abc {"def" "ghi"} jkl""" +65 - _ = f"""abc {"def" "ghi"} jkl""" 65 + _ = f"""abc {"defghi"} jkl""" -66 | _ = f"""abc { | ISC001 Implicitly concatenated string literals on one line @@ -227,10 +212,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -71 | # Nested f-strings - - _ = "a" f"b {f"c" f"d"} e" "f" +72 - _ = "a" f"b {f"c" f"d"} e" "f" 72 + _ = "a" f"b {f"cd"} e" "f" -73 | _ = f"b {f"c" f"d {f"e" f"f"} g"} h" | ISC001 [*] Implicitly concatenated string literals on one line @@ -245,10 +228,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -72 | _ = "a" f"b {f"c" f"d"} e" "f" - - _ = f"b {f"c" f"d {f"e" f"f"} g"} h" +73 - _ = f"b {f"c" f"d {f"e" f"f"} g"} h" 73 + _ = f"b {f"cd {f"e" f"f"} g"} h" -74 | _ = f"b {f"abc" \ | ISC001 [*] Implicitly concatenated string literals on one line @@ -263,10 +244,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -72 | _ = "a" f"b {f"c" f"d"} e" "f" - - _ = f"b {f"c" f"d {f"e" f"f"} g"} h" +73 - _ = f"b {f"c" f"d {f"e" f"f"} g"} h" 73 + _ = f"b {f"c" f"d {f"ef"} g"} h" -74 | _ = f"b {f"abc" \ | ISC001 [*] Implicitly concatenated string literals on one line @@ -280,10 +259,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -83 | # See https://github.com/astral-sh/ruff/issues/12936 - - _ = "\12""0" # fix should be "\0120" +84 - _ = "\12""0" # fix should be "\0120" 84 + _ = "\0120" # fix should be "\0120" -85 | _ = "\\12""0" # fix should be "\\120" | ISC001 [*] Implicitly concatenated string literals on one line @@ -298,10 +275,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -84 | _ = "\12""0" # fix should be "\0120" - - _ = "\\12""0" # fix should be "\\120" +85 - _ = "\\12""0" # fix should be "\\120" 85 + _ = "\\120" # fix should be "\\120" -86 | _ = "\\\12""0" # fix should be "\\\0120" | ISC001 [*] Implicitly concatenated string literals on one line @@ -316,10 +291,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -85 | _ = "\\12""0" # fix should be "\\120" - - _ = "\\\12""0" # fix should be "\\\0120" +86 - _ = "\\\12""0" # fix should be "\\\0120" 86 + _ = "\\\0120" # fix should be "\\\0120" -87 | _ = "\12 0""0" # fix should be "\12 00" | ISC001 [*] Implicitly concatenated string literals on one line @@ -334,10 +307,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -86 | _ = "\\\12""0" # fix should be "\\\0120" - - _ = "\12 0""0" # fix should be "\12 00" +87 - _ = "\12 0""0" # fix should be "\12 00" 87 + _ = "\12 00" # fix should be "\12 00" -88 | _ = r"\12"r"0" # fix should be r"\120" | ISC001 [*] Implicitly concatenated string literals on one line @@ -352,10 +323,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -87 | _ = "\12 0""0" # fix should be "\12 00" - - _ = r"\12"r"0" # fix should be r"\120" +88 - _ = r"\12"r"0" # fix should be r"\120" 88 + _ = r"\120" # fix should be r"\120" -89 | _ = "\12 and more""0" # fix should be "\12 and more0" | ISC001 [*] Implicitly concatenated string literals on one line @@ -370,10 +339,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -88 | _ = r"\12"r"0" # fix should be r"\120" - - _ = "\12 and more""0" # fix should be "\12 and more0" +89 - _ = "\12 and more""0" # fix should be "\12 and more0" 89 + _ = "\12 and more0" # fix should be "\12 and more0" -90 | _ = "\8""0" # fix should be "\80" | ISC001 [*] Implicitly concatenated string literals on one line @@ -388,10 +355,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -89 | _ = "\12 and more""0" # fix should be "\12 and more0" - - _ = "\8""0" # fix should be "\80" +90 - _ = "\8""0" # fix should be "\80" 90 + _ = "\80" # fix should be "\80" -91 | _ = "\12""8" # fix should be "\128" | ISC001 [*] Implicitly concatenated string literals on one line @@ -406,10 +371,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -90 | _ = "\8""0" # fix should be "\80" - - _ = "\12""8" # fix should be "\128" +91 - _ = "\12""8" # fix should be "\128" 91 + _ = "\128" # fix should be "\128" -92 | _ = "\12""foo" # fix should be "\12foo" | ISC001 [*] Implicitly concatenated string literals on one line @@ -423,10 +386,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -91 | _ = "\12""8" # fix should be "\128" - - _ = "\12""foo" # fix should be "\12foo" +92 - _ = "\12""foo" # fix should be "\12foo" 92 + _ = "\12foo" # fix should be "\12foo" -93 | _ = "\12" "" # fix should be "\12" | ISC001 [*] Implicitly concatenated string literals on one line @@ -438,10 +399,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | ^^^^^^^^ help: Combine string literals | -92 | _ = "\12""foo" # fix should be "\12foo" - - _ = "\12" "" # fix should be "\12" +93 - _ = "\12" "" # fix should be "\12" 93 + _ = "\12" # fix should be "\12" -94 | | ISC001 [*] Implicitly concatenated string literals on one line @@ -456,10 +415,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -192 | # ISC001 - - t"The quick " t"brown fox." +193 - t"The quick " t"brown fox." 193 + t"The quick brown fox." -194 | | ISC001 Implicitly concatenated string literals on one line @@ -495,10 +452,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -205 | # nested examples with both t and f-strings - - _ = "a" f"b {t"c" t"d"} e" "f" +206 - _ = "a" f"b {t"c" t"d"} e" "f" 206 + _ = "a" f"b {t"cd"} e" "f" -207 | _ = t"b {f"c" f"d {t"e" t"f"} g"} h" | ISC001 [*] Implicitly concatenated string literals on one line @@ -513,10 +468,8 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -206 | _ = "a" f"b {t"c" t"d"} e" "f" - - _ = t"b {f"c" f"d {t"e" t"f"} g"} h" +207 - _ = t"b {f"c" f"d {t"e" t"f"} g"} h" 207 + _ = t"b {f"cd {t"e" t"f"} g"} h" -208 | _ = f"b {t"abc" \ | ISC001 [*] Implicitly concatenated string literals on one line @@ -531,8 +484,6 @@ ISC001 [*] Implicitly concatenated string literals on one line | help: Combine string literals | -206 | _ = "a" f"b {t"c" t"d"} e" "f" - - _ = t"b {f"c" f"d {t"e" t"f"} g"} h" +207 - _ = t"b {f"c" f"d {t"e" t"f"} g"} h" 207 + _ = t"b {f"c" f"d {t"ef"} g"} h" -208 | _ = f"b {t"abc" \ | diff --git a/crates/ruff_linter/src/rules/flake8_import_conventions/snapshots/ruff_linter__rules__flake8_import_conventions__tests__defaults.snap b/crates/ruff_linter/src/rules/flake8_import_conventions/snapshots/ruff_linter__rules__flake8_import_conventions__tests__defaults.snap index 7a919ec733cc4..bd72900e5d838 100644 --- a/crates/ruff_linter/src/rules/flake8_import_conventions/snapshots/ruff_linter__rules__flake8_import_conventions__tests__defaults.snap +++ b/crates/ruff_linter/src/rules/flake8_import_conventions/snapshots/ruff_linter__rules__flake8_import_conventions__tests__defaults.snap @@ -12,11 +12,8 @@ ICN001 [*] `altair` should be imported as `alt` | help: Alias `altair` to `alt` | -5 | def unconventional(): - - import altair -6 + import altair as alt -7 | import matplotlib.pyplot - | +6 | import altair as alt + | ++++++ note: This is an unsafe fix and may change runtime behavior ICN001 `matplotlib.pyplot` should be imported as `plt` @@ -43,11 +40,8 @@ ICN001 [*] `numpy` should be imported as `np` | help: Alias `numpy` to `np` | -7 | import matplotlib.pyplot - - import numpy -8 + import numpy as np -9 | import pandas - | +8 | import numpy as np + | +++++ note: This is an unsafe fix and may change runtime behavior ICN001 [*] `pandas` should be imported as `pd` @@ -61,12 +55,9 @@ ICN001 [*] `pandas` should be imported as `pd` 11 | import tkinter | help: Alias `pandas` to `pd` - | -8 | import numpy - - import pandas -9 + import pandas as pd -10 | import seaborn - | + | +9 | import pandas as pd + | +++++ note: This is an unsafe fix and may change runtime behavior ICN001 [*] `seaborn` should be imported as `sns` @@ -81,11 +72,8 @@ ICN001 [*] `seaborn` should be imported as `sns` | help: Alias `seaborn` to `sns` | -9 | import pandas - - import seaborn -10 + import seaborn as sns -11 | import tkinter - | +10 | import seaborn as sns + | ++++++ note: This is an unsafe fix and may change runtime behavior ICN001 [*] `tkinter` should be imported as `tk` @@ -99,11 +87,8 @@ ICN001 [*] `tkinter` should be imported as `tk` | help: Alias `tkinter` to `tk` | -10 | import seaborn - - import tkinter -11 + import tkinter as tk -12 | import networkx - | +11 | import tkinter as tk + | +++++ note: This is an unsafe fix and may change runtime behavior ICN001 [*] `networkx` should be imported as `nx` @@ -115,11 +100,8 @@ ICN001 [*] `networkx` should be imported as `nx` | ^^^^^^^^ help: Alias `networkx` to `nx` | -11 | import tkinter - - import networkx -12 + import networkx as nx -13 | - | +12 | import networkx as nx + | +++++ note: This is an unsafe fix and may change runtime behavior ICN001 [*] `altair` should be imported as `alt` @@ -133,10 +115,8 @@ ICN001 [*] `altair` should be imported as `alt` | help: Alias `altair` to `alt` | -15 | def unconventional_aliases(): - - import altair as altr +16 - import altair as altr 16 + import altair as alt -17 | import matplotlib.pyplot as plot | note: This is an unsafe fix and may change runtime behavior @@ -152,10 +132,8 @@ ICN001 [*] `matplotlib.pyplot` should be imported as `plt` | help: Alias `matplotlib.pyplot` to `plt` | -16 | import altair as altr - - import matplotlib.pyplot as plot +17 - import matplotlib.pyplot as plot 17 + import matplotlib.pyplot as plt -18 | import numpy as nmp | note: This is an unsafe fix and may change runtime behavior @@ -171,10 +149,8 @@ ICN001 [*] `numpy` should be imported as `np` | help: Alias `numpy` to `np` | -17 | import matplotlib.pyplot as plot - - import numpy as nmp +18 - import numpy as nmp 18 + import numpy as np -19 | import pandas as pdas | note: This is an unsafe fix and may change runtime behavior @@ -190,10 +166,8 @@ ICN001 [*] `pandas` should be imported as `pd` | help: Alias `pandas` to `pd` | -18 | import numpy as nmp - - import pandas as pdas +19 - import pandas as pdas 19 + import pandas as pd -20 | import seaborn as sbrn | note: This is an unsafe fix and may change runtime behavior @@ -209,10 +183,8 @@ ICN001 [*] `seaborn` should be imported as `sns` | help: Alias `seaborn` to `sns` | -19 | import pandas as pdas - - import seaborn as sbrn +20 - import seaborn as sbrn 20 + import seaborn as sns -21 | import tkinter as tkr | note: This is an unsafe fix and may change runtime behavior @@ -227,10 +199,8 @@ ICN001 [*] `tkinter` should be imported as `tk` | help: Alias `tkinter` to `tk` | -20 | import seaborn as sbrn - - import tkinter as tkr +21 - import tkinter as tkr 21 + import tkinter as tk -22 | import networkx as nxy | note: This is an unsafe fix and may change runtime behavior @@ -243,9 +213,7 @@ ICN001 [*] `networkx` should be imported as `nx` | ^^^ help: Alias `networkx` to `nx` | -21 | import tkinter as tkr - - import networkx as nxy +22 - import networkx as nxy 22 + import networkx as nx -23 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_import_conventions/snapshots/ruff_linter__rules__flake8_import_conventions__tests__same_name.snap b/crates/ruff_linter/src/rules/flake8_import_conventions/snapshots/ruff_linter__rules__flake8_import_conventions__tests__same_name.snap index 430456689a09a..df87bb11cc8ba 100644 --- a/crates/ruff_linter/src/rules/flake8_import_conventions/snapshots/ruff_linter__rules__flake8_import_conventions__tests__same_name.snap +++ b/crates/ruff_linter/src/rules/flake8_import_conventions/snapshots/ruff_linter__rules__flake8_import_conventions__tests__same_name.snap @@ -9,8 +9,6 @@ ICN001 [*] `django.conf.settings` should be imported as `settings` | ^ help: Alias `django.conf.settings` to `settings` | -9 | def unconventional_alias(): - - from django.conf import settings as s -10 + from django.conf import settings as settings - | +10 | from django.conf import settings as settings + | +++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_import_conventions/snapshots/ruff_linter__rules__flake8_import_conventions__tests__tricky.snap b/crates/ruff_linter/src/rules/flake8_import_conventions/snapshots/ruff_linter__rules__flake8_import_conventions__tests__tricky.snap index 199fda2353358..812400a45252d 100644 --- a/crates/ruff_linter/src/rules/flake8_import_conventions/snapshots/ruff_linter__rules__flake8_import_conventions__tests__tricky.snap +++ b/crates/ruff_linter/src/rules/flake8_import_conventions/snapshots/ruff_linter__rules__flake8_import_conventions__tests__tricky.snap @@ -13,11 +13,7 @@ ICN001 [*] `pandas` should be imported as `pd` | help: Alias `pandas` to `pd` | -5 | try: - - global pandas - - import pandas -6 + global pd -7 + import pandas as pd -8 | except ImportError: +6 ~ global pd +7 ~ import pandas as pd | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG001_LOG001.py.snap b/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG001_LOG001.py.snap index 0999876c88c6e..38984a06d800a 100644 --- a/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG001_LOG001.py.snap +++ b/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG001_LOG001.py.snap @@ -13,10 +13,9 @@ LOG001 [*] Use `logging.getLogger()` to instantiate loggers | help: Replace with `logging.getLogger()` | +1 ~ import logging 2 | - - logging.Logger(__name__) -3 + logging.getLogger(__name__) -4 | logging.Logger() +3 ~ logging.getLogger(__name__) | note: This is an unsafe fix and may change runtime behavior @@ -30,9 +29,9 @@ LOG001 [*] Use `logging.getLogger()` to instantiate loggers | help: Replace with `logging.getLogger()` | +1 ~ import logging +2 | 3 | logging.Logger(__name__) - - logging.Logger() -4 + logging.getLogger() -5 | logging.getLogger(__name__) +4 ~ logging.getLogger() | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG002_LOG002.py.snap b/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG002_LOG002.py.snap index f3a695620c538..0f0690dfa64fe 100644 --- a/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG002_LOG002.py.snap +++ b/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG002_LOG002.py.snap @@ -11,10 +11,8 @@ LOG002 [*] Use `__name__` with `logging.getLogger()` | help: Replace with `__name__` | -10 | # LOG002 - - getLogger(__file__) +11 - getLogger(__file__) 11 + getLogger(__name__) -12 | logging.getLogger(name=__file__) | note: This is an unsafe fix and may change runtime behavior @@ -30,10 +28,8 @@ LOG002 [*] Use `__name__` with `logging.getLogger()` | help: Replace with `__name__` | -11 | getLogger(__file__) - - logging.getLogger(name=__file__) +12 - logging.getLogger(name=__file__) 12 + logging.getLogger(name=__name__) -13 | | note: This is an unsafe fix and may change runtime behavior @@ -48,10 +44,8 @@ LOG002 [*] Use `__name__` with `logging.getLogger()` | help: Replace with `__name__` | -13 | - - logging.getLogger(__cached__) +14 - logging.getLogger(__cached__) 14 + logging.getLogger(__name__) -15 | getLogger(name=__cached__) | note: This is an unsafe fix and may change runtime behavior @@ -63,9 +57,7 @@ LOG002 [*] Use `__name__` with `logging.getLogger()` | ^^^^^^^^^^ help: Replace with `__name__` | -14 | logging.getLogger(__cached__) - - getLogger(name=__cached__) +15 - getLogger(name=__cached__) 15 + getLogger(name=__name__) -16 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG004_LOG004_0.py.snap b/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG004_LOG004_0.py.snap index e6bbb3636a98e..8f29eec11198b 100644 --- a/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG004_LOG004_0.py.snap +++ b/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG004_LOG004_0.py.snap @@ -13,10 +13,8 @@ LOG004 [*] `.exception()` call outside exception handlers | help: Replace with `.error()` | -12 | - - logging.exception("") +13 - logging.exception("") 13 + logging.error("") -14 | logger.exception("") | note: This is an unsafe fix and may change runtime behavior @@ -30,10 +28,8 @@ LOG004 [*] `.exception()` call outside exception handlers | help: Replace with `.error()` | -13 | logging.exception("") - - logger.exception("") +14 - logger.exception("") 14 + logger.error("") -15 | exc("") | note: This is an unsafe fix and may change runtime behavior @@ -57,10 +53,8 @@ LOG004 [*] `.exception()` call outside exception handlers | help: Replace with `.error()` | -18 | def _(): - - logging.exception("") +19 - logging.exception("") 19 + logging.error("") -20 | logger.exception("") | note: This is an unsafe fix and may change runtime behavior @@ -75,10 +69,8 @@ LOG004 [*] `.exception()` call outside exception handlers | help: Replace with `.error()` | -19 | logging.exception("") - - logger.exception("") +20 - logger.exception("") 20 + logger.error("") -21 | exc("") | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG004_LOG004_1.py.snap b/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG004_LOG004_1.py.snap index 96ff758efacc7..0c8293c8a8323 100644 --- a/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG004_LOG004_1.py.snap +++ b/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG004_LOG004_1.py.snap @@ -8,8 +8,7 @@ LOG004 [*] `.exception()` call outside exception handlers | ^^^^^^^^^^^^^^^^^^^^ help: Replace with `.error()` | -3 | - - logger.exception("") +4 - logger.exception("") 4 + logger.error("") | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG009_LOG009.py.snap b/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG009_LOG009.py.snap index 7b1574d0a3638..c327c4909dacc 100644 --- a/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG009_LOG009.py.snap +++ b/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG009_LOG009.py.snap @@ -12,10 +12,9 @@ LOG009 [*] Use of undocumented `logging.WARN` constant | help: Replace `logging.WARN` with `logging.WARNING` | +2 ~ import logging 3 | - - logging.WARN # LOG009 -4 + logging.WARNING # LOG009 -5 | logging.WARNING # OK +4 ~ logging.WARNING # LOG009 | LOG009 [*] Use of undocumented `logging.WARN` constant @@ -29,8 +28,7 @@ LOG009 [*] Use of undocumented `logging.WARN` constant | help: Replace `logging.WARN` with `logging.WARNING` | + 9 ~ from logging import WARN, WARNING 10 | - - WARN # LOG009 -11 + WARNING # LOG009 -12 | WARNING # OK +11 ~ WARNING # LOG009 | diff --git a/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG014_LOG014_0.py.snap b/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG014_LOG014_0.py.snap index 9aa12dfdc3799..bfb20487dfdd1 100644 --- a/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG014_LOG014_0.py.snap +++ b/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG014_LOG014_0.py.snap @@ -12,10 +12,8 @@ LOG014 [*] `exc_info=` outside exception handlers | help: Remove `exc_info=` | -11 | - - logging.info("", exc_info=True) +12 - logging.info("", exc_info=True) 12 + logging.info("") -13 | logger.info("", exc_info=True) | note: This is an unsafe fix and may change runtime behavior @@ -27,10 +25,8 @@ LOG014 [*] `exc_info=` outside exception handlers | ^^^^^^^^^^^^^ help: Remove `exc_info=` | -12 | logging.info("", exc_info=True) - - logger.info("", exc_info=True) +13 - logger.info("", exc_info=True) 13 + logger.info("") -14 | | note: This is an unsafe fix and may change runtime behavior @@ -43,10 +39,8 @@ LOG014 [*] `exc_info=` outside exception handlers | help: Remove `exc_info=` | -15 | - - logging.info("", exc_info=1) +16 - logging.info("", exc_info=1) 16 + logging.info("") -17 | logger.info("", exc_info=1) | note: This is an unsafe fix and may change runtime behavior @@ -58,10 +52,8 @@ LOG014 [*] `exc_info=` outside exception handlers | ^^^^^^^^^^ help: Remove `exc_info=` | -16 | logging.info("", exc_info=1) - - logger.info("", exc_info=1) +17 - logger.info("", exc_info=1) 17 + logger.info("") -18 | | note: This is an unsafe fix and may change runtime behavior @@ -75,10 +67,8 @@ LOG014 [*] `exc_info=` outside exception handlers | help: Remove `exc_info=` | -20 | def _(): - - logging.info("", exc_info=True) +21 - logging.info("", exc_info=True) 21 + logging.info("") -22 | logger.info("", exc_info=True) | note: This is an unsafe fix and may change runtime behavior @@ -91,9 +81,7 @@ LOG014 [*] `exc_info=` outside exception handlers | ^^^^^^^^^^^^^ help: Remove `exc_info=` | -21 | logging.info("", exc_info=True) - - logger.info("", exc_info=True) +22 - logger.info("", exc_info=True) 22 + logger.info("") -23 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG014_LOG014_1.py.snap b/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG014_LOG014_1.py.snap index 79c6d2f14bfea..3ece6588b107e 100644 --- a/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG014_LOG014_1.py.snap +++ b/crates/ruff_linter/src/rules/flake8_logging/snapshots/ruff_linter__rules__flake8_logging__tests__LOG014_LOG014_1.py.snap @@ -8,8 +8,7 @@ LOG014 [*] `exc_info=` outside exception handlers | ^^^^^^^^^^^^^ help: Remove `exc_info=` | -3 | - - logger.info("", exc_info=True) +4 - logger.info("", exc_info=True) 4 + logger.info("") | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_logging_format/snapshots/ruff_linter__rules__flake8_logging_format__tests__G010.py.snap b/crates/ruff_linter/src/rules/flake8_logging_format/snapshots/ruff_linter__rules__flake8_logging_format__tests__G010.py.snap index 113a2b4ae3893..367e0f9a23cbc 100644 --- a/crates/ruff_linter/src/rules/flake8_logging_format/snapshots/ruff_linter__rules__flake8_logging_format__tests__G010.py.snap +++ b/crates/ruff_linter/src/rules/flake8_logging_format/snapshots/ruff_linter__rules__flake8_logging_format__tests__G010.py.snap @@ -13,11 +13,8 @@ G010 [*] Logging statement uses `warn` instead of `warning` | help: Convert to `warning` | -5 | - - logging.warn("Hello World!") -6 + logging.warning("Hello World!") -7 | log.warn("Hello world!") # This shouldn't be considered as a logger candidate - | +6 | logging.warning("Hello World!") + | +++ G010 [*] Logging statement uses `warn` instead of `warning` --> G010.py:8:8 @@ -31,11 +28,8 @@ G010 [*] Logging statement uses `warn` instead of `warning` | help: Convert to `warning` | -7 | log.warn("Hello world!") # This shouldn't be considered as a logger candidate - - logger.warn("Hello world!") -8 + logger.warning("Hello world!") -9 | - | +8 | logger.warning("Hello world!") + | +++ G010 [*] Logging statement uses `warn` instead of `warning` --> G010.py:10:11 @@ -49,11 +43,8 @@ G010 [*] Logging statement uses `warn` instead of `warning` | help: Convert to `warning` | -9 | - - logging . warn("Hello World!") -10 + logging . warning("Hello World!") -11 | - | +10 | logging . warning("Hello World!") + | +++ G010 [*] Logging statement uses `warn` instead of `warning` --> G010.py:13:1 @@ -66,9 +57,5 @@ G010 [*] Logging statement uses `warn` instead of `warning` | help: Convert to `warning` | -12 | from logging import warn, warning, exception - - warn("foo") 13 | warning("foo") -14 + warning("foo") -15 | exception("foo") - | + | +++ diff --git a/crates/ruff_linter/src/rules/flake8_logging_format/snapshots/ruff_linter__rules__flake8_logging_format__tests__preview__G004_G004.py.snap b/crates/ruff_linter/src/rules/flake8_logging_format/snapshots/ruff_linter__rules__flake8_logging_format__tests__preview__G004_G004.py.snap index 6921cae7d97d4..7f9d811e82ca4 100644 --- a/crates/ruff_linter/src/rules/flake8_logging_format/snapshots/ruff_linter__rules__flake8_logging_format__tests__preview__G004_G004.py.snap +++ b/crates/ruff_linter/src/rules/flake8_logging_format/snapshots/ruff_linter__rules__flake8_logging_format__tests__preview__G004_G004.py.snap @@ -11,10 +11,8 @@ G004 [*] Logging statement uses f-string | help: Convert to lazy `%` formatting | -3 | name = "world" - - logging.info(f"Hello {name}") +4 - logging.info(f"Hello {name}") 4 + logging.info("Hello %s", name) -5 | logging.log(logging.INFO, f"Hello {name}") | G004 [*] Logging statement uses f-string @@ -29,10 +27,8 @@ G004 [*] Logging statement uses f-string | help: Convert to lazy `%` formatting | -4 | logging.info(f"Hello {name}") - - logging.log(logging.INFO, f"Hello {name}") +5 - logging.log(logging.INFO, f"Hello {name}") 5 + logging.log(logging.INFO, "Hello %s", name) -6 | | G004 [*] Logging statement uses f-string @@ -46,10 +42,8 @@ G004 [*] Logging statement uses f-string | help: Convert to lazy `%` formatting | -7 | _LOGGER = logging.getLogger() - - _LOGGER.info(f"{__name__}") +8 - _LOGGER.info(f"{__name__}") 8 + _LOGGER.info("%s", __name__) -9 | | G004 [*] Logging statement uses f-string @@ -64,10 +58,8 @@ G004 [*] Logging statement uses f-string | help: Convert to lazy `%` formatting | -9 | - - logging.getLogger().info(f"{name}") +10 - logging.getLogger().info(f"{name}") 10 + logging.getLogger().info("%s", name) -11 | | G004 [*] Logging statement uses f-string @@ -81,10 +73,8 @@ G004 [*] Logging statement uses f-string | help: Convert to lazy `%` formatting | -13 | - - info(f"{name}") +14 - info(f"{name}") 14 + info("%s", name) -15 | info(f"{__name__}") | G004 [*] Logging statement uses f-string @@ -98,10 +88,8 @@ G004 [*] Logging statement uses f-string | help: Convert to lazy `%` formatting | -14 | info(f"{name}") - - info(f"{__name__}") +15 - info(f"{__name__}") 15 + info("%s", __name__) -16 | | G004 [*] Logging statement uses f-string @@ -113,10 +101,8 @@ G004 [*] Logging statement uses f-string | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Convert to lazy `%` formatting | -23 | directory_path = "/home/hamir/ruff/crates/ruff_linter/resources/test/" - - logging.info(f"{count} out of {total} files in {directory_path} checked") +24 - logging.info(f"{count} out of {total} files in {directory_path} checked") 24 + logging.info("%s out of %s files in %s checked", count, total, directory_path) -25 | | G004 Logging statement uses f-string diff --git a/crates/ruff_linter/src/rules/flake8_logging_format/snapshots/ruff_linter__rules__flake8_logging_format__tests__preview__G004_G004_implicit_concat.py.snap b/crates/ruff_linter/src/rules/flake8_logging_format/snapshots/ruff_linter__rules__flake8_logging_format__tests__preview__G004_G004_implicit_concat.py.snap index 5aa21a2be0a63..2e509892e2a2f 100644 --- a/crates/ruff_linter/src/rules/flake8_logging_format/snapshots/ruff_linter__rules__flake8_logging_format__tests__preview__G004_G004_implicit_concat.py.snap +++ b/crates/ruff_linter/src/rules/flake8_logging_format/snapshots/ruff_linter__rules__flake8_logging_format__tests__preview__G004_G004_implicit_concat.py.snap @@ -12,10 +12,8 @@ G004 [*] Logging statement uses f-string | help: Convert to lazy `%` formatting | -5 | log = logging.getLogger(__name__) - - log.info(f"a" f"b {variablename}") +6 - log.info(f"a" f"b {variablename}") 6 + log.info("ab %s", variablename) -7 | log.info("a " f"b {variablename}") | G004 [*] Logging statement uses f-string @@ -29,10 +27,8 @@ G004 [*] Logging statement uses f-string | help: Convert to lazy `%` formatting | -6 | log.info(f"a" f"b {variablename}") - - log.info("a " f"b {variablename}") +7 - log.info("a " f"b {variablename}") 7 + log.info("a b %s", variablename) -8 | log.info("prefix " f"middle {variablename}" f" suffix") | G004 [*] Logging statement uses f-string @@ -44,7 +40,6 @@ G004 [*] Logging statement uses f-string | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Convert to lazy `%` formatting | -7 | log.info("a " f"b {variablename}") - - log.info("prefix " f"middle {variablename}" f" suffix") +8 - log.info("prefix " f"middle {variablename}" f" suffix") 8 + log.info("prefix middle %s suffix", variablename) | diff --git a/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE790_PIE790.py.snap b/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE790_PIE790.py.snap index d429ead79e01b..94073ee3a657a 100644 --- a/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE790_PIE790.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE790_PIE790.py.snap @@ -10,9 +10,7 @@ PIE790 [*] Unnecessary `pass` statement | ^^^^ help: Remove unnecessary `pass` | -3 | - - pass -4 | +4 - pass | PIE790 [*] Unnecessary `pass` statement @@ -23,11 +21,9 @@ PIE790 [*] Unnecessary `pass` statement 9 | pass | ^^^^ help: Remove unnecessary `pass` - | -8 | """foo""" - - pass -9 | - | + | + 9 - pass + | PIE790 [*] Unnecessary `pass` statement --> PIE790.py:14:5 @@ -38,10 +34,8 @@ PIE790 [*] Unnecessary `pass` statement | ^^^^ help: Remove unnecessary `pass` | -13 | """This is a function.""" - - pass; print("hello") +14 - pass; print("hello") 14 + print("hello") -15 | | PIE790 [*] Unnecessary `pass` statement @@ -53,9 +47,7 @@ PIE790 [*] Unnecessary `pass` statement | ^^^^ help: Remove unnecessary `pass` | -20 | """bar""" - - pass -21 | +21 - pass | PIE790 [*] Unnecessary `pass` statement @@ -67,9 +59,7 @@ PIE790 [*] Unnecessary `pass` statement | ^^^^ help: Remove unnecessary `pass` | -27 | """bar""" - - pass -28 | +28 - pass | PIE790 [*] Unnecessary `pass` statement @@ -81,9 +71,7 @@ PIE790 [*] Unnecessary `pass` statement | ^^^^ help: Remove unnecessary `pass` | -34 | """bar""" - - pass -35 | +35 - pass | PIE790 [*] Unnecessary `pass` statement @@ -95,9 +83,7 @@ PIE790 [*] Unnecessary `pass` statement | ^^^^ help: Remove unnecessary `pass` | -41 | """bar""" - - pass -42 | +42 - pass | PIE790 [*] Unnecessary `pass` statement @@ -109,9 +95,7 @@ PIE790 [*] Unnecessary `pass` statement | ^^^^ help: Remove unnecessary `pass` | -49 | - - pass -50 | +50 - pass | PIE790 [*] Unnecessary `pass` statement @@ -123,9 +107,7 @@ PIE790 [*] Unnecessary `pass` statement | ^^^^ help: Remove unnecessary `pass` | -57 | - - pass -58 | +58 - pass | PIE790 [*] Unnecessary `pass` statement @@ -140,9 +122,7 @@ PIE790 [*] Unnecessary `pass` statement | help: Remove unnecessary `pass` | -64 | """ - - pass -65 | except ValueError: +65 - pass | PIE790 [*] Unnecessary `pass` statement @@ -154,9 +134,7 @@ PIE790 [*] Unnecessary `pass` statement | ^^^^ help: Remove unnecessary `pass` | -73 | """bar""" - - pass -74 | +74 - pass | PIE790 [*] Unnecessary `pass` statement @@ -171,9 +149,7 @@ PIE790 [*] Unnecessary `pass` statement | help: Remove unnecessary `pass` | -78 | """buzz""" - - pass -79 | +79 - pass | PIE790 [*] Unnecessary `pass` statement @@ -188,9 +164,7 @@ PIE790 [*] Unnecessary `pass` statement | help: Remove unnecessary `pass` | -82 | """buzz""" - - pass -83 | +83 - pass | PIE790 [*] Unnecessary `pass` statement @@ -202,9 +176,7 @@ PIE790 [*] Unnecessary `pass` statement | ^^^^ help: Remove unnecessary `pass` | -86 | """buzz""" - - pass -87 | +87 - pass | PIE790 [*] Unnecessary `pass` statement @@ -219,9 +191,7 @@ PIE790 [*] Unnecessary `pass` statement | help: Remove unnecessary `pass` | -91 | """buzz""" - - pass -92 | +92 - pass | PIE790 [*] Unnecessary `pass` statement @@ -233,9 +203,7 @@ PIE790 [*] Unnecessary `pass` statement | ^^^^ help: Remove unnecessary `pass` | -95 | """buzz""" - - pass -96 | +96 - pass | PIE790 [*] Unnecessary `pass` statement @@ -247,10 +215,8 @@ PIE790 [*] Unnecessary `pass` statement | ^^^^ help: Remove unnecessary `pass` | -100 | """buzz""" - - pass # bar +101 - pass # bar 101 + # bar -102 | | PIE790 [*] Unnecessary `pass` statement @@ -262,9 +228,7 @@ PIE790 [*] Unnecessary `pass` statement | ^^^^ help: Remove unnecessary `pass` | -129 | print("foo") - - pass -130 | +130 - pass | PIE790 [*] Unnecessary `pass` statement @@ -276,9 +240,7 @@ PIE790 [*] Unnecessary `pass` statement | ^^^^ help: Remove unnecessary `pass` | -135 | print("foo") - - pass -136 | +136 - pass | PIE790 [*] Unnecessary `pass` statement @@ -291,9 +253,7 @@ PIE790 [*] Unnecessary `pass` statement | help: Remove unnecessary `pass` | -140 | pass - - pass -141 | +140 - pass | PIE790 [*] Unnecessary `pass` statement @@ -308,9 +268,7 @@ PIE790 [*] Unnecessary `pass` statement | help: Remove unnecessary `pass` | -140 | pass - - pass -141 | +141 - pass | PIE790 [*] Unnecessary `pass` statement @@ -324,9 +282,7 @@ PIE790 [*] Unnecessary `pass` statement | help: Remove unnecessary `pass` | -143 | for i in range(10): - - pass -144 | +144 - pass | PIE790 [*] Unnecessary `pass` statement @@ -341,9 +297,7 @@ PIE790 [*] Unnecessary `pass` statement | help: Remove unnecessary `pass` | -145 | - - pass -146 | +146 - pass | PIE790 [*] Unnecessary `pass` statement @@ -356,10 +310,8 @@ PIE790 [*] Unnecessary `pass` statement | help: Remove unnecessary `pass` | -148 | for i in range(10): - - pass # comment +149 - pass # comment 149 + # comment -150 | pass | PIE790 [*] Unnecessary `pass` statement @@ -371,9 +323,7 @@ PIE790 [*] Unnecessary `pass` statement | ^^^^ help: Remove unnecessary `pass` | -149 | pass # comment - - pass -150 | +150 - pass | PIE790 [*] Unnecessary `...` literal @@ -385,9 +335,7 @@ PIE790 [*] Unnecessary `...` literal | ^^^ help: Remove unnecessary `...` | -154 | print("foo") - - ... -155 | +155 - ... | PIE790 [*] Unnecessary `...` literal @@ -399,9 +347,7 @@ PIE790 [*] Unnecessary `...` literal | ^^^ help: Remove unnecessary `...` | -160 | print("foo") - - ... -161 | +161 - ... | PIE790 [*] Unnecessary `...` literal @@ -414,9 +360,7 @@ PIE790 [*] Unnecessary `...` literal | help: Remove unnecessary `...` | -165 | ... - - ... -166 | +165 - ... | PIE790 [*] Unnecessary `...` literal @@ -431,9 +375,7 @@ PIE790 [*] Unnecessary `...` literal | help: Remove unnecessary `...` | -165 | ... - - ... -166 | +166 - ... | PIE790 [*] Unnecessary `...` literal @@ -447,9 +389,7 @@ PIE790 [*] Unnecessary `...` literal | help: Remove unnecessary `...` | -168 | for i in range(10): - - ... -169 | +169 - ... | PIE790 [*] Unnecessary `...` literal @@ -464,9 +404,7 @@ PIE790 [*] Unnecessary `...` literal | help: Remove unnecessary `...` | -170 | - - ... -171 | +171 - ... | PIE790 [*] Unnecessary `...` literal @@ -479,10 +417,8 @@ PIE790 [*] Unnecessary `...` literal | help: Remove unnecessary `...` | -173 | for i in range(10): - - ... # comment +174 - ... # comment 174 + # comment -175 | ... | PIE790 [*] Unnecessary `...` literal @@ -497,9 +433,7 @@ PIE790 [*] Unnecessary `...` literal | help: Remove unnecessary `...` | -174 | ... # comment - - ... -175 | +175 - ... | PIE790 [*] Unnecessary `...` literal @@ -512,9 +446,7 @@ PIE790 [*] Unnecessary `...` literal | help: Remove unnecessary `...` | -177 | for i in range(10): - - ... -178 | pass +178 - ... | PIE790 [*] Unnecessary `pass` statement @@ -529,9 +461,7 @@ PIE790 [*] Unnecessary `pass` statement | help: Remove unnecessary `pass` | -178 | ... - - pass -179 | +179 - pass | PIE790 [*] Unnecessary `...` literal @@ -543,9 +473,7 @@ PIE790 [*] Unnecessary `...` literal | ^^^ help: Remove unnecessary `...` | -208 | """Docstring""" - - ... -209 | +209 - ... | PIE790 [*] Unnecessary `pass` statement @@ -560,9 +488,7 @@ PIE790 [*] Unnecessary `pass` statement | help: Remove unnecessary `pass` | -240 | class PotentialDocstring1: - - pass -241 | """ +241 - pass | note: This is an unsafe fix and may change runtime behavior @@ -576,8 +502,6 @@ PIE790 [*] Unnecessary `...` literal | help: Remove unnecessary `...` | -247 | class PotentialDocstring2: - - ... -248 | 'Lorem ipsum dolor sit amet.' +248 - ... | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE794_PIE794.py.snap b/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE794_PIE794.py.snap index 72a0b2dbcf172..42125ca32a0e7 100644 --- a/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE794_PIE794.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE794_PIE794.py.snap @@ -13,9 +13,7 @@ PIE794 [*] Class field `name` is defined multiple times | help: Remove duplicate field definition for `name` | -3 | # .... - - name = StringField() # PIE794 -4 | +4 - name = StringField() # PIE794 | note: This is an unsafe fix and may change runtime behavior @@ -31,9 +29,7 @@ PIE794 [*] Class field `name` is defined multiple times | help: Remove duplicate field definition for `name` | -12 | # .... - - name = StringField() # PIE794 -13 | +13 - name = StringField() # PIE794 | note: This is an unsafe fix and may change runtime behavior @@ -46,9 +42,7 @@ PIE794 [*] Class field `bar` is defined multiple times | ^^^^^^^^^^^^^^^^^^^ help: Remove duplicate field definition for `bar` | -22 | # ... - - bar = StringField() # PIE794 -23 | +23 - bar = StringField() # PIE794 | note: This is an unsafe fix and may change runtime behavior @@ -61,9 +55,7 @@ PIE794 [*] Class field `bar` is defined multiple times | ^^^^^^^^^^^^^^^^^^^ help: Remove duplicate field definition for `bar` | -39 | # ... - - bar = StringField() # PIE794 -40 | +40 - bar = StringField() # PIE794 | note: This is an unsafe fix and may change runtime behavior @@ -76,9 +68,7 @@ PIE794 [*] Class field `name` is defined multiple times | ^^^^^^^^^^^^ help: Remove duplicate field definition for `name` | -45 | name = name + " Bar" - - name = "Bar" # PIE794 -46 | +46 - name = "Bar" # PIE794 | note: This is an unsafe fix and may change runtime behavior @@ -91,9 +81,7 @@ PIE794 [*] Class field `name` is defined multiple times | ^^^^^^^^^^^^^^^^^ help: Remove duplicate field definition for `name` | -51 | name: str = name + " Bar" - - name: str = "Bar" # PIE794 -52 | +52 - name: str = "Bar" # PIE794 | note: This is an unsafe fix and may change runtime behavior @@ -106,7 +94,6 @@ PIE794 [*] Class field `start_line` is defined multiple times | ^^^^^^^^^^^^^^^ help: Remove duplicate field definition for `start_line` | -56 | start_line: int - - start_line: int # PIE794 +57 - start_line: int # PIE794 | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE800_PIE800.py.snap b/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE800_PIE800.py.snap index 52ba224af0b36..e81161e8237cd 100644 --- a/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE800_PIE800.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE800_PIE800.py.snap @@ -11,9 +11,8 @@ PIE800 [*] Unnecessary spread `**` | help: Remove unnecessary dict | - - {"foo": 1, **{"bar": 1}} # PIE800 +1 - {"foo": 1, **{"bar": 1}} # PIE800 1 + {"foo": 1, "bar": 1} # PIE800 -2 | | PIE800 [*] Unnecessary spread `**` @@ -28,10 +27,8 @@ PIE800 [*] Unnecessary spread `**` | help: Remove unnecessary dict | -2 | - - {**{"bar": 10}, "a": "b"} # PIE800 +3 - {**{"bar": 10}, "a": "b"} # PIE800 3 + {"bar": 10, "a": "b"} # PIE800 -4 | | PIE800 [*] Unnecessary spread `**` @@ -46,10 +43,8 @@ PIE800 [*] Unnecessary spread `**` | help: Remove unnecessary dict | -4 | - - foo({**foo, **{"bar": True}}) # PIE800 +5 - foo({**foo, **{"bar": True}}) # PIE800 5 + foo({**foo, "bar": True}) # PIE800 -6 | | PIE800 [*] Unnecessary spread `**` @@ -64,10 +59,8 @@ PIE800 [*] Unnecessary spread `**` | help: Remove unnecessary dict | -6 | - - {**foo, **{"bar": 10}} # PIE800 +7 - {**foo, **{"bar": 10}} # PIE800 7 + {**foo, "bar": 10} # PIE800 -8 | | PIE800 [*] Unnecessary spread `**` @@ -86,16 +79,11 @@ PIE800 [*] Unnecessary spread `**` | help: Remove unnecessary dict | -11 | # Preserve - - **{ -12 + +12 ~ 13 | # all - - "bar": 10, # the -14 + "bar": 10 # the +14 ~ "bar": 10 # the 15 | # comments - - }, -16 + , -17 | } +16 ~ , | PIE800 [*] Unnecessary spread `**` @@ -110,10 +98,8 @@ PIE800 [*] Unnecessary spread `**` | help: Remove unnecessary dict | -18 | - - {**foo, **buzz, **{bar: 10}} # PIE800 +19 - {**foo, **buzz, **{bar: 10}} # PIE800 19 + {**foo, **buzz, bar: 10} # PIE800 -20 | | PIE800 [*] Unnecessary spread `**` @@ -127,10 +113,8 @@ PIE800 [*] Unnecessary spread `**` | help: Remove unnecessary dict | -23 | "data": [], - - **({"count": 1 if include_count else {}}), +24 - **({"count": 1 if include_count else {}}), 24 + "count": 1 if include_count else {}, -25 | } | PIE800 [*] Unnecessary spread `**` @@ -145,14 +129,9 @@ PIE800 [*] Unnecessary spread `**` | help: Remove unnecessary dict | -28 | "data": [], - - **( # Comment - - { # Comment - - "count": 1 if include_count else {}}), -29 + # Comment -30 + # Comment -31 + "count": 1 if include_count else {}, -32 | } +29 ~ # Comment +30 ~ # Comment +31 ~ "count": 1 if include_count else {}, | PIE800 [*] Unnecessary spread `**` @@ -167,14 +146,9 @@ PIE800 [*] Unnecessary spread `**` | help: Remove unnecessary dict | -35 | "data": [], - - **( - - { - - "count": (a := 1),}), -36 + -37 + -38 + "count": (a := 1), -39 | } +36 ~ +37 ~ +38 ~ "count": (a := 1), | PIE800 [*] Unnecessary spread `**` @@ -191,17 +165,11 @@ PIE800 [*] Unnecessary spread `**` | help: Remove unnecessary dict | -42 | "data": [], - - **( - - { -43 + -44 + +43 ~ +44 ~ 45 | "count": (a := 1) - - } - - ) -46 + -47 + -48 | , +46 ~ +47 ~ | PIE800 [*] Unnecessary spread `**` @@ -218,18 +186,11 @@ PIE800 [*] Unnecessary spread `**` | help: Remove unnecessary dict | -52 | "data": [], - - **( - - { - - "count": (a := 1), # Comment - - } # Comment - - ) # Comment -53 + -54 + -55 + "count": (a := 1) # Comment -56 + # Comment -57 + # Comment -58 | , +53 ~ +54 ~ +55 ~ "count": (a := 1) # Comment +56 ~ # Comment +57 ~ # Comment | PIE800 [*] Unnecessary spread `**` @@ -246,22 +207,13 @@ PIE800 [*] Unnecessary spread `**` | help: Remove unnecessary dict | -62 | "data": [], - - **( # Comment - - ( # Comment - - { # Comment - - "count": (a := 1), # Comment - - } # Comment - - ) - - ) # Comment -63 + # Comment -64 + # Comment -65 + # Comment -66 + "count": (a := 1) # Comment -67 + # Comment -68 + -69 + # Comment -70 | , +63 ~ # Comment +64 ~ # Comment +65 | # Comment +66 ~ "count": (a := 1) # Comment +67 ~ # Comment +68 ~ +69 ~ # Comment | PIE800 [*] Unnecessary spread `**` @@ -278,19 +230,12 @@ PIE800 [*] Unnecessary spread `**` | help: Remove unnecessary dict | -74 | "data": [], - - ** # Foo - - ( # Comment - - { "a": b, -75 + # Foo -76 + # Comment -77 + "a": b +75 ~ # Foo +76 ~ # Comment +77 ~ "a": b 78 | # Comment - - } - - ) , -79 + -80 + , -81 | c: 9, +79 ~ +80 ~ , | PIE800 [*] Unnecessary spread `**` @@ -303,10 +248,8 @@ PIE800 [*] Unnecessary spread `**` | help: Remove unnecessary dict | -85 | # https://github.com/astral-sh/ruff/issues/15997 - - {"a": [], **{},} +86 - {"a": [], **{},} 86 + {"a": [], } -87 | {"a": [], **({}),} | PIE800 [*] Unnecessary spread `**` @@ -321,10 +264,8 @@ PIE800 [*] Unnecessary spread `**` | help: Remove unnecessary dict | -86 | {"a": [], **{},} - - {"a": [], **({}),} +87 - {"a": [], **({}),} 87 + {"a": [], } -88 | | PIE800 [*] Unnecessary spread `**` @@ -338,10 +279,8 @@ PIE800 [*] Unnecessary spread `**` | help: Remove unnecessary dict | -88 | - - {"a": [], **{}, 6: 3} +89 - {"a": [], **{}, 6: 3} 89 + {"a": [], 6: 3} -90 | {"a": [], **({}), 6: 3} | PIE800 [*] Unnecessary spread `**` @@ -355,10 +294,8 @@ PIE800 [*] Unnecessary spread `**` | help: Remove unnecessary dict | -89 | {"a": [], **{}, 6: 3} - - {"a": [], **({}), 6: 3} +90 - {"a": [], **({}), 6: 3} 90 + {"a": [], 6: 3} -91 | | PIE800 [*] Unnecessary spread `**` @@ -376,13 +313,7 @@ PIE800 [*] Unnecessary spread `**` | help: Remove unnecessary dict | -91 | - - {"a": [], **{ -92 + {"a": [], -93 | # Comment - - }, 6: 3} -94 + 6: 3} -95 | {"a": [], **({ +92 ~ {"a": [], | PIE800 [*] Unnecessary spread `**` @@ -397,11 +328,5 @@ PIE800 [*] Unnecessary spread `**` | |_^ help: Remove unnecessary dict | -94 | }, 6: 3} - - {"a": [], **({ -95 + {"a": [], -96 | # Comment - - }), 6: 3} -97 + 6: 3} -98 | +95 ~ {"a": [], | diff --git a/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE804_PIE804.py.snap b/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE804_PIE804.py.snap index d93461856cf4b..5c38871130b10 100644 --- a/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE804_PIE804.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE804_PIE804.py.snap @@ -11,9 +11,8 @@ PIE804 [*] Unnecessary `dict` kwargs | help: Remove unnecessary kwargs | - - foo(**{"bar": True}) # PIE804 +1 - foo(**{"bar": True}) # PIE804 1 + foo(bar=True) # PIE804 -2 | | PIE804 [*] Unnecessary `dict` kwargs @@ -28,10 +27,8 @@ PIE804 [*] Unnecessary `dict` kwargs | help: Remove unnecessary kwargs | -2 | - - foo(**{"r2d2": True}) # PIE804 +3 - foo(**{"r2d2": True}) # PIE804 3 + foo(r2d2=True) # PIE804 -4 | | PIE804 [*] Unnecessary `dict` kwargs @@ -46,10 +43,8 @@ PIE804 [*] Unnecessary `dict` kwargs | help: Remove unnecessary kwargs | -4 | - - Foo.objects.create(**{"bar": True}) # PIE804 +5 - Foo.objects.create(**{"bar": True}) # PIE804 5 + Foo.objects.create(bar=True) # PIE804 -6 | | PIE804 [*] Unnecessary `dict` kwargs @@ -64,10 +59,8 @@ PIE804 [*] Unnecessary `dict` kwargs | help: Remove unnecessary kwargs | -6 | - - Foo.objects.create(**{"_id": some_id}) # PIE804 +7 - Foo.objects.create(**{"_id": some_id}) # PIE804 7 + Foo.objects.create(_id=some_id) # PIE804 -8 | | PIE804 [*] Unnecessary `dict` kwargs @@ -81,12 +74,10 @@ PIE804 [*] Unnecessary `dict` kwargs 11 | foo(**{}) | help: Remove unnecessary kwargs - | -8 | - - Foo.objects.create(**{**bar}) # PIE804 -9 + Foo.objects.create(**bar) # PIE804 -10 | - | + | +9 - Foo.objects.create(**{**bar}) # PIE804 +9 + Foo.objects.create(**bar) # PIE804 + | PIE804 [*] Unnecessary `dict` kwargs --> PIE804.py:11:5 @@ -100,10 +91,8 @@ PIE804 [*] Unnecessary `dict` kwargs | help: Remove unnecessary kwargs | -10 | - - foo(**{}) +11 - foo(**{}) 11 + foo() -12 | | PIE804 [*] Unnecessary `dict` kwargs @@ -118,10 +107,8 @@ PIE804 [*] Unnecessary `dict` kwargs | help: Remove unnecessary kwargs | -21 | abc(**{"for": 3}) - - foo(**{},) +22 - foo(**{},) 22 + foo() -23 | | PIE804 Unnecessary `dict` kwargs @@ -168,10 +155,8 @@ PIE804 [*] Unnecessary `dict` kwargs | help: Remove unnecessary kwargs | -25 | abc(**{'a': b}, **{'a': c}) # PIE804 - - abc(a=1, **{'a': c}, **{'b': c}) # PIE804 +26 - abc(a=1, **{'a': c}, **{'b': c}) # PIE804 26 + abc(a=1, **{'a': c}, b=c) # PIE804 -27 | | PIE804 [*] Unnecessary `dict` kwargs @@ -185,10 +170,8 @@ PIE804 [*] Unnecessary `dict` kwargs | help: Remove unnecessary kwargs | -29 | def foo(): - - abc(foo=1, **{'bar': (bar := 1)}) # PIE804 +30 - abc(foo=1, **{'bar': (bar := 1)}) # PIE804 30 + abc(foo=1, bar=(bar := 1)) # PIE804 -31 | abc(foo=1, **{'bar': (yield 1)}) # PIE804 | PIE804 [*] Unnecessary `dict` kwargs @@ -203,10 +186,8 @@ PIE804 [*] Unnecessary `dict` kwargs | help: Remove unnecessary kwargs | -30 | abc(foo=1, **{'bar': (bar := 1)}) # PIE804 - - abc(foo=1, **{'bar': (yield 1)}) # PIE804 +31 - abc(foo=1, **{'bar': (yield 1)}) # PIE804 31 + abc(foo=1, bar=(yield 1)) # PIE804 -32 | | PIE804 [*] Unnecessary `dict` kwargs @@ -225,14 +206,12 @@ PIE804 [*] Unnecessary `dict` kwargs | help: Remove unnecessary kwargs | -35 | foo( - - **{ - - # Comment 1 - - "x": 1.0, - - # Comment 2 - - "y": 2.0, - - } +36 - **{ +37 - # Comment 1 +38 - "x": 1.0, +39 - # Comment 2 +40 - "y": 2.0, +41 - } 36 + x=1.0, y=2.0 -37 | ) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE807_PIE807.py.snap b/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE807_PIE807.py.snap index 3054374f38a2e..13e7b96bda7ba 100644 --- a/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE807_PIE807.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE807_PIE807.py.snap @@ -12,10 +12,8 @@ PIE807 [*] Prefer `list` over useless lambda | help: Replace with `lambda` with `list` | -2 | class Foo: - - foo: List[str] = field(default_factory=lambda: []) # PIE807 +3 - foo: List[str] = field(default_factory=lambda: []) # PIE807 3 + foo: List[str] = field(default_factory=list) # PIE807 -4 | bar: Dict[str, int] = field(default_factory=lambda: {}) # PIE807 | PIE807 [*] Prefer `dict` over useless lambda @@ -27,10 +25,8 @@ PIE807 [*] Prefer `dict` over useless lambda | ^^^^^^^^^^ help: Replace with `lambda` with `dict` | -3 | foo: List[str] = field(default_factory=lambda: []) # PIE807 - - bar: Dict[str, int] = field(default_factory=lambda: {}) # PIE807 +4 - bar: Dict[str, int] = field(default_factory=lambda: {}) # PIE807 4 + bar: Dict[str, int] = field(default_factory=dict) # PIE807 -5 | | PIE807 [*] Prefer `list` over useless lambda @@ -43,10 +39,8 @@ PIE807 [*] Prefer `list` over useless lambda | help: Replace with `lambda` with `list` | -7 | class FooTable(BaseTable): - - foo = fields.ListField(default=lambda: []) # PIE807 +8 - foo = fields.ListField(default=lambda: []) # PIE807 8 + foo = fields.ListField(default=list) # PIE807 -9 | bar = fields.ListField(default=lambda: {}) # PIE807 | PIE807 [*] Prefer `dict` over useless lambda @@ -57,12 +51,10 @@ PIE807 [*] Prefer `dict` over useless lambda 9 | bar = fields.ListField(default=lambda: {}) # PIE807 | ^^^^^^^^^^ help: Replace with `lambda` with `dict` - | -8 | foo = fields.ListField(default=lambda: []) # PIE807 - - bar = fields.ListField(default=lambda: {}) # PIE807 -9 + bar = fields.ListField(default=dict) # PIE807 -10 | - | + | +9 - bar = fields.ListField(default=lambda: {}) # PIE807 +9 + bar = fields.ListField(default=dict) # PIE807 + | PIE807 [*] Prefer `list` over useless lambda --> PIE807.py:13:28 @@ -74,10 +66,8 @@ PIE807 [*] Prefer `list` over useless lambda | help: Replace with `lambda` with `list` | -12 | class FooTable(BaseTable): - - foo = fields.ListField(lambda: []) # PIE807 +13 - foo = fields.ListField(lambda: []) # PIE807 13 + foo = fields.ListField(list) # PIE807 -14 | bar = fields.ListField(default=lambda: {}) # PIE807 | PIE807 [*] Prefer `dict` over useless lambda @@ -89,8 +79,6 @@ PIE807 [*] Prefer `dict` over useless lambda | ^^^^^^^^^^ help: Replace with `lambda` with `dict` | -13 | foo = fields.ListField(lambda: []) # PIE807 - - bar = fields.ListField(default=lambda: {}) # PIE807 +14 - bar = fields.ListField(default=lambda: {}) # PIE807 14 + bar = fields.ListField(default=dict) # PIE807 -15 | | diff --git a/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE808_PIE808.py.snap b/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE808_PIE808.py.snap index ed12ff97e9f49..e317fd2a9f7c3 100644 --- a/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE808_PIE808.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE808_PIE808.py.snap @@ -12,10 +12,8 @@ PIE808 [*] Unnecessary `start` argument in `range` | help: Remove `start` argument | -1 | # PIE808 - - range(0, 10) +2 - range(0, 10) 2 + range(10) -3 | | PIE808 [*] Unnecessary `start` argument in `range` @@ -29,10 +27,8 @@ PIE808 [*] Unnecessary `start` argument in `range` | help: Remove `start` argument | -4 | import builtins - - builtins.range(0, 10) +5 - builtins.range(0, 10) 5 + builtins.range(10) -6 | | PIE808 [*] Unnecessary `start` argument in `range` @@ -43,10 +39,8 @@ PIE808 [*] Unnecessary `start` argument in `range` | ^ help: Remove `start` argument | -18 | # regression test for https://github.com/astral-sh/ruff/pull/18805 - - range((0), 42) +19 - range((0), 42) 19 + range(42) -20 | | PIE808 [*] Unnecessary `start` argument in `range` @@ -56,7 +50,6 @@ PIE808 [*] Unnecessary `start` argument in `range` | ^ help: Remove `start` argument | -26 | - - range(0, 3) +27 - range(0, 3) 27 + range(3) | diff --git a/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE810_PIE810.py.snap b/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE810_PIE810.py.snap index dd4cdc8a35793..200f2eb24be93 100644 --- a/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE810_PIE810.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pie/snapshots/ruff_linter__rules__flake8_pie__tests__PIE810_PIE810.py.snap @@ -12,10 +12,8 @@ PIE810 [*] Call `startswith` once with a `tuple` | help: Merge into a single `startswith` call | -1 | # error - - obj.startswith("foo") or obj.startswith("bar") +2 - obj.startswith("foo") or obj.startswith("bar") 2 + obj.startswith(("foo", "bar")) -3 | # error | note: This is an unsafe fix and may change runtime behavior @@ -31,10 +29,8 @@ PIE810 [*] Call `endswith` once with a `tuple` | help: Merge into a single `endswith` call | -3 | # error - - obj.endswith("foo") or obj.endswith("bar") +4 - obj.endswith("foo") or obj.endswith("bar") 4 + obj.endswith(("foo", "bar")) -5 | # error | note: This is an unsafe fix and may change runtime behavior @@ -50,10 +46,8 @@ PIE810 [*] Call `startswith` once with a `tuple` | help: Merge into a single `startswith` call | -5 | # error - - obj.startswith(foo) or obj.startswith(bar) +6 - obj.startswith(foo) or obj.startswith(bar) 6 + obj.startswith((foo, bar)) -7 | # error | note: This is an unsafe fix and may change runtime behavior @@ -69,10 +63,8 @@ PIE810 [*] Call `startswith` once with a `tuple` | help: Merge into a single `startswith` call | -7 | # error - - obj.startswith(foo) or obj.startswith("foo") +8 - obj.startswith(foo) or obj.startswith("foo") 8 + obj.startswith((foo, "foo")) -9 | # error | note: This is an unsafe fix and may change runtime behavior @@ -88,10 +80,8 @@ PIE810 [*] Call `startswith` once with a `tuple` | help: Merge into a single `startswith` call | -9 | # error - - obj.endswith(foo) or obj.startswith(foo) or obj.startswith("foo") +10 - obj.endswith(foo) or obj.startswith(foo) or obj.startswith("foo") 10 + obj.endswith(foo) or obj.startswith((foo, "foo")) -11 | | note: This is an unsafe fix and may change runtime behavior @@ -106,10 +96,8 @@ PIE810 [*] Call `startswith` once with a `tuple` | help: Merge into a single `startswith` call | -18 | - - if msg.startswith(x) or msg.startswith(y) or msg.startswith(z): # Error +19 - if msg.startswith(x) or msg.startswith(y) or msg.startswith(z): # Error 19 + if msg.startswith((x, z)) or msg.startswith(y): # Error -20 | print("yes") | note: This is an unsafe fix and may change runtime behavior @@ -124,10 +112,8 @@ PIE810 [*] Call `startswith` once with a `tuple` | help: Merge into a single `startswith` call | -24 | - - if msg.startswith(("h", "e", "l", "l", "o")) or msg.startswith("h") or msg.startswith("w"): # Error +25 - if msg.startswith(("h", "e", "l", "l", "o")) or msg.startswith("h") or msg.startswith("w"): # Error 25 + if msg.startswith(("h", "e", "l", "l", "o", "h", "w")): # Error -26 | print("yes") | note: This is an unsafe fix and may change runtime behavior @@ -142,9 +128,7 @@ PIE810 [*] Call `startswith` once with a `tuple` | help: Merge into a single `startswith` call | -82 | "Regression test for https://github.com/astral-sh/ruff/issues/9663" - - if x.startswith("a") or x.startswith("b") or re.match(r"a\.b", x): +83 - if x.startswith("a") or x.startswith("b") or re.match(r"a\.b", x): 83 + if x.startswith(("a", "b")) or re.match(r"a\.b", x): -84 | print("yes") | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_print/snapshots/ruff_linter__rules__flake8_print__tests__T201_T201.py.snap b/crates/ruff_linter/src/rules/flake8_print/snapshots/ruff_linter__rules__flake8_print__tests__T201_T201.py.snap index c7f5054725c5d..40bcf6771e72e 100644 --- a/crates/ruff_linter/src/rules/flake8_print/snapshots/ruff_linter__rules__flake8_print__tests__T201_T201.py.snap +++ b/crates/ruff_linter/src/rules/flake8_print/snapshots/ruff_linter__rules__flake8_print__tests__T201_T201.py.snap @@ -13,9 +13,7 @@ T201 [*] `print` found | help: Remove `print` | -3 | - - print("Hello, world!") # T201 -4 | print("Hello, world!", file=None) # T201 +4 - print("Hello, world!") # T201 | note: This is an unsafe fix and may change runtime behavior @@ -30,9 +28,7 @@ T201 [*] `print` found | help: Remove `print` | -4 | print("Hello, world!") # T201 - - print("Hello, world!", file=None) # T201 -5 | print("Hello, world!", file=sys.stdout) # T201 +5 - print("Hello, world!", file=None) # T201 | note: This is an unsafe fix and may change runtime behavior @@ -47,9 +43,7 @@ T201 [*] `print` found | help: Remove `print` | -5 | print("Hello, world!", file=None) # T201 - - print("Hello, world!", file=sys.stdout) # T201 -6 | print("Hello, world!", file=sys.stderr) # T201 +6 - print("Hello, world!", file=sys.stdout) # T201 | note: This is an unsafe fix and may change runtime behavior @@ -65,8 +59,6 @@ T201 [*] `print` found | help: Remove `print` | -6 | print("Hello, world!", file=sys.stdout) # T201 - - print("Hello, world!", file=sys.stderr) # T201 -7 | +7 - print("Hello, world!", file=sys.stderr) # T201 | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_print/snapshots/ruff_linter__rules__flake8_print__tests__T203_T203.py.snap b/crates/ruff_linter/src/rules/flake8_print/snapshots/ruff_linter__rules__flake8_print__tests__T203_T203.py.snap index ab7f0c79b31b6..940ec0f42f8bd 100644 --- a/crates/ruff_linter/src/rules/flake8_print/snapshots/ruff_linter__rules__flake8_print__tests__T203_T203.py.snap +++ b/crates/ruff_linter/src/rules/flake8_print/snapshots/ruff_linter__rules__flake8_print__tests__T203_T203.py.snap @@ -13,9 +13,7 @@ T203 [*] `pprint` found | help: Remove `pprint` | -4 | - - pprint("Hello, world!") # T203 -5 | pprint("Hello, world!", stream=None) # T203 +5 - pprint("Hello, world!") # T203 | note: This is an unsafe fix and may change runtime behavior @@ -30,9 +28,7 @@ T203 [*] `pprint` found | help: Remove `pprint` | -5 | pprint("Hello, world!") # T203 - - pprint("Hello, world!", stream=None) # T203 -6 | pprint("Hello, world!", stream=sys.stdout) # T203 +6 - pprint("Hello, world!", stream=None) # T203 | note: This is an unsafe fix and may change runtime behavior @@ -47,9 +43,7 @@ T203 [*] `pprint` found | help: Remove `pprint` | -6 | pprint("Hello, world!", stream=None) # T203 - - pprint("Hello, world!", stream=sys.stdout) # T203 -7 | pprint("Hello, world!", stream=sys.stderr) # T203 +7 - pprint("Hello, world!", stream=sys.stdout) # T203 | note: This is an unsafe fix and may change runtime behavior @@ -65,9 +59,7 @@ T203 [*] `pprint` found | help: Remove `pprint` | -7 | pprint("Hello, world!", stream=sys.stdout) # T203 - - pprint("Hello, world!", stream=sys.stderr) # T203 -8 | +8 - pprint("Hello, world!", stream=sys.stderr) # T203 | note: This is an unsafe fix and may change runtime behavior @@ -83,9 +75,7 @@ T203 [*] `pprint` found | help: Remove `pprint` | -14 | - - pprint.pprint("Hello, world!") # T203 -15 | pprint.pprint("Hello, world!", stream=None) # T203 +15 - pprint.pprint("Hello, world!") # T203 | note: This is an unsafe fix and may change runtime behavior @@ -100,9 +90,7 @@ T203 [*] `pprint` found | help: Remove `pprint` | -15 | pprint.pprint("Hello, world!") # T203 - - pprint.pprint("Hello, world!", stream=None) # T203 -16 | pprint.pprint("Hello, world!", stream=sys.stdout) # T203 +16 - pprint.pprint("Hello, world!", stream=None) # T203 | note: This is an unsafe fix and may change runtime behavior @@ -117,9 +105,7 @@ T203 [*] `pprint` found | help: Remove `pprint` | -16 | pprint.pprint("Hello, world!", stream=None) # T203 - - pprint.pprint("Hello, world!", stream=sys.stdout) # T203 -17 | pprint.pprint("Hello, world!", stream=sys.stderr) # T203 +17 - pprint.pprint("Hello, world!", stream=sys.stdout) # T203 | note: This is an unsafe fix and may change runtime behavior @@ -135,8 +121,6 @@ T203 [*] `pprint` found | help: Remove `pprint` | -17 | pprint.pprint("Hello, world!", stream=sys.stdout) # T203 - - pprint.pprint("Hello, world!", stream=sys.stderr) # T203 -18 | +18 - pprint.pprint("Hello, world!", stream=sys.stderr) # T203 | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI009_PYI009.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI009_PYI009.pyi.snap index 047e12d981999..1969d4b2de680 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI009_PYI009.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI009_PYI009.pyi.snap @@ -13,10 +13,8 @@ PYI009 [*] Empty body should contain `...`, not `pass` | help: Replace `pass` with `...` | -2 | def foo(): - - pass # ERROR PYI009, since we're in a stub file +3 - pass # ERROR PYI009, since we're in a stub file 3 + ... # ERROR PYI009, since we're in a stub file -4 | | PYI009 [*] Empty body should contain `...`, not `pass` @@ -27,7 +25,6 @@ PYI009 [*] Empty body should contain `...`, not `pass` | ^^^^ help: Replace `pass` with `...` | -7 | class Foo: - - pass # ERROR PYI009, since we're in a stub file +8 - pass # ERROR PYI009, since we're in a stub file 8 + ... # ERROR PYI009, since we're in a stub file | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI010_PYI010.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI010_PYI010.pyi.snap index 1a06d666a8ae6..a8bbe6e5ddfcc 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI010_PYI010.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI010_PYI010.pyi.snap @@ -12,10 +12,8 @@ PYI010 [*] Function body must contain only `...` | help: Replace function body with `...` | -5 | def buzz(): - - print("buzz") # ERROR PYI010 +6 - print("buzz") # ERROR PYI010 6 + ... # ERROR PYI010 -7 | | PYI010 [*] Function body must contain only `...` @@ -28,12 +26,10 @@ PYI010 [*] Function body must contain only `...` 11 | def bizz(): | help: Replace function body with `...` - | -8 | def foo2(): - - 123 # ERROR PYI010 -9 + ... # ERROR PYI010 -10 | - | + | +9 - 123 # ERROR PYI010 +9 + ... # ERROR PYI010 + | PYI010 [*] Function body must contain only `...` --> PYI010.pyi:12:5 @@ -46,8 +42,6 @@ PYI010 [*] Function body must contain only `...` | help: Replace function body with `...` | -11 | def bizz(): - - x = 123 # ERROR PYI010 +12 - x = 123 # ERROR PYI010 12 + ... # ERROR PYI010 -13 | | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI011_PYI011.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI011_PYI011.pyi.snap index f5b6970bc6eed..6bab5530a471f 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI011_PYI011.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI011_PYI011.pyi.snap @@ -13,10 +13,8 @@ PYI011 [*] Only simple default values allowed for typed arguments | help: Replace default value with `...` | -9 | x, - - y: str = os.pathsep, # Error PYI011 Only simple default values allowed for typed arguments +10 - y: str = os.pathsep, # Error PYI011 Only simple default values allowed for typed arguments 10 + y: str = ..., # Error PYI011 Only simple default values allowed for typed arguments -11 | ) -> None: ... | PYI011 [*] Only simple default values allowed for typed arguments @@ -35,13 +33,11 @@ PYI011 [*] Only simple default values allowed for typed arguments | help: Replace default value with `...` | -37 | int, int - - ] = { # Error PYI011 Only simple default values allowed for typed arguments - - 1: 2, - - **{3: 4}, - - } +38 - ] = { # Error PYI011 Only simple default values allowed for typed arguments +39 - 1: 2, +40 - **{3: 4}, +41 - } 38 + ] = ... -39 | ) -> None: ... | PYI011 [*] Only simple default values allowed for typed arguments @@ -69,22 +65,20 @@ PYI011 [*] Only simple default values allowed for typed arguments | help: Replace default value with `...` | -45 | int - - ] = [ # Error PYI011 Only simple default values allowed for typed arguments - - 1, - - 2, - - 3, - - 4, - - 5, - - 6, - - 7, - - 8, - - 9, - - 10, - - 11, - - ] +46 - ] = [ # Error PYI011 Only simple default values allowed for typed arguments +47 - 1, +48 - 2, +49 - 3, +50 - 4, +51 - 5, +52 - 6, +53 - 7, +54 - 8, +55 - 9, +56 - 10, +57 - 11, +58 - ] 46 + ] = ... -47 | ) -> None: ... | PYI011 [*] Only simple default values allowed for typed arguments @@ -103,13 +97,11 @@ PYI011 [*] Only simple default values allowed for typed arguments | help: Replace default value with `...` | -62 | str, tuple[str, ...] - - ] = ( # Error PYI011 Only simple default values allowed for typed arguments - - "foo", - - ("bar", "baz"), - - ) +63 - ] = ( # Error PYI011 Only simple default values allowed for typed arguments +64 - "foo", +65 - ("bar", "baz"), +66 - ) 63 + ] = ... -64 | ) -> None: ... | PYI011 [*] Only simple default values allowed for typed arguments @@ -127,12 +119,10 @@ PYI011 [*] Only simple default values allowed for typed arguments | help: Replace default value with `...` | -70 | int - - ] = [ # Error PYI011 Only simple default values allowed for typed arguments - - *range(10) - - ], +71 - ] = [ # Error PYI011 Only simple default values allowed for typed arguments +72 - *range(10) +73 - ], 71 + ] = ..., -72 | ) -> None: ... | PYI011 [*] Only simple default values allowed for typed arguments @@ -150,12 +140,10 @@ PYI011 [*] Only simple default values allowed for typed arguments | help: Replace default value with `...` | -77 | int - - ] = list( # Error PYI011 Only simple default values allowed for typed arguments - - range(10) - - ), +78 - ] = list( # Error PYI011 Only simple default values allowed for typed arguments +79 - range(10) +80 - ), 78 + ] = ..., -79 | ) -> None: ... | PYI011 [*] Only simple default values allowed for typed arguments @@ -173,12 +161,10 @@ PYI011 [*] Only simple default values allowed for typed arguments | help: Replace default value with `...` | -84 | bytes - - ] = frozenset( # Error PYI011 Only simple default values allowed for typed arguments - - {b"foo", b"bar", b"baz"} - - ) +85 - ] = frozenset( # Error PYI011 Only simple default values allowed for typed arguments +86 - {b"foo", b"bar", b"baz"} +87 - ) 85 + ] = ... -86 | ) -> None: ... | PYI011 [*] Only simple default values allowed for typed arguments @@ -195,11 +181,9 @@ PYI011 [*] Only simple default values allowed for typed arguments | help: Replace default value with `...` | -89 | def f17( - - x: str = "foo" # Error PYI011 Only simple default values allowed for typed arguments - - + "bar", +90 - x: str = "foo" # Error PYI011 Only simple default values allowed for typed arguments +91 - + "bar", 90 + x: str = ..., -91 | ) -> None: ... | PYI011 [*] Only simple default values allowed for typed arguments @@ -216,11 +200,9 @@ PYI011 [*] Only simple default values allowed for typed arguments | help: Replace default value with `...` | -93 | def f18( - - x: str = b"foo" # Error PYI011 Only simple default values allowed for typed arguments - - + b"bar", +94 - x: str = b"foo" # Error PYI011 Only simple default values allowed for typed arguments +95 - + b"bar", 94 + x: str = ..., -95 | ) -> None: ... | PYI011 [*] Only simple default values allowed for typed arguments @@ -237,11 +219,9 @@ PYI011 [*] Only simple default values allowed for typed arguments | help: Replace default value with `...` | -97 | def f19( - - x: object = "foo" # Error PYI011 Only simple default values allowed for typed arguments - - + 4, +98 - x: object = "foo" # Error PYI011 Only simple default values allowed for typed arguments +99 - + 4, 98 + x: object = ..., -99 | ) -> None: ... | PYI011 [*] Only simple default values allowed for typed arguments @@ -258,11 +238,9 @@ PYI011 [*] Only simple default values allowed for typed arguments | help: Replace default value with `...` | -101 | def f20( - - x: int = 5 - - + 5, # Error PYI011 Only simple default values allowed for typed arguments +102 - x: int = 5 +103 - + 5, # Error PYI011 Only simple default values allowed for typed arguments 102 + x: int = ..., # Error PYI011 Only simple default values allowed for typed arguments -103 | ) -> None: ... | PYI011 [*] Only simple default values allowed for typed arguments @@ -279,11 +257,9 @@ PYI011 [*] Only simple default values allowed for typed arguments | help: Replace default value with `...` | -105 | def f21( - - x: complex = 3j - - - 3j, # Error PYI011 Only simple default values allowed for typed arguments +106 - x: complex = 3j +107 - - 3j, # Error PYI011 Only simple default values allowed for typed arguments 106 + x: complex = ..., # Error PYI011 Only simple default values allowed for typed arguments -107 | ) -> None: ... | PYI011 [*] Only simple default values allowed for typed arguments @@ -300,11 +276,9 @@ PYI011 [*] Only simple default values allowed for typed arguments | help: Replace default value with `...` | -109 | def f22( - - x: complex = -42.5j # Error PYI011 Only simple default values allowed for typed arguments - - + 4.3j, +110 - x: complex = -42.5j # Error PYI011 Only simple default values allowed for typed arguments +111 - + 4.3j, 110 + x: complex = ..., -111 | ) -> None: ... | PYI011 [*] Only simple default values allowed for typed arguments @@ -319,10 +293,8 @@ PYI011 [*] Only simple default values allowed for typed arguments | help: Replace default value with `...` | -137 | def f31( - - x: float = inf, # Error PYI011 Only simple default values allowed for typed arguments +138 - x: float = inf, # Error PYI011 Only simple default values allowed for typed arguments 138 + x: float = ..., # Error PYI011 Only simple default values allowed for typed arguments -139 | ) -> None: ... | PYI011 [*] Only simple default values allowed for typed arguments @@ -337,10 +309,8 @@ PYI011 [*] Only simple default values allowed for typed arguments | help: Replace default value with `...` | -140 | def f32( - - x: float = np.inf, # Error PYI011 Only simple default values allowed for typed arguments +141 - x: float = np.inf, # Error PYI011 Only simple default values allowed for typed arguments 141 + x: float = ..., # Error PYI011 Only simple default values allowed for typed arguments -142 | ) -> None: ... | PYI011 [*] Only simple default values allowed for typed arguments @@ -355,10 +325,8 @@ PYI011 [*] Only simple default values allowed for typed arguments | help: Replace default value with `...` | -146 | def f34( - - x: float = -math.nan, # Error PYI011 Only simple default values allowed for typed arguments +147 - x: float = -math.nan, # Error PYI011 Only simple default values allowed for typed arguments 147 + x: float = ..., # Error PYI011 Only simple default values allowed for typed arguments -148 | ) -> None: ... | PYI011 [*] Only simple default values allowed for typed arguments @@ -375,11 +343,9 @@ PYI011 [*] Only simple default values allowed for typed arguments | help: Replace default value with `...` | -149 | def f35( - - x: complex = math.inf # Error PYI011 Only simple default values allowed for typed arguments - - + 1j, +150 - x: complex = math.inf # Error PYI011 Only simple default values allowed for typed arguments +151 - + 1j, 150 + x: complex = ..., -151 | ) -> None: ... | PYI011 [*] Only simple default values allowed for typed arguments @@ -395,9 +361,7 @@ PYI011 [*] Only simple default values allowed for typed arguments | help: Replace default value with `...` | -158 | *, - - x: str = "" # Error PYI011 Only simple default values allowed for typed arguments - - + "", +159 - x: str = "" # Error PYI011 Only simple default values allowed for typed arguments +160 - + "", 159 + x: str = ..., -160 | ) -> None: ... | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI012_PYI012.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI012_PYI012.pyi.snap index 6ab9428eba83f..ad2a8a7fbcb2b 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI012_PYI012.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI012_PYI012.pyi.snap @@ -13,9 +13,7 @@ PYI012 [*] Class body must not contain `pass` | help: Remove unnecessary `pass` | -4 | value: int - - pass # PYI012 Class body must not contain `pass` -5 | +5 - pass # PYI012 Class body must not contain `pass` | PYI012 [*] Class body must not contain `pass` @@ -28,9 +26,7 @@ PYI012 [*] Class body must not contain `pass` | help: Remove unnecessary `pass` | -7 | class OneAttributeClassRev: - - pass # PYI012 Class body must not contain `pass` -8 | value: int +8 - pass # PYI012 Class body must not contain `pass` | PYI012 [*] Class body must not contain `pass` @@ -45,9 +41,7 @@ PYI012 [*] Class body must not contain `pass` | help: Remove unnecessary `pass` | -15 | - - pass # PYI012 Class body must not contain `pass` -16 | +16 - pass # PYI012 Class body must not contain `pass` | PYI012 [*] Class body must not contain `pass` @@ -62,9 +56,7 @@ PYI012 [*] Class body must not contain `pass` | help: Remove unnecessary `pass` | -19 | value: int - - pass # PYI012 Class body must not contain `pass` -20 | +20 - pass # PYI012 Class body must not contain `pass` | PYI012 [*] Class body must not contain `pass` @@ -77,9 +69,7 @@ PYI012 [*] Class body must not contain `pass` | help: Remove unnecessary `pass` | -22 | class NonEmptyChild2(Exception): - - pass # PYI012 Class body must not contain `pass` -23 | value: int +23 - pass # PYI012 Class body must not contain `pass` | PYI012 [*] Class body must not contain `pass` @@ -94,7 +84,5 @@ PYI012 [*] Class body must not contain `pass` | help: Remove unnecessary `pass` | -27 | value: int - - pass # PYI012 Class body must not contain `pass` -28 | +28 - pass # PYI012 Class body must not contain `pass` | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI013_PYI013.py.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI013_PYI013.py.snap index abaf31f44d489..72f4d87c77d74 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI013_PYI013.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI013_PYI013.py.snap @@ -10,9 +10,7 @@ PYI013 [*] Non-empty class body must not contain `...` | ^^^ help: Remove unnecessary `...` | -2 | value: int - - ... -3 | +3 - ... | PYI013 [*] Non-empty class body must not contain `...` @@ -25,9 +23,7 @@ PYI013 [*] Non-empty class body must not contain `...` | help: Remove unnecessary `...` | -6 | class OneAttributeClass2: - - ... -7 | value: int +7 - ... | PYI013 [*] Non-empty class body must not contain `...` @@ -40,9 +36,7 @@ PYI013 [*] Non-empty class body must not contain `...` | help: Remove unnecessary `...` | -12 | ... - - ... -13 | +12 - ... | PYI013 [*] Non-empty class body must not contain `...` @@ -54,9 +48,7 @@ PYI013 [*] Non-empty class body must not contain `...` | ^^^ help: Remove unnecessary `...` | -12 | ... - - ... -13 | +13 - ... | PYI013 [*] Non-empty class body must not contain `...` @@ -68,9 +60,7 @@ PYI013 [*] Non-empty class body must not contain `...` | ^^^ help: Remove unnecessary `...` | -20 | - - ... -21 | +21 - ... | PYI013 [*] Non-empty class body must not contain `...` @@ -82,9 +72,7 @@ PYI013 [*] Non-empty class body must not contain `...` | ^^^ help: Remove unnecessary `...` | -25 | value: int - - ... -26 | +26 - ... | PYI013 [*] Non-empty class body must not contain `...` @@ -97,9 +85,7 @@ PYI013 [*] Non-empty class body must not contain `...` | help: Remove unnecessary `...` | -29 | class NonEmptyChild2(Exception): - - ... -30 | value: int +30 - ... | PYI013 [*] Non-empty class body must not contain `...` @@ -114,9 +100,7 @@ PYI013 [*] Non-empty class body must not contain `...` | help: Remove unnecessary `...` | -35 | value: int - - ... -36 | +36 - ... | PYI013 [*] Non-empty class body must not contain `...` @@ -128,8 +112,6 @@ PYI013 [*] Non-empty class body must not contain `...` | ^^^ help: Remove unnecessary `...` | -43 | value: int - - ... # preserve me +44 - ... # preserve me 44 + # preserve me -45 | | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI013_PYI013.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI013_PYI013.pyi.snap index ca3fd4061dd49..fafde612b5726 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI013_PYI013.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI013_PYI013.pyi.snap @@ -13,10 +13,8 @@ PYI013 [*] Non-empty class body must not contain `...` | help: Remove unnecessary `...` | -4 | value: int - - ... # Error +5 - ... # Error 5 + # Error -6 | | PYI013 [*] Non-empty class body must not contain `...` @@ -29,10 +27,8 @@ PYI013 [*] Non-empty class body must not contain `...` | help: Remove unnecessary `...` | -7 | class OneAttributeClass2: - - ... # Error +8 - ... # Error 8 + # Error -9 | value: int | PYI013 [*] Non-empty class body must not contain `...` @@ -45,9 +41,7 @@ PYI013 [*] Non-empty class body must not contain `...` | help: Remove unnecessary `...` | -11 | class MyClass: - - ... -12 | value: int +12 - ... | PYI013 [*] Non-empty class body must not contain `...` @@ -60,9 +54,7 @@ PYI013 [*] Non-empty class body must not contain `...` | help: Remove unnecessary `...` | -15 | class TwoEllipsesClass: - - ... -16 | ... # Error +16 - ... | PYI013 [*] Non-empty class body must not contain `...` @@ -77,10 +69,8 @@ PYI013 [*] Non-empty class body must not contain `...` | help: Remove unnecessary `...` | -16 | ... - - ... # Error +17 - ... # Error 17 + # Error -18 | | PYI013 [*] Non-empty class body must not contain `...` @@ -95,10 +85,8 @@ PYI013 [*] Non-empty class body must not contain `...` | help: Remove unnecessary `...` | -23 | - - ... # Error +24 - ... # Error 24 + # Error -25 | | PYI013 [*] Non-empty class body must not contain `...` @@ -113,10 +101,8 @@ PYI013 [*] Non-empty class body must not contain `...` | help: Remove unnecessary `...` | -27 | value: int - - ... # Error +28 - ... # Error 28 + # Error -29 | | PYI013 [*] Non-empty class body must not contain `...` @@ -129,10 +115,8 @@ PYI013 [*] Non-empty class body must not contain `...` | help: Remove unnecessary `...` | -30 | class NonEmptyChild2(Exception): - - ... # Error +31 - ... # Error 31 + # Error -32 | value: int | PYI013 [*] Non-empty class body must not contain `...` @@ -147,10 +131,8 @@ PYI013 [*] Non-empty class body must not contain `...` | help: Remove unnecessary `...` | -35 | value: int - - ... # Error +36 - ... # Error 36 + # Error -37 | | PYI013 [*] Non-empty class body must not contain `...` @@ -165,8 +147,6 @@ PYI013 [*] Non-empty class body must not contain `...` | help: Remove unnecessary `...` | -42 | value: int - - ... # preserve me +43 - ... # preserve me 43 + # preserve me -44 | | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI014_PYI014.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI014_PYI014.pyi.snap index 5ac96400771fb..bbb99ba29e31d 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI014_PYI014.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI014_PYI014.pyi.snap @@ -13,10 +13,8 @@ PYI014 [*] Only simple default values allowed for arguments | help: Replace default value with `...` | -2 | x, - - y=os.pathsep, # Error PYI014 +3 - y=os.pathsep, # Error PYI014 3 + y=..., # Error PYI014 -4 | ) -> None: ... | PYI014 [*] Only simple default values allowed for arguments @@ -35,13 +33,11 @@ PYI014 [*] Only simple default values allowed for arguments | help: Replace default value with `...` | -28 | def f152( - - x={ # Error PYI014 - - 1: 2, - - **{3: 4}, - - } +29 - x={ # Error PYI014 +30 - 1: 2, +31 - **{3: 4}, +32 - } 29 + x=... -30 | ) -> None: ... | PYI014 [*] Only simple default values allowed for arguments @@ -69,22 +65,20 @@ PYI014 [*] Only simple default values allowed for arguments | help: Replace default value with `...` | -34 | def f153( - - x=[ # Error PYI014 - - 1, - - 2, - - 3, - - 4, - - 5, - - 6, - - 7, - - 8, - - 9, - - 10, - - 11, - - ] +35 - x=[ # Error PYI014 +36 - 1, +37 - 2, +38 - 3, +39 - 4, +40 - 5, +41 - 6, +42 - 7, +43 - 8, +44 - 9, +45 - 10, +46 - 11, +47 - ] 35 + x=... -36 | ) -> None: ... | PYI014 [*] Only simple default values allowed for arguments @@ -103,13 +97,11 @@ PYI014 [*] Only simple default values allowed for arguments | help: Replace default value with `...` | -49 | def f154( - - x=( # Error PYI014 - - "foo", - - ("bar", "baz"), - - ) +50 - x=( # Error PYI014 +51 - "foo", +52 - ("bar", "baz"), +53 - ) 50 + x=... -51 | ) -> None: ... | PYI014 [*] Only simple default values allowed for arguments @@ -124,10 +116,8 @@ PYI014 [*] Only simple default values allowed for arguments | help: Replace default value with `...` | -55 | def f141( - - x=[*range(10)], # Error PYI014 +56 - x=[*range(10)], # Error PYI014 56 + x=..., # Error PYI014 -57 | ) -> None: ... | PYI014 [*] Only simple default values allowed for arguments @@ -142,10 +132,8 @@ PYI014 [*] Only simple default values allowed for arguments | help: Replace default value with `...` | -58 | def f142( - - x=list(range(10)), # Error PYI014 +59 - x=list(range(10)), # Error PYI014 59 + x=..., # Error PYI014 -60 | ) -> None: ... | PYI014 [*] Only simple default values allowed for arguments @@ -160,10 +148,8 @@ PYI014 [*] Only simple default values allowed for arguments | help: Replace default value with `...` | -60 | ) -> None: ... - - def f16(x=frozenset({b"foo", b"bar", b"baz"})) -> None: ... # Error PYI014 +61 - def f16(x=frozenset({b"foo", b"bar", b"baz"})) -> None: ... # Error PYI014 61 + def f16(x=...) -> None: ... # Error PYI014 -62 | def f17( | PYI014 [*] Only simple default values allowed for arguments @@ -178,10 +164,8 @@ PYI014 [*] Only simple default values allowed for arguments | help: Replace default value with `...` | -62 | def f17( - - x="foo" + "bar", # Error PYI014 +63 - x="foo" + "bar", # Error PYI014 63 + x=..., # Error PYI014 -64 | ) -> None: ... | PYI014 [*] Only simple default values allowed for arguments @@ -196,10 +180,8 @@ PYI014 [*] Only simple default values allowed for arguments | help: Replace default value with `...` | -65 | def f18( - - x=b"foo" + b"bar", # Error PYI014 +66 - x=b"foo" + b"bar", # Error PYI014 66 + x=..., # Error PYI014 -67 | ) -> None: ... | PYI014 [*] Only simple default values allowed for arguments @@ -214,10 +196,8 @@ PYI014 [*] Only simple default values allowed for arguments | help: Replace default value with `...` | -68 | def f19( - - x="foo" + 4, # Error PYI014 +69 - x="foo" + 4, # Error PYI014 69 + x=..., # Error PYI014 -70 | ) -> None: ... | PYI014 [*] Only simple default values allowed for arguments @@ -232,10 +212,8 @@ PYI014 [*] Only simple default values allowed for arguments | help: Replace default value with `...` | -71 | def f20( - - x=5 + 5, # Error PYI014 +72 - x=5 + 5, # Error PYI014 72 + x=..., # Error PYI014 -73 | ) -> None: ... | PYI014 [*] Only simple default values allowed for arguments @@ -250,10 +228,8 @@ PYI014 [*] Only simple default values allowed for arguments | help: Replace default value with `...` | -74 | def f21( - - x=3j - 3j, # Error PYI014 +75 - x=3j - 3j, # Error PYI014 75 + x=..., # Error PYI014 -76 | ) -> None: ... | PYI014 [*] Only simple default values allowed for arguments @@ -268,8 +244,6 @@ PYI014 [*] Only simple default values allowed for arguments | help: Replace default value with `...` | -77 | def f22( - - x=-42.5j + 4.3j, # Error PYI014 +78 - x=-42.5j + 4.3j, # Error PYI014 78 + x=..., # Error PYI014 -79 | ) -> None: ... | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI015_PYI015.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI015_PYI015.pyi.snap index 31e58ec1cba61..7e0a96d0e32c5 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI015_PYI015.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI015_PYI015.pyi.snap @@ -12,10 +12,8 @@ PYI015 [*] Only simple default values allowed for assignments | help: Replace default value with `...` | -43 | # We *should* emit Y015 for more complex default values - - field221: list[int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] # Y015 Only simple default values are allowed for assignments +44 - field221: list[int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] # Y015 Only simple default values are allowed for assignments 44 + field221: list[int] = ... # Y015 Only simple default values are allowed for assignments -45 | field223: list[int] = [*range(10)] # Y015 Only simple default values are allowed for assignments | PYI015 [*] Only simple default values allowed for assignments @@ -30,10 +28,8 @@ PYI015 [*] Only simple default values allowed for assignments | help: Replace default value with `...` | -44 | field221: list[int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] # Y015 Only simple default values are allowed for assignments - - field223: list[int] = [*range(10)] # Y015 Only simple default values are allowed for assignments +45 - field223: list[int] = [*range(10)] # Y015 Only simple default values are allowed for assignments 45 + field223: list[int] = ... # Y015 Only simple default values are allowed for assignments -46 | field224: list[int] = list(range(10)) # Y015 Only simple default values are allowed for assignments | PYI015 [*] Only simple default values allowed for assignments @@ -48,10 +44,8 @@ PYI015 [*] Only simple default values allowed for assignments | help: Replace default value with `...` | -45 | field223: list[int] = [*range(10)] # Y015 Only simple default values are allowed for assignments - - field224: list[int] = list(range(10)) # Y015 Only simple default values are allowed for assignments +46 - field224: list[int] = list(range(10)) # Y015 Only simple default values are allowed for assignments 46 + field224: list[int] = ... # Y015 Only simple default values are allowed for assignments -47 | field225: list[object] = [{}, 1, 2] # Y015 Only simple default values are allowed for assignments | PYI015 [*] Only simple default values allowed for assignments @@ -66,10 +60,8 @@ PYI015 [*] Only simple default values allowed for assignments | help: Replace default value with `...` | -46 | field224: list[int] = list(range(10)) # Y015 Only simple default values are allowed for assignments - - field225: list[object] = [{}, 1, 2] # Y015 Only simple default values are allowed for assignments +47 - field225: list[object] = [{}, 1, 2] # Y015 Only simple default values are allowed for assignments 47 + field225: list[object] = ... # Y015 Only simple default values are allowed for assignments -48 | field226: tuple[str | tuple[str, ...], ...] = ("foo", ("foo", "bar")) # Y015 Only simple default values are allowed for assignments | PYI015 [*] Only simple default values allowed for assignments @@ -84,10 +76,8 @@ PYI015 [*] Only simple default values allowed for assignments | help: Replace default value with `...` | -47 | field225: list[object] = [{}, 1, 2] # Y015 Only simple default values are allowed for assignments - - field226: tuple[str | tuple[str, ...], ...] = ("foo", ("foo", "bar")) # Y015 Only simple default values are allowed for assignments +48 - field226: tuple[str | tuple[str, ...], ...] = ("foo", ("foo", "bar")) # Y015 Only simple default values are allowed for assignments 48 + field226: tuple[str | tuple[str, ...], ...] = ... # Y015 Only simple default values are allowed for assignments -49 | field227: dict[str, object] = {"foo": {"foo": "bar"}} # Y015 Only simple default values are allowed for assignments | PYI015 [*] Only simple default values allowed for assignments @@ -102,10 +92,8 @@ PYI015 [*] Only simple default values allowed for assignments | help: Replace default value with `...` | -48 | field226: tuple[str | tuple[str, ...], ...] = ("foo", ("foo", "bar")) # Y015 Only simple default values are allowed for assignments - - field227: dict[str, object] = {"foo": {"foo": "bar"}} # Y015 Only simple default values are allowed for assignments +49 - field227: dict[str, object] = {"foo": {"foo": "bar"}} # Y015 Only simple default values are allowed for assignments 49 + field227: dict[str, object] = ... # Y015 Only simple default values are allowed for assignments -50 | field228: dict[str, list[object]] = {"foo": []} # Y015 Only simple default values are allowed for assignments | PYI015 [*] Only simple default values allowed for assignments @@ -120,10 +108,8 @@ PYI015 [*] Only simple default values allowed for assignments | help: Replace default value with `...` | -49 | field227: dict[str, object] = {"foo": {"foo": "bar"}} # Y015 Only simple default values are allowed for assignments - - field228: dict[str, list[object]] = {"foo": []} # Y015 Only simple default values are allowed for assignments +50 - field228: dict[str, list[object]] = {"foo": []} # Y015 Only simple default values are allowed for assignments 50 + field228: dict[str, list[object]] = ... # Y015 Only simple default values are allowed for assignments -51 | # When parsed, this case results in `None` being placed in the `.keys` list for the `ast.Dict` node | PYI015 [*] Only simple default values allowed for assignments @@ -138,10 +124,8 @@ PYI015 [*] Only simple default values allowed for assignments | help: Replace default value with `...` | -51 | # When parsed, this case results in `None` being placed in the `.keys` list for the `ast.Dict` node - - field229: dict[int, int] = {1: 2, **{3: 4}} # Y015 Only simple default values are allowed for assignments +52 - field229: dict[int, int] = {1: 2, **{3: 4}} # Y015 Only simple default values are allowed for assignments 52 + field229: dict[int, int] = ... # Y015 Only simple default values are allowed for assignments -53 | field23 = "foo" + "bar" # Y015 Only simple default values are allowed for assignments | PYI015 [*] Only simple default values allowed for assignments @@ -156,10 +140,8 @@ PYI015 [*] Only simple default values allowed for assignments | help: Replace default value with `...` | -52 | field229: dict[int, int] = {1: 2, **{3: 4}} # Y015 Only simple default values are allowed for assignments - - field23 = "foo" + "bar" # Y015 Only simple default values are allowed for assignments +53 - field23 = "foo" + "bar" # Y015 Only simple default values are allowed for assignments 53 + field23 = ... # Y015 Only simple default values are allowed for assignments -54 | field24 = b"foo" + b"bar" # Y015 Only simple default values are allowed for assignments | PYI015 [*] Only simple default values allowed for assignments @@ -173,10 +155,8 @@ PYI015 [*] Only simple default values allowed for assignments | help: Replace default value with `...` | -53 | field23 = "foo" + "bar" # Y015 Only simple default values are allowed for assignments - - field24 = b"foo" + b"bar" # Y015 Only simple default values are allowed for assignments +54 - field24 = b"foo" + b"bar" # Y015 Only simple default values are allowed for assignments 54 + field24 = ... # Y015 Only simple default values are allowed for assignments -55 | field25 = 5 * 5 # Y015 Only simple default values are allowed for assignments | PYI015 [*] Only simple default values allowed for assignments @@ -191,8 +171,6 @@ PYI015 [*] Only simple default values allowed for assignments | help: Replace default value with `...` | -54 | field24 = b"foo" + b"bar" # Y015 Only simple default values are allowed for assignments - - field25 = 5 * 5 # Y015 Only simple default values are allowed for assignments +55 - field25 = 5 * 5 # Y015 Only simple default values are allowed for assignments 55 + field25 = ... # Y015 Only simple default values are allowed for assignments -56 | | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI016_PYI016.py.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI016_PYI016.py.snap index 1e7493cc15a1e..c414594989b22 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI016_PYI016.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI016_PYI016.py.snap @@ -12,10 +12,8 @@ PYI016 [*] Duplicate union member `str` | help: Remove duplicate union member `str` | -6 | # Should emit for duplicate field types. - - field2: str | str # PYI016: Duplicate union member `str` +7 - field2: str | str # PYI016: Duplicate union member `str` 7 + field2: str # PYI016: Duplicate union member `str` -8 | | PYI016 [*] Duplicate union member `int` @@ -28,10 +26,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -9 | # Should emit for union types in arguments. - - def func1(arg1: int | int): # PYI016: Duplicate union member `int` +10 - def func1(arg1: int | int): # PYI016: Duplicate union member `int` 10 + def func1(arg1: int): # PYI016: Duplicate union member `int` -11 | print(arg1) | PYI016 [*] Duplicate union member `str` @@ -44,10 +40,8 @@ PYI016 [*] Duplicate union member `str` | help: Remove duplicate union member `str` | -13 | # Should emit for unions in return types. - - def func2() -> str | str: # PYI016: Duplicate union member `str` +14 - def func2() -> str | str: # PYI016: Duplicate union member `str` 14 + def func2() -> str: # PYI016: Duplicate union member `str` -15 | return "my string" | PYI016 [*] Duplicate union member `str` @@ -61,10 +55,8 @@ PYI016 [*] Duplicate union member `str` | help: Remove duplicate union member `str` | -17 | # Should emit in longer unions, even if not directly adjacent. - - field3: str | str | int # PYI016: Duplicate union member `str` +18 - field3: str | str | int # PYI016: Duplicate union member `str` 18 + field3: str | int # PYI016: Duplicate union member `str` -19 | field4: int | int | str # PYI016: Duplicate union member `int` | PYI016 [*] Duplicate union member `int` @@ -79,10 +71,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -18 | field3: str | str | int # PYI016: Duplicate union member `str` - - field4: int | int | str # PYI016: Duplicate union member `int` +19 - field4: int | int | str # PYI016: Duplicate union member `int` 19 + field4: int | str # PYI016: Duplicate union member `int` -20 | field5: str | int | str # PYI016: Duplicate union member `str` | PYI016 [*] Duplicate union member `str` @@ -96,10 +86,8 @@ PYI016 [*] Duplicate union member `str` | help: Remove duplicate union member `str` | -19 | field4: int | int | str # PYI016: Duplicate union member `int` - - field5: str | int | str # PYI016: Duplicate union member `str` +20 - field5: str | int | str # PYI016: Duplicate union member `str` 20 + field5: str | int # PYI016: Duplicate union member `str` -21 | field6: int | bool | str | int # PYI016: Duplicate union member `int` | PYI016 [*] Duplicate union member `int` @@ -114,10 +102,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -20 | field5: str | int | str # PYI016: Duplicate union member `str` - - field6: int | bool | str | int # PYI016: Duplicate union member `int` +21 - field6: int | bool | str | int # PYI016: Duplicate union member `int` 21 + field6: int | bool | str # PYI016: Duplicate union member `int` -22 | | PYI016 [*] Duplicate union member `int` @@ -131,10 +117,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -26 | # Should emit for strangely-bracketed unions. - - field8: int | (str | int) # PYI016: Duplicate union member `int` +27 - field8: int | (str | int) # PYI016: Duplicate union member `int` 27 + field8: int | str # PYI016: Duplicate union member `int` -28 | | PYI016 [*] Duplicate union member `int` @@ -147,10 +131,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -29 | # Should handle user brackets when fixing. - - field9: int | (int | str) # PYI016: Duplicate union member `int` +30 - field9: int | (int | str) # PYI016: Duplicate union member `int` 30 + field9: int | str # PYI016: Duplicate union member `int` -31 | field10: (str | int) | str # PYI016: Duplicate union member `str` | PYI016 [*] Duplicate union member `str` @@ -165,10 +147,8 @@ PYI016 [*] Duplicate union member `str` | help: Remove duplicate union member `str` | -30 | field9: int | (int | str) # PYI016: Duplicate union member `int` - - field10: (str | int) | str # PYI016: Duplicate union member `str` +31 - field10: (str | int) | str # PYI016: Duplicate union member `str` 31 + field10: str | int # PYI016: Duplicate union member `str` -32 | | PYI016 [*] Duplicate union member `int` @@ -182,10 +162,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -33 | # Should emit for nested unions. - - field11: dict[int | int, str] +34 - field11: dict[int | int, str] 34 + field11: dict[int, str] -35 | | PYI016 [*] Duplicate union member `int` @@ -198,10 +176,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -36 | # Should emit for unions with more than two cases - - field12: int | int | int # Error +37 - field12: int | int | int # Error 37 + field12: int # Error -38 | field13: int | int | int | int # Error | PYI016 [*] Duplicate union member `int` @@ -214,10 +190,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -36 | # Should emit for unions with more than two cases - - field12: int | int | int # Error +37 - field12: int | int | int # Error 37 + field12: int # Error -38 | field13: int | int | int | int # Error | PYI016 [*] Duplicate union member `int` @@ -232,10 +206,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -37 | field12: int | int | int # Error - - field13: int | int | int | int # Error +38 - field13: int | int | int | int # Error 38 + field13: int # Error -39 | | PYI016 [*] Duplicate union member `int` @@ -250,10 +222,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -37 | field12: int | int | int # Error - - field13: int | int | int | int # Error +38 - field13: int | int | int | int # Error 38 + field13: int # Error -39 | | PYI016 [*] Duplicate union member `int` @@ -268,10 +238,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -37 | field12: int | int | int # Error - - field13: int | int | int | int # Error +38 - field13: int | int | int | int # Error 38 + field13: int # Error -39 | | PYI016 [*] Duplicate union member `int` @@ -285,10 +253,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -40 | # Should emit for unions with more than two cases, even if not directly adjacent - - field14: int | int | str | int # Error +41 - field14: int | int | str | int # Error 41 + field14: int | str # Error -42 | | PYI016 [*] Duplicate union member `int` @@ -302,10 +268,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -40 | # Should emit for unions with more than two cases, even if not directly adjacent - - field14: int | int | str | int # Error +41 - field14: int | int | str | int # Error 41 + field14: int | str # Error -42 | | PYI016 [*] Duplicate union member `typing.Literal[1]` @@ -319,10 +283,8 @@ PYI016 [*] Duplicate union member `typing.Literal[1]` | help: Remove duplicate union member `typing.Literal[1]` | -43 | # Should emit for duplicate literal types; also covered by PYI030 - - field15: typing.Literal[1] | typing.Literal[1] # Error +44 - field15: typing.Literal[1] | typing.Literal[1] # Error 44 + field15: typing.Literal[1] # Error -45 | | PYI016 [*] Duplicate union member `set[int]` @@ -338,17 +300,15 @@ PYI016 [*] Duplicate union member `set[int]` | help: Remove duplicate union member `set[int]` | -52 | # Should emit in cases with newlines - - field18: typing.Union[ - - set[ - - int # foo - - ], - - set[ - - int # bar - - ], - - ] # Error, newline and comment will not be emitted in message +53 - field18: typing.Union[ +54 - set[ +55 - int # foo +56 - ], +57 - set[ +58 - int # bar +59 - ], +60 - ] # Error, newline and comment will not be emitted in message 53 + field18: set[int] # Error, newline and comment will not be emitted in message -54 | | note: This is an unsafe fix and may change runtime behavior @@ -363,10 +323,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -62 | # Should emit in cases with `typing.Union` instead of `|` - - field19: typing.Union[int, int] # Error +63 - field19: typing.Union[int, int] # Error 63 + field19: int # Error -64 | | PYI016 [*] Duplicate union member `int` @@ -380,10 +338,11 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | + 1 ~ import typing + 2 | + … 65 | # Should emit in cases with nested `typing.Union` - - field20: typing.Union[int, typing.Union[int, str]] # Error -66 + field20: typing.Union[int, str] # Error -67 | +66 ~ field20: typing.Union[int, str] # Error | PYI016 [*] Duplicate union member `int` @@ -397,10 +356,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -68 | # Should emit in cases with mixed `typing.Union` and `|` - - field21: typing.Union[int, int | str] # Error +69 - field21: typing.Union[int, int | str] # Error 69 + field21: int | str # Error -70 | | PYI016 [*] Duplicate union member `int` @@ -414,10 +371,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -71 | # Should emit only once in cases with multiple nested `typing.Union` - - field22: typing.Union[int, typing.Union[int, typing.Union[int, int]]] # Error +72 - field22: typing.Union[int, typing.Union[int, typing.Union[int, int]]] # Error 72 + field22: int # Error -73 | | PYI016 [*] Duplicate union member `int` @@ -431,10 +386,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -71 | # Should emit only once in cases with multiple nested `typing.Union` - - field22: typing.Union[int, typing.Union[int, typing.Union[int, int]]] # Error +72 - field22: typing.Union[int, typing.Union[int, typing.Union[int, int]]] # Error 72 + field22: int # Error -73 | | PYI016 [*] Duplicate union member `int` @@ -448,10 +401,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -71 | # Should emit only once in cases with multiple nested `typing.Union` - - field22: typing.Union[int, typing.Union[int, typing.Union[int, int]]] # Error +72 - field22: typing.Union[int, typing.Union[int, typing.Union[int, int]]] # Error 72 + field22: int # Error -73 | | PYI016 [*] Duplicate union member `set[int]` @@ -466,11 +417,9 @@ PYI016 [*] Duplicate union member `set[int]` | help: Remove duplicate union member `set[int]` | -74 | # Should emit in cases with newlines - - field23: set[ # foo - - int] | set[int] +75 - field23: set[ # foo +76 - int] | set[int] 75 + field23: set[int] -76 | | note: This is an unsafe fix and may change runtime behavior @@ -486,10 +435,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -80 | # we incorrectly re-checked the nested union). - - field24: typing.Union[int, typing.Union[int, int]] # PYI016: Duplicate union member `int` +81 - field24: typing.Union[int, typing.Union[int, int]] # PYI016: Duplicate union member `int` 81 + field24: int # PYI016: Duplicate union member `int` -82 | | PYI016 [*] Duplicate union member `int` @@ -504,10 +451,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -80 | # we incorrectly re-checked the nested union). - - field24: typing.Union[int, typing.Union[int, int]] # PYI016: Duplicate union member `int` +81 - field24: typing.Union[int, typing.Union[int, int]] # PYI016: Duplicate union member `int` 81 + field24: int # PYI016: Duplicate union member `int` -82 | | PYI016 [*] Duplicate union member `int` @@ -522,10 +467,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -85 | # we incorrectly re-checked the nested union). - - field25: typing.Union[int, int | int] # PYI016: Duplicate union member `int` +86 - field25: typing.Union[int, int | int] # PYI016: Duplicate union member `int` 86 + field25: int # PYI016: Duplicate union member `int` -87 | | PYI016 [*] Duplicate union member `int` @@ -540,10 +483,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -85 | # we incorrectly re-checked the nested union). - - field25: typing.Union[int, int | int] # PYI016: Duplicate union member `int` +86 - field25: typing.Union[int, int | int] # PYI016: Duplicate union member `int` 86 + field25: int # PYI016: Duplicate union member `int` -87 | | PYI016 [*] Duplicate union member `int` @@ -557,10 +498,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -88 | # Should emit in cases with nested `typing.Union` - - field26: typing.Union[typing.Union[int, int]] # PYI016: Duplicate union member `int` +89 - field26: typing.Union[typing.Union[int, int]] # PYI016: Duplicate union member `int` 89 + field26: int # PYI016: Duplicate union member `int` -90 | | PYI016 [*] Duplicate union member `int` @@ -574,10 +513,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -91 | # Should emit in cases with nested `typing.Union` - - field27: typing.Union[typing.Union[typing.Union[int, int]]] # PYI016: Duplicate union member `int` +92 - field27: typing.Union[typing.Union[typing.Union[int, int]]] # PYI016: Duplicate union member `int` 92 + field27: int # PYI016: Duplicate union member `int` -93 | | PYI016 [*] Duplicate union member `int` @@ -591,10 +528,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -94 | # Should emit in cases with mixed `typing.Union` and `|` - - field28: typing.Union[int | int] # Error +95 - field28: typing.Union[int | int] # Error 95 + field28: int # Error -96 | | PYI016 [*] Duplicate union member `int` @@ -608,10 +543,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -97 | # Should emit twice in cases with multiple nested `typing.Union` - - field29: typing.Union[int, typing.Union[typing.Union[int, int]]] # Error +98 - field29: typing.Union[int, typing.Union[typing.Union[int, int]]] # Error 98 + field29: int # Error -99 | | PYI016 [*] Duplicate union member `int` @@ -625,10 +558,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -97 | # Should emit twice in cases with multiple nested `typing.Union` - - field29: typing.Union[int, typing.Union[typing.Union[int, int]]] # Error +98 - field29: typing.Union[int, typing.Union[typing.Union[int, int]]] # Error 98 + field29: int # Error -99 | | PYI016 [*] Duplicate union member `int` @@ -642,10 +573,11 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | + 1 ~ import typing + 2 | + … 100 | # Should emit once in cases with multiple nested `typing.Union` - - field30: typing.Union[int, typing.Union[typing.Union[int, str]]] # Error -101 + field30: typing.Union[int, str] # Error -102 | +101 ~ field30: typing.Union[int, str] # Error | PYI016 [*] Duplicate union member `int` @@ -659,10 +591,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -103 | # Should emit once, and fix to `typing.Union[float, int]` - - field31: typing.Union[float, typing.Union[int | int]] # Error +104 - field31: typing.Union[float, typing.Union[int | int]] # Error 104 + field31: float | int # Error -105 | | PYI016 [*] Duplicate union member `int` @@ -676,10 +606,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -106 | # Should emit once, and fix to `typing.Union[float, int]` - - field32: typing.Union[float, typing.Union[int | int | int]] # Error +107 - field32: typing.Union[float, typing.Union[int | int | int]] # Error 107 + field32: float | int # Error -108 | | PYI016 [*] Duplicate union member `int` @@ -693,10 +621,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -106 | # Should emit once, and fix to `typing.Union[float, int]` - - field32: typing.Union[float, typing.Union[int | int | int]] # Error +107 - field32: typing.Union[float, typing.Union[int | int | int]] # Error 107 + field32: float | int # Error -108 | | PYI016 [*] Duplicate union member `int` @@ -710,10 +636,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -109 | # Test case for mixed union type fix - - field33: typing.Union[typing.Union[int | int] | typing.Union[int | int]] # Error +110 - field33: typing.Union[typing.Union[int | int] | typing.Union[int | int]] # Error 110 + field33: int # Error -111 | | PYI016 [*] Duplicate union member `int` @@ -727,10 +651,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -109 | # Test case for mixed union type fix - - field33: typing.Union[typing.Union[int | int] | typing.Union[int | int]] # Error +110 - field33: typing.Union[typing.Union[int | int] | typing.Union[int | int]] # Error 110 + field33: int # Error -111 | | PYI016 [*] Duplicate union member `int` @@ -744,10 +666,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -109 | # Test case for mixed union type fix - - field33: typing.Union[typing.Union[int | int] | typing.Union[int | int]] # Error +110 - field33: typing.Union[typing.Union[int | int] | typing.Union[int | int]] # Error 110 + field33: int # Error -111 | | PYI016 [*] Duplicate union member `list[int]` @@ -761,10 +681,11 @@ PYI016 [*] Duplicate union member `list[int]` | help: Remove duplicate union member `list[int]` | + 1 ~ import typing + 2 | + … 112 | # Test case for mixed union type - - field34: typing.Union[list[int], str] | typing.Union[bytes, list[int]] # Error -113 + field34: typing.Union[list[int], str, bytes] # Error -114 | +113 ~ field34: typing.Union[list[int], str, bytes] # Error | PYI016 [*] Duplicate union member `int` @@ -776,10 +697,8 @@ PYI016 [*] Duplicate union member `int` | ^^^ help: Remove duplicate union member `int` | -114 | - - field35: "int | str | int" # Error +115 - field35: "int | str | int" # Error 115 + field35: "int | str" # Error -116 | | PYI016 [*] Duplicate union member `None` @@ -794,10 +713,8 @@ PYI016 [*] Duplicate union member `None` | help: Remove duplicate union member `None` | -129 | # equivalent to None - - field39: typing.Optional[None] +130 - field39: typing.Optional[None] 130 + field39: None -131 | # equivalent to int | None | PYI016 [*] Duplicate union member `None` @@ -812,10 +729,11 @@ PYI016 [*] Duplicate union member `None` | help: Remove duplicate union member `None` | + 1 ~ import typing + 2 | + … 131 | # equivalent to int | None - - field40: typing.Union[typing.Optional[int], None] -132 + field40: typing.Union[None, int] -133 | field41: typing.Optional[typing.Union[int, None]] +132 ~ field40: typing.Union[None, int] | PYI016 [*] Duplicate union member `None` @@ -830,10 +748,11 @@ PYI016 [*] Duplicate union member `None` | help: Remove duplicate union member `None` | + 1 ~ import typing + 2 | + … 132 | field40: typing.Union[typing.Optional[int], None] - - field41: typing.Optional[typing.Union[int, None]] -133 + field41: typing.Union[None, int] -134 | field42: typing.Union[typing.Optional[int], typing.Optional[int]] +133 ~ field41: typing.Union[None, int] | PYI016 [*] Duplicate union member `None` @@ -848,10 +767,11 @@ PYI016 [*] Duplicate union member `None` | help: Remove duplicate union member `None` | + 1 ~ import typing + 2 | + … 133 | field41: typing.Optional[typing.Union[int, None]] - - field42: typing.Union[typing.Optional[int], typing.Optional[int]] -134 + field42: typing.Union[None, int] -135 | field43: typing.Optional[int] | None +134 ~ field42: typing.Union[None, int] | PYI016 [*] Duplicate union member `int` @@ -866,10 +786,11 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | + 1 ~ import typing + 2 | + … 133 | field41: typing.Optional[typing.Union[int, None]] - - field42: typing.Union[typing.Optional[int], typing.Optional[int]] -134 + field42: typing.Union[None, int] -135 | field43: typing.Optional[int] | None +134 ~ field42: typing.Union[None, int] | PYI016 [*] Duplicate union member `None` @@ -884,10 +805,8 @@ PYI016 [*] Duplicate union member `None` | help: Remove duplicate union member `None` | -134 | field42: typing.Union[typing.Optional[int], typing.Optional[int]] - - field43: typing.Optional[int] | None +135 - field43: typing.Optional[int] | None 135 + field43: None | int -136 | field44: typing.Optional[int | None] | PYI016 [*] Duplicate union member `None` @@ -902,10 +821,8 @@ PYI016 [*] Duplicate union member `None` | help: Remove duplicate union member `None` | -135 | field43: typing.Optional[int] | None - - field44: typing.Optional[int | None] +136 - field44: typing.Optional[int | None] 136 + field44: None | int -137 | field45: typing.Optional[int] | typing.Optional[int] | PYI016 [*] Duplicate union member `None` @@ -920,10 +837,11 @@ PYI016 [*] Duplicate union member `None` | help: Remove duplicate union member `None` | + 1 ~ import typing + 2 | + … 136 | field44: typing.Optional[int | None] - - field45: typing.Optional[int] | typing.Optional[int] -137 + field45: typing.Union[None, int] -138 | # equivalent to int | dict | None +137 ~ field45: typing.Union[None, int] | PYI016 [*] Duplicate union member `int` @@ -938,10 +856,11 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | + 1 ~ import typing + 2 | + … 136 | field44: typing.Optional[int | None] - - field45: typing.Optional[int] | typing.Optional[int] -137 + field45: typing.Union[None, int] -138 | # equivalent to int | dict | None +137 ~ field45: typing.Union[None, int] | PYI016 [*] Duplicate union member `None` @@ -955,10 +874,11 @@ PYI016 [*] Duplicate union member `None` | help: Remove duplicate union member `None` | + 1 ~ import typing + 2 | + … 138 | # equivalent to int | dict | None - - field46: typing.Union[typing.Optional[int], typing.Optional[dict]] -139 + field46: typing.Union[None, int, dict] -140 | field47: typing.Optional[int] | typing.Optional[dict] +139 ~ field46: typing.Union[None, int, dict] | PYI016 [*] Duplicate union member `None` @@ -973,10 +893,11 @@ PYI016 [*] Duplicate union member `None` | help: Remove duplicate union member `None` | + 1 ~ import typing + 2 | + … 139 | field46: typing.Union[typing.Optional[int], typing.Optional[dict]] - - field47: typing.Optional[int] | typing.Optional[dict] -140 + field47: typing.Union[None, int, dict] -141 | +140 ~ field47: typing.Union[None, int, dict] | PYI016 [*] Duplicate union member `complex` @@ -989,10 +910,11 @@ PYI016 [*] Duplicate union member `complex` | help: Remove duplicate union member `complex` | + 1 ~ import typing + 2 | + … 142 | # avoid reporting twice - - field48: typing.Union[typing.Optional[typing.Union[complex, complex]], complex] -143 + field48: typing.Union[None, complex] -144 | field49: typing.Optional[complex | complex] | complex +143 ~ field48: typing.Union[None, complex] | PYI016 [*] Duplicate union member `complex` @@ -1005,10 +927,11 @@ PYI016 [*] Duplicate union member `complex` | help: Remove duplicate union member `complex` | + 1 ~ import typing + 2 | + … 142 | # avoid reporting twice - - field48: typing.Union[typing.Optional[typing.Union[complex, complex]], complex] -143 + field48: typing.Union[None, complex] -144 | field49: typing.Optional[complex | complex] | complex +143 ~ field48: typing.Union[None, complex] | PYI016 [*] Duplicate union member `complex` @@ -1023,10 +946,8 @@ PYI016 [*] Duplicate union member `complex` | help: Remove duplicate union member `complex` | -143 | field48: typing.Union[typing.Optional[typing.Union[complex, complex]], complex] - - field49: typing.Optional[complex | complex] | complex +144 - field49: typing.Optional[complex | complex] | complex 144 + field49: None | complex -145 | | PYI016 [*] Duplicate union member `complex` @@ -1041,10 +962,8 @@ PYI016 [*] Duplicate union member `complex` | help: Remove duplicate union member `complex` | -143 | field48: typing.Union[typing.Optional[typing.Union[complex, complex]], complex] - - field49: typing.Optional[complex | complex] | complex +144 - field49: typing.Optional[complex | complex] | complex 144 + field49: None | complex -145 | | PYI016 Duplicate union member `None` @@ -1071,10 +990,8 @@ PYI016 [*] Duplicate union member `typing.Literal[f"{x=}"]` | help: Remove duplicate union member `typing.Literal[f"{x=}"]` | -153 | field51: typing.Literal[f"{x=}"] | typing.Literal[f"{x}"] # OK (f"{x=}" -> "x=1", f"{x}" -> "1") - - field52: typing.Literal[f"{x=}"] | typing.Literal[f"{x=}"] # Error (true duplicate) +154 - field52: typing.Literal[f"{x=}"] | typing.Literal[f"{x=}"] # Error (true duplicate) 154 + field52: typing.Literal[f"{x=}"] # Error (true duplicate) -155 | field53: typing.Literal[f"{x:.2f}"] | typing.Literal[f"{x:.3f}"] # OK (different format specs) | PYI016 [*] Duplicate union member `typing.Literal[f"{x}"]` @@ -1089,8 +1006,6 @@ PYI016 [*] Duplicate union member `typing.Literal[f"{x}"]` | help: Remove duplicate union member `typing.Literal[f"{x}"]` | -155 | field53: typing.Literal[f"{x:.2f}"] | typing.Literal[f"{x:.3f}"] # OK (different format specs) - - field54: typing.Literal[f"{x}"] | typing.Literal[f"{x}"] # Error (true duplicate) +156 - field54: typing.Literal[f"{x}"] | typing.Literal[f"{x}"] # Error (true duplicate) 156 + field54: typing.Literal[f"{x}"] # Error (true duplicate) -157 | field55: typing.Literal[f"{x =}"] | typing.Literal[f"{x=}"] # OK (different debug text due to spaces) | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI016_PYI016.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI016_PYI016.pyi.snap index e528fa5fdcb3f..938921c073332 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI016_PYI016.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI016_PYI016.pyi.snap @@ -12,10 +12,8 @@ PYI016 [*] Duplicate union member `str` | help: Remove duplicate union member `str` | -6 | # Should emit for duplicate field types. - - field2: str | str # PYI016: Duplicate union member `str` +7 - field2: str | str # PYI016: Duplicate union member `str` 7 + field2: str # PYI016: Duplicate union member `str` -8 | | PYI016 [*] Duplicate union member `int` @@ -28,10 +26,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -9 | # Should emit for union types in arguments. - - def func1(arg1: int | int): # PYI016: Duplicate union member `int` +10 - def func1(arg1: int | int): # PYI016: Duplicate union member `int` 10 + def func1(arg1: int): # PYI016: Duplicate union member `int` -11 | print(arg1) | PYI016 [*] Duplicate union member `str` @@ -44,10 +40,8 @@ PYI016 [*] Duplicate union member `str` | help: Remove duplicate union member `str` | -13 | # Should emit for unions in return types. - - def func2() -> str | str: # PYI016: Duplicate union member `str` +14 - def func2() -> str | str: # PYI016: Duplicate union member `str` 14 + def func2() -> str: # PYI016: Duplicate union member `str` -15 | return "my string" | PYI016 [*] Duplicate union member `str` @@ -61,10 +55,8 @@ PYI016 [*] Duplicate union member `str` | help: Remove duplicate union member `str` | -17 | # Should emit in longer unions, even if not directly adjacent. - - field3: str | str | int # PYI016: Duplicate union member `str` +18 - field3: str | str | int # PYI016: Duplicate union member `str` 18 + field3: str | int # PYI016: Duplicate union member `str` -19 | field4: int | int | str # PYI016: Duplicate union member `int` | PYI016 [*] Duplicate union member `int` @@ -79,10 +71,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -18 | field3: str | str | int # PYI016: Duplicate union member `str` - - field4: int | int | str # PYI016: Duplicate union member `int` +19 - field4: int | int | str # PYI016: Duplicate union member `int` 19 + field4: int | str # PYI016: Duplicate union member `int` -20 | field5: str | int | str # PYI016: Duplicate union member `str` | PYI016 [*] Duplicate union member `str` @@ -96,10 +86,8 @@ PYI016 [*] Duplicate union member `str` | help: Remove duplicate union member `str` | -19 | field4: int | int | str # PYI016: Duplicate union member `int` - - field5: str | int | str # PYI016: Duplicate union member `str` +20 - field5: str | int | str # PYI016: Duplicate union member `str` 20 + field5: str | int # PYI016: Duplicate union member `str` -21 | field6: int | bool | str | int # PYI016: Duplicate union member `int` | PYI016 [*] Duplicate union member `int` @@ -114,10 +102,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -20 | field5: str | int | str # PYI016: Duplicate union member `str` - - field6: int | bool | str | int # PYI016: Duplicate union member `int` +21 - field6: int | bool | str | int # PYI016: Duplicate union member `int` 21 + field6: int | bool | str # PYI016: Duplicate union member `int` -22 | | PYI016 [*] Duplicate union member `int` @@ -131,10 +117,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -26 | # Should emit for strangely-bracketed unions. - - field8: int | (str | int) # PYI016: Duplicate union member `int` +27 - field8: int | (str | int) # PYI016: Duplicate union member `int` 27 + field8: int | str # PYI016: Duplicate union member `int` -28 | | PYI016 [*] Duplicate union member `int` @@ -147,10 +131,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -29 | # Should handle user brackets when fixing. - - field9: int | (int | str) # PYI016: Duplicate union member `int` +30 - field9: int | (int | str) # PYI016: Duplicate union member `int` 30 + field9: int | str # PYI016: Duplicate union member `int` -31 | field10: (str | int) | str # PYI016: Duplicate union member `str` | PYI016 [*] Duplicate union member `str` @@ -165,10 +147,8 @@ PYI016 [*] Duplicate union member `str` | help: Remove duplicate union member `str` | -30 | field9: int | (int | str) # PYI016: Duplicate union member `int` - - field10: (str | int) | str # PYI016: Duplicate union member `str` +31 - field10: (str | int) | str # PYI016: Duplicate union member `str` 31 + field10: str | int # PYI016: Duplicate union member `str` -32 | | PYI016 [*] Duplicate union member `int` @@ -182,10 +162,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -33 | # Should emit for nested unions. - - field11: dict[int | int, str] +34 - field11: dict[int | int, str] 34 + field11: dict[int, str] -35 | | PYI016 [*] Duplicate union member `int` @@ -198,10 +176,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -36 | # Should emit for unions with more than two cases - - field12: int | int | int # Error +37 - field12: int | int | int # Error 37 + field12: int # Error -38 | field13: int | int | int | int # Error | PYI016 [*] Duplicate union member `int` @@ -214,10 +190,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -36 | # Should emit for unions with more than two cases - - field12: int | int | int # Error +37 - field12: int | int | int # Error 37 + field12: int # Error -38 | field13: int | int | int | int # Error | PYI016 [*] Duplicate union member `int` @@ -232,10 +206,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -37 | field12: int | int | int # Error - - field13: int | int | int | int # Error +38 - field13: int | int | int | int # Error 38 + field13: int # Error -39 | | PYI016 [*] Duplicate union member `int` @@ -250,10 +222,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -37 | field12: int | int | int # Error - - field13: int | int | int | int # Error +38 - field13: int | int | int | int # Error 38 + field13: int # Error -39 | | PYI016 [*] Duplicate union member `int` @@ -268,10 +238,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -37 | field12: int | int | int # Error - - field13: int | int | int | int # Error +38 - field13: int | int | int | int # Error 38 + field13: int # Error -39 | | PYI016 [*] Duplicate union member `int` @@ -285,10 +253,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -40 | # Should emit for unions with more than two cases, even if not directly adjacent - - field14: int | int | str | int # Error +41 - field14: int | int | str | int # Error 41 + field14: int | str # Error -42 | | PYI016 [*] Duplicate union member `int` @@ -302,10 +268,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -40 | # Should emit for unions with more than two cases, even if not directly adjacent - - field14: int | int | str | int # Error +41 - field14: int | int | str | int # Error 41 + field14: int | str # Error -42 | | PYI016 [*] Duplicate union member `typing.Literal[1]` @@ -319,10 +283,8 @@ PYI016 [*] Duplicate union member `typing.Literal[1]` | help: Remove duplicate union member `typing.Literal[1]` | -43 | # Should emit for duplicate literal types; also covered by PYI030 - - field15: typing.Literal[1] | typing.Literal[1] # Error +44 - field15: typing.Literal[1] | typing.Literal[1] # Error 44 + field15: typing.Literal[1] # Error -45 | | PYI016 [*] Duplicate union member `set[int]` @@ -338,17 +300,15 @@ PYI016 [*] Duplicate union member `set[int]` | help: Remove duplicate union member `set[int]` | -52 | # Should emit in cases with newlines - - field18: typing.Union[ - - set[ - - int # foo - - ], - - set[ - - int # bar - - ], - - ] # Error, newline and comment will not be emitted in message +53 - field18: typing.Union[ +54 - set[ +55 - int # foo +56 - ], +57 - set[ +58 - int # bar +59 - ], +60 - ] # Error, newline and comment will not be emitted in message 53 + field18: set[int] # Error, newline and comment will not be emitted in message -54 | | note: This is an unsafe fix and may change runtime behavior @@ -363,10 +323,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -62 | # Should emit in cases with `typing.Union` instead of `|` - - field19: typing.Union[int, int] # Error +63 - field19: typing.Union[int, int] # Error 63 + field19: int # Error -64 | | PYI016 [*] Duplicate union member `int` @@ -380,10 +338,11 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | + 1 ~ import typing + 2 | + … 65 | # Should emit in cases with nested `typing.Union` - - field20: typing.Union[int, typing.Union[int, str]] # Error -66 + field20: typing.Union[int, str] # Error -67 | +66 ~ field20: typing.Union[int, str] # Error | PYI016 [*] Duplicate union member `int` @@ -397,10 +356,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -68 | # Should emit in cases with mixed `typing.Union` and `|` - - field21: typing.Union[int, int | str] # Error +69 - field21: typing.Union[int, int | str] # Error 69 + field21: int | str # Error -70 | | PYI016 [*] Duplicate union member `int` @@ -414,10 +371,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -71 | # Should emit only once in cases with multiple nested `typing.Union` - - field22: typing.Union[int, typing.Union[int, typing.Union[int, int]]] # Error +72 - field22: typing.Union[int, typing.Union[int, typing.Union[int, int]]] # Error 72 + field22: int # Error -73 | | PYI016 [*] Duplicate union member `int` @@ -431,10 +386,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -71 | # Should emit only once in cases with multiple nested `typing.Union` - - field22: typing.Union[int, typing.Union[int, typing.Union[int, int]]] # Error +72 - field22: typing.Union[int, typing.Union[int, typing.Union[int, int]]] # Error 72 + field22: int # Error -73 | | PYI016 [*] Duplicate union member `int` @@ -448,10 +401,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -71 | # Should emit only once in cases with multiple nested `typing.Union` - - field22: typing.Union[int, typing.Union[int, typing.Union[int, int]]] # Error +72 - field22: typing.Union[int, typing.Union[int, typing.Union[int, int]]] # Error 72 + field22: int # Error -73 | | PYI016 [*] Duplicate union member `set[int]` @@ -466,11 +417,9 @@ PYI016 [*] Duplicate union member `set[int]` | help: Remove duplicate union member `set[int]` | -74 | # Should emit in cases with newlines - - field23: set[ # foo - - int] | set[int] +75 - field23: set[ # foo +76 - int] | set[int] 75 + field23: set[int] -76 | | note: This is an unsafe fix and may change runtime behavior @@ -486,10 +435,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -80 | # we incorrectly re-checked the nested union). - - field24: typing.Union[int, typing.Union[int, int]] # PYI016: Duplicate union member `int` +81 - field24: typing.Union[int, typing.Union[int, int]] # PYI016: Duplicate union member `int` 81 + field24: int # PYI016: Duplicate union member `int` -82 | | PYI016 [*] Duplicate union member `int` @@ -504,10 +451,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -80 | # we incorrectly re-checked the nested union). - - field24: typing.Union[int, typing.Union[int, int]] # PYI016: Duplicate union member `int` +81 - field24: typing.Union[int, typing.Union[int, int]] # PYI016: Duplicate union member `int` 81 + field24: int # PYI016: Duplicate union member `int` -82 | | PYI016 [*] Duplicate union member `int` @@ -522,10 +467,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -85 | # we incorrectly re-checked the nested union). - - field25: typing.Union[int, int | int] # PYI016: Duplicate union member `int` +86 - field25: typing.Union[int, int | int] # PYI016: Duplicate union member `int` 86 + field25: int # PYI016: Duplicate union member `int` -87 | | PYI016 [*] Duplicate union member `int` @@ -540,10 +483,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -85 | # we incorrectly re-checked the nested union). - - field25: typing.Union[int, int | int] # PYI016: Duplicate union member `int` +86 - field25: typing.Union[int, int | int] # PYI016: Duplicate union member `int` 86 + field25: int # PYI016: Duplicate union member `int` -87 | | PYI016 [*] Duplicate union member `int` @@ -557,10 +498,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -88 | # Should emit in cases with nested `typing.Union` - - field26: typing.Union[typing.Union[int, int]] # PYI016: Duplicate union member `int` +89 - field26: typing.Union[typing.Union[int, int]] # PYI016: Duplicate union member `int` 89 + field26: int # PYI016: Duplicate union member `int` -90 | | PYI016 [*] Duplicate union member `int` @@ -574,10 +513,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -91 | # Should emit in cases with nested `typing.Union` - - field27: typing.Union[typing.Union[typing.Union[int, int]]] # PYI016: Duplicate union member `int` +92 - field27: typing.Union[typing.Union[typing.Union[int, int]]] # PYI016: Duplicate union member `int` 92 + field27: int # PYI016: Duplicate union member `int` -93 | | PYI016 [*] Duplicate union member `int` @@ -591,10 +528,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -94 | # Should emit in cases with mixed `typing.Union` and `|` - - field28: typing.Union[int | int] # Error +95 - field28: typing.Union[int | int] # Error 95 + field28: int # Error -96 | | PYI016 [*] Duplicate union member `int` @@ -608,10 +543,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -97 | # Should emit twice in cases with multiple nested `typing.Union` - - field29: typing.Union[int, typing.Union[typing.Union[int, int]]] # Error +98 - field29: typing.Union[int, typing.Union[typing.Union[int, int]]] # Error 98 + field29: int # Error -99 | | PYI016 [*] Duplicate union member `int` @@ -625,10 +558,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -97 | # Should emit twice in cases with multiple nested `typing.Union` - - field29: typing.Union[int, typing.Union[typing.Union[int, int]]] # Error +98 - field29: typing.Union[int, typing.Union[typing.Union[int, int]]] # Error 98 + field29: int # Error -99 | | PYI016 [*] Duplicate union member `int` @@ -642,10 +573,11 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | + 1 ~ import typing + 2 | + … 100 | # Should emit once in cases with multiple nested `typing.Union` - - field30: typing.Union[int, typing.Union[typing.Union[int, str]]] # Error -101 + field30: typing.Union[int, str] # Error -102 | +101 ~ field30: typing.Union[int, str] # Error | PYI016 [*] Duplicate union member `int` @@ -659,10 +591,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -103 | # Should emit once, and fix to `typing.Union[float, int]` - - field31: typing.Union[float, typing.Union[int | int]] # Error +104 - field31: typing.Union[float, typing.Union[int | int]] # Error 104 + field31: float | int # Error -105 | | PYI016 [*] Duplicate union member `int` @@ -676,10 +606,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -106 | # Should emit once, and fix to `typing.Union[float, int]` - - field32: typing.Union[float, typing.Union[int | int | int]] # Error +107 - field32: typing.Union[float, typing.Union[int | int | int]] # Error 107 + field32: float | int # Error -108 | | PYI016 [*] Duplicate union member `int` @@ -693,10 +621,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -106 | # Should emit once, and fix to `typing.Union[float, int]` - - field32: typing.Union[float, typing.Union[int | int | int]] # Error +107 - field32: typing.Union[float, typing.Union[int | int | int]] # Error 107 + field32: float | int # Error -108 | | PYI016 [*] Duplicate union member `int` @@ -710,10 +636,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -109 | # Test case for mixed union type fix - - field33: typing.Union[typing.Union[int | int] | typing.Union[int | int]] # Error +110 - field33: typing.Union[typing.Union[int | int] | typing.Union[int | int]] # Error 110 + field33: int # Error -111 | | PYI016 [*] Duplicate union member `int` @@ -727,10 +651,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -109 | # Test case for mixed union type fix - - field33: typing.Union[typing.Union[int | int] | typing.Union[int | int]] # Error +110 - field33: typing.Union[typing.Union[int | int] | typing.Union[int | int]] # Error 110 + field33: int # Error -111 | | PYI016 [*] Duplicate union member `int` @@ -744,10 +666,8 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | -109 | # Test case for mixed union type fix - - field33: typing.Union[typing.Union[int | int] | typing.Union[int | int]] # Error +110 - field33: typing.Union[typing.Union[int | int] | typing.Union[int | int]] # Error 110 + field33: int # Error -111 | | PYI016 [*] Duplicate union member `list[int]` @@ -761,10 +681,11 @@ PYI016 [*] Duplicate union member `list[int]` | help: Remove duplicate union member `list[int]` | + 1 ~ import typing + 2 | + … 112 | # Test case for mixed union type - - field34: typing.Union[list[int], str] | typing.Union[bytes, list[int]] # Error -113 + field34: typing.Union[list[int], str, bytes] # Error -114 | +113 ~ field34: typing.Union[list[int], str, bytes] # Error | PYI016 [*] Duplicate union member `None` @@ -779,10 +700,8 @@ PYI016 [*] Duplicate union member `None` | help: Remove duplicate union member `None` | -120 | # equivalent to None - - field39: typing.Optional[None] +121 - field39: typing.Optional[None] 121 + field39: None -122 | # equivalent to int | None | PYI016 [*] Duplicate union member `None` @@ -797,10 +716,11 @@ PYI016 [*] Duplicate union member `None` | help: Remove duplicate union member `None` | + 1 ~ import typing + 2 | + … 122 | # equivalent to int | None - - field40: typing.Union[typing.Optional[int], None] -123 + field40: typing.Union[None, int] -124 | field41: typing.Optional[typing.Union[int, None]] +123 ~ field40: typing.Union[None, int] | PYI016 [*] Duplicate union member `None` @@ -815,10 +735,11 @@ PYI016 [*] Duplicate union member `None` | help: Remove duplicate union member `None` | + 1 ~ import typing + 2 | + … 123 | field40: typing.Union[typing.Optional[int], None] - - field41: typing.Optional[typing.Union[int, None]] -124 + field41: typing.Union[None, int] -125 | field42: typing.Union[typing.Optional[int], typing.Optional[int]] +124 ~ field41: typing.Union[None, int] | PYI016 [*] Duplicate union member `None` @@ -833,10 +754,11 @@ PYI016 [*] Duplicate union member `None` | help: Remove duplicate union member `None` | + 1 ~ import typing + 2 | + … 124 | field41: typing.Optional[typing.Union[int, None]] - - field42: typing.Union[typing.Optional[int], typing.Optional[int]] -125 + field42: typing.Union[None, int] -126 | field43: typing.Optional[int] | None +125 ~ field42: typing.Union[None, int] | PYI016 [*] Duplicate union member `int` @@ -851,10 +773,11 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | + 1 ~ import typing + 2 | + … 124 | field41: typing.Optional[typing.Union[int, None]] - - field42: typing.Union[typing.Optional[int], typing.Optional[int]] -125 + field42: typing.Union[None, int] -126 | field43: typing.Optional[int] | None +125 ~ field42: typing.Union[None, int] | PYI016 [*] Duplicate union member `None` @@ -869,10 +792,8 @@ PYI016 [*] Duplicate union member `None` | help: Remove duplicate union member `None` | -125 | field42: typing.Union[typing.Optional[int], typing.Optional[int]] - - field43: typing.Optional[int] | None +126 - field43: typing.Optional[int] | None 126 + field43: None | int -127 | field44: typing.Optional[int | None] | PYI016 [*] Duplicate union member `None` @@ -887,10 +808,8 @@ PYI016 [*] Duplicate union member `None` | help: Remove duplicate union member `None` | -126 | field43: typing.Optional[int] | None - - field44: typing.Optional[int | None] +127 - field44: typing.Optional[int | None] 127 + field44: None | int -128 | field45: typing.Optional[int] | typing.Optional[int] | PYI016 [*] Duplicate union member `None` @@ -905,10 +824,11 @@ PYI016 [*] Duplicate union member `None` | help: Remove duplicate union member `None` | + 1 ~ import typing + 2 | + … 127 | field44: typing.Optional[int | None] - - field45: typing.Optional[int] | typing.Optional[int] -128 + field45: typing.Union[None, int] -129 | # equivalent to int | dict | None +128 ~ field45: typing.Union[None, int] | PYI016 [*] Duplicate union member `int` @@ -923,10 +843,11 @@ PYI016 [*] Duplicate union member `int` | help: Remove duplicate union member `int` | + 1 ~ import typing + 2 | + … 127 | field44: typing.Optional[int | None] - - field45: typing.Optional[int] | typing.Optional[int] -128 + field45: typing.Union[None, int] -129 | # equivalent to int | dict | None +128 ~ field45: typing.Union[None, int] | PYI016 [*] Duplicate union member `None` @@ -940,10 +861,11 @@ PYI016 [*] Duplicate union member `None` | help: Remove duplicate union member `None` | + 1 ~ import typing + 2 | + … 129 | # equivalent to int | dict | None - - field46: typing.Union[typing.Optional[int], typing.Optional[dict]] -130 + field46: typing.Union[None, int, dict] -131 | field47: typing.Optional[int] | typing.Optional[dict] +130 ~ field46: typing.Union[None, int, dict] | PYI016 [*] Duplicate union member `None` @@ -958,10 +880,11 @@ PYI016 [*] Duplicate union member `None` | help: Remove duplicate union member `None` | + 1 ~ import typing + 2 | + … 130 | field46: typing.Union[typing.Optional[int], typing.Optional[dict]] - - field47: typing.Optional[int] | typing.Optional[dict] -131 + field47: typing.Union[None, int, dict] -132 | +131 ~ field47: typing.Union[None, int, dict] | PYI016 [*] Duplicate union member `complex` @@ -974,10 +897,11 @@ PYI016 [*] Duplicate union member `complex` | help: Remove duplicate union member `complex` | + 1 ~ import typing + 2 | + … 133 | # avoid reporting twice - - field48: typing.Union[typing.Optional[typing.Union[complex, complex]], complex] -134 + field48: typing.Union[None, complex] -135 | field49: typing.Optional[complex | complex] | complex +134 ~ field48: typing.Union[None, complex] | PYI016 [*] Duplicate union member `complex` @@ -990,10 +914,11 @@ PYI016 [*] Duplicate union member `complex` | help: Remove duplicate union member `complex` | + 1 ~ import typing + 2 | + … 133 | # avoid reporting twice - - field48: typing.Union[typing.Optional[typing.Union[complex, complex]], complex] -134 + field48: typing.Union[None, complex] -135 | field49: typing.Optional[complex | complex] | complex +134 ~ field48: typing.Union[None, complex] | PYI016 [*] Duplicate union member `complex` @@ -1005,8 +930,7 @@ PYI016 [*] Duplicate union member `complex` | ^^^^^^^ help: Remove duplicate union member `complex` | -134 | field48: typing.Union[typing.Optional[typing.Union[complex, complex]], complex] - - field49: typing.Optional[complex | complex] | complex +135 - field49: typing.Optional[complex | complex] | complex 135 + field49: None | complex | @@ -1019,7 +943,6 @@ PYI016 [*] Duplicate union member `complex` | ^^^^^^^ help: Remove duplicate union member `complex` | -134 | field48: typing.Union[typing.Optional[typing.Union[complex, complex]], complex] - - field49: typing.Optional[complex | complex] | complex +135 - field49: typing.Optional[complex | complex] | complex 135 + field49: None | complex | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI018_PYI018.py.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI018_PYI018.py.snap index a7995482c6d5a..6697a8e86caf3 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI018_PYI018.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI018_PYI018.py.snap @@ -13,9 +13,7 @@ PYI018 [*] Private TypeVar `_T` is never used | help: Remove unused private TypeVar `_T` | -5 | - - _T = typing.TypeVar("_T") -6 | _Ts = typing_extensions.TypeVarTuple("_Ts") +6 - _T = typing.TypeVar("_T") | note: This is an unsafe fix and may change runtime behavior @@ -30,9 +28,7 @@ PYI018 [*] Private TypeVarTuple `_Ts` is never used | help: Remove unused private TypeVarTuple `_Ts` | -6 | _T = typing.TypeVar("_T") - - _Ts = typing_extensions.TypeVarTuple("_Ts") -7 | _P = ParamSpec("_P") +7 - _Ts = typing_extensions.TypeVarTuple("_Ts") | note: This is an unsafe fix and may change runtime behavior @@ -48,9 +44,7 @@ PYI018 [*] Private ParamSpec `_P` is never used | help: Remove unused private ParamSpec `_P` | -7 | _Ts = typing_extensions.TypeVarTuple("_Ts") - - _P = ParamSpec("_P") -8 | _P2 = typing.ParamSpec("_P2") +8 - _P = ParamSpec("_P") | note: This is an unsafe fix and may change runtime behavior @@ -64,11 +58,9 @@ PYI018 [*] Private ParamSpec `_P2` is never used 10 | _Ts2 = TypeVarTuple("_Ts2") | help: Remove unused private ParamSpec `_P2` - | -8 | _P = ParamSpec("_P") - - _P2 = typing.ParamSpec("_P2") -9 | _Ts2 = TypeVarTuple("_Ts2") - | + | + 9 - _P2 = typing.ParamSpec("_P2") + | note: This is an unsafe fix and may change runtime behavior PYI018 [*] Private TypeVarTuple `_Ts2` is never used @@ -83,8 +75,6 @@ PYI018 [*] Private TypeVarTuple `_Ts2` is never used | help: Remove unused private TypeVarTuple `_Ts2` | -9 | _P2 = typing.ParamSpec("_P2") - - _Ts2 = TypeVarTuple("_Ts2") -10 | +10 - _Ts2 = TypeVarTuple("_Ts2") | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI018_PYI018.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI018_PYI018.pyi.snap index 614cb105ca513..8b7911225ab92 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI018_PYI018.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI018_PYI018.pyi.snap @@ -13,9 +13,7 @@ PYI018 [*] Private TypeVar `_T` is never used | help: Remove unused private TypeVar `_T` | -5 | - - _T = typing.TypeVar("_T") -6 | _Ts = typing_extensions.TypeVarTuple("_Ts") +6 - _T = typing.TypeVar("_T") | note: This is an unsafe fix and may change runtime behavior @@ -30,9 +28,7 @@ PYI018 [*] Private TypeVarTuple `_Ts` is never used | help: Remove unused private TypeVarTuple `_Ts` | -6 | _T = typing.TypeVar("_T") - - _Ts = typing_extensions.TypeVarTuple("_Ts") -7 | _P = ParamSpec("_P") +7 - _Ts = typing_extensions.TypeVarTuple("_Ts") | note: This is an unsafe fix and may change runtime behavior @@ -48,9 +44,7 @@ PYI018 [*] Private ParamSpec `_P` is never used | help: Remove unused private ParamSpec `_P` | -7 | _Ts = typing_extensions.TypeVarTuple("_Ts") - - _P = ParamSpec("_P") -8 | _P2 = typing.ParamSpec("_P2") +8 - _P = ParamSpec("_P") | note: This is an unsafe fix and may change runtime behavior @@ -64,11 +58,9 @@ PYI018 [*] Private ParamSpec `_P2` is never used 10 | _Ts2 = TypeVarTuple("_Ts2") | help: Remove unused private ParamSpec `_P2` - | -8 | _P = ParamSpec("_P") - - _P2 = typing.ParamSpec("_P2") -9 | _Ts2 = TypeVarTuple("_Ts2") - | + | + 9 - _P2 = typing.ParamSpec("_P2") + | note: This is an unsafe fix and may change runtime behavior PYI018 [*] Private TypeVarTuple `_Ts2` is never used @@ -83,8 +75,6 @@ PYI018 [*] Private TypeVarTuple `_Ts2` is never used | help: Remove unused private TypeVarTuple `_Ts2` | -9 | _P2 = typing.ParamSpec("_P2") - - _Ts2 = TypeVarTuple("_Ts2") -10 | +10 - _Ts2 = TypeVarTuple("_Ts2") | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI019_PYI019_0.py.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI019_PYI019_0.py.snap index 18480905e97f9..d8c1e62898a8c 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI019_PYI019_0.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI019_PYI019_0.py.snap @@ -9,10 +9,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `_S` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `_S` with `Self` | +1 ~ from typing import TypeVar, Self, Type, cast +2 | +… 6 | class BadClass: - - def __new__(cls: type[_S], *args: str, **kwargs: int) -> _S: ... # PYI019 -7 + def __new__(cls, *args: str, **kwargs: int) -> Self: ... # PYI019 -8 | +7 ~ def __new__(cls, *args: str, **kwargs: int) -> Self: ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `_S` @@ -22,10 +23,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `_S` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `_S` with `Self` | -9 | - - def bad_instance_method(self: _S, arg: bytes) -> _S: ... # PYI019 -10 + def bad_instance_method(self, arg: bytes) -> Self: ... # PYI019 -11 | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … + 9 | +10 ~ def bad_instance_method(self, arg: bytes) -> Self: ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `_S` @@ -36,10 +38,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `_S` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `_S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 13 | @classmethod - - def bad_class_method(cls: type[_S], arg: int) -> _S: ... # PYI019 -14 + def bad_class_method(cls, arg: int) -> Self: ... # PYI019 -15 | +14 ~ def bad_class_method(cls, arg: int) -> Self: ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `_S` @@ -50,10 +53,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `_S` | ^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `_S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 17 | @classmethod - - def bad_posonly_class_method(cls: type[_S], /) -> _S: ... # PYI019 -18 + def bad_posonly_class_method(cls, /) -> Self: ... # PYI019 -19 | +18 ~ def bad_posonly_class_method(cls, /) -> Self: ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -65,10 +69,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 38 | class PEP695BadDunderNew[T]: - - def __new__[S](cls: type[S], *args: Any, ** kwargs: Any) -> S: ... # PYI019 -39 + def __new__(cls, *args: Any, ** kwargs: Any) -> Self: ... # PYI019 -40 | +39 ~ def __new__(cls, *args: Any, ** kwargs: Any) -> Self: ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -78,10 +83,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | ^^^^^^^^^^^^^^^^^ help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 41 | - - def generic_instance_method[S](self: S) -> S: ... # PYI019 -42 + def generic_instance_method(self) -> Self: ... # PYI019 -43 | +42 ~ def generic_instance_method(self) -> Self: ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -93,10 +99,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | ^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 53 | @foo_classmethod - - def foo[S](cls: type[S]) -> S: ... # PYI019 -54 + def foo(cls) -> Self: ... # PYI019 -55 | +54 ~ def foo(cls) -> Self: ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -110,10 +117,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 60 | class PEP695Fix: - - def __new__[S: PEP695Fix](cls: type[S]) -> S: ... -61 + def __new__(cls) -> Self: ... -62 | +61 ~ def __new__(cls) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -128,10 +136,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 62 | - - def __init_subclass__[S](cls: type[S]) -> S: ... -63 + def __init_subclass__(cls) -> Self: ... -64 | +63 ~ def __init_subclass__(cls) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -146,10 +155,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 64 | - - def __neg__[S: PEP695Fix](self: S) -> S: ... -65 + def __neg__(self) -> Self: ... -66 | +65 ~ def __neg__(self) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -164,10 +174,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 66 | - - def __pos__[S](self: S) -> S: ... -67 + def __pos__(self) -> Self: ... -68 | +67 ~ def __pos__(self) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -182,10 +193,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 68 | - - def __add__[S: PEP695Fix](self: S, other: S) -> S: ... -69 + def __add__(self, other: Self) -> Self: ... -70 | +69 ~ def __add__(self, other: Self) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -200,10 +212,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 70 | - - def __sub__[S](self: S, other: S) -> S: ... -71 + def __sub__(self, other: Self) -> Self: ... -72 | +71 ~ def __sub__(self, other: Self) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -217,10 +230,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 73 | @classmethod - - def class_method_bound[S: PEP695Fix](cls: type[S]) -> S: ... -74 + def class_method_bound(cls) -> Self: ... -75 | +74 ~ def class_method_bound(cls) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -234,10 +248,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 76 | @classmethod - - def class_method_unbound[S](cls: type[S]) -> S: ... -77 + def class_method_unbound(cls) -> Self: ... -78 | +77 ~ def class_method_unbound(cls) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -252,10 +267,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 78 | - - def instance_method_bound[S: PEP695Fix](self: S) -> S: ... -79 + def instance_method_bound(self) -> Self: ... -80 | +79 ~ def instance_method_bound(self) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -270,10 +286,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 80 | - - def instance_method_unbound[S](self: S) -> S: ... -81 + def instance_method_unbound(self) -> Self: ... -82 | +81 ~ def instance_method_unbound(self) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -288,10 +305,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 82 | - - def instance_method_bound_with_another_parameter[S: PEP695Fix](self: S, other: S) -> S: ... -83 + def instance_method_bound_with_another_parameter(self, other: Self) -> Self: ... -84 | +83 ~ def instance_method_bound_with_another_parameter(self, other: Self) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -306,10 +324,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 84 | - - def instance_method_unbound_with_another_parameter[S](self: S, other: S) -> S: ... -85 + def instance_method_unbound_with_another_parameter(self, other: Self) -> Self: ... -86 | +85 ~ def instance_method_unbound_with_another_parameter(self, other: Self) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -324,10 +343,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 86 | - - def multiple_type_vars[S, *Ts, T](self: S, other: S, /, *args: *Ts, a: T, b: list[T]) -> S: ... -87 + def multiple_type_vars[*Ts, T](self, other: Self, /, *args: *Ts, a: T, b: list[T]) -> Self: ... -88 | +87 ~ def multiple_type_vars[*Ts, T](self, other: Self, /, *args: *Ts, a: T, b: list[T]) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `_S695` @@ -339,10 +359,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `_S695` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `_S695` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 88 | - - def mixing_old_and_new_style_type_vars[T](self: _S695, a: T, b: T) -> _S695: ... -89 + def mixing_old_and_new_style_type_vars[T](self, a: T, b: T) -> Self: ... -90 | +89 ~ def mixing_old_and_new_style_type_vars[T](self, a: T, b: T) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -356,10 +377,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 93 | @classmethod - - def m[S](cls: type[S], /) -> S[int]: ... -94 + def m(cls, /) -> Self[int]: ... -95 | def n(self: S) -> S[int]: ... +94 ~ def m(cls, /) -> Self[int]: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -371,10 +393,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 113 | @classmethod - - def m[S](cls: type[S]) -> type[S]: ... # PYI019 -114 + def m(cls) -> type[Self]: ... # PYI019 -115 | +114 ~ def m(cls) -> type[Self]: ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -388,10 +411,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 117 | class SelfNotUsedInReturnAnnotation: - - def m[S](self: S, other: S) -> int: ... -118 + def m(self, other: Self) -> int: ... -119 | @classmethod +118 ~ def m(self, other: Self) -> int: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -403,10 +427,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 119 | @classmethod - - def n[S](cls: type[S], other: S) -> int: ... -120 + def n(cls, other: Self) -> int: ... -121 | +120 ~ def n(cls, other: Self) -> int: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -420,10 +445,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 134 | class NoReturnAnnotations: - - def m[S](self: S, other: S): ... -135 + def m(self, other: Self): ... -136 | @classmethod +135 ~ def m(self, other: Self): ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -438,10 +464,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 136 | @classmethod - - def n[S](cls: type[S], other: S): ... -137 + def n(cls, other: Self): ... -138 | +137 ~ def n(cls, other: Self): ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -454,10 +481,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 139 | class MultipleBoundParameters: - - def m[S: int, T: int](self: S, other: T) -> S: ... -140 + def m[T: int](self, other: T) -> Self: ... -141 | def n[T: (int, str), S: (int, str)](self: S, other: T) -> S: ... +140 ~ def m[T: int](self, other: T) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -472,10 +500,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 140 | def m[S: int, T: int](self: S, other: T) -> S: ... - - def n[T: (int, str), S: (int, str)](self: S, other: T) -> S: ... -141 + def n[T: (int, str)](self, other: T) -> Self: ... -142 | +141 ~ def n[T: (int, str)](self, other: T) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -489,12 +518,12 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 143 | class MethodsWithBody: - - def m[S](self: S, other: S) -> S: - - x: S = other -144 + def m(self, other: Self) -> Self: -145 + x: Self = other -146 | return x +144 ~ def m(self, other: Self) -> Self: +145 ~ x: Self = other | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -508,12 +537,12 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 148 | @classmethod - - def n[S](cls: type[S], other: S) -> S: - - x: type[S] = type(other) -149 + def n(cls, other: Self) -> Self: -150 + x: type[Self] = type(other) -151 | return x() +149 ~ def n(cls, other: Self) -> Self: +150 ~ x: type[Self] = type(other) | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -527,12 +556,12 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 153 | class StringizedReferencesCanBeFixed: - - def m[S](self: S) -> S: - - x = cast("list[tuple[S, S]]", self) -154 + def m(self) -> Self: -155 + x = cast("list[tuple[Self, Self]]", self) -156 | return x +154 ~ def m(self) -> Self: +155 ~ x = cast("list[tuple[Self, Self]]", self) | PYI019 Use `Self` instead of custom TypeVar `_T` @@ -557,10 +586,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 163 | class DeletionsAreNotTouched: - - def m[S](self: S) -> S: -164 + def m(self) -> Self: -165 | # `S` is not a local variable here, and `del` can only be used with local variables, +164 ~ def m(self) -> Self: | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -574,10 +604,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 172 | class NamesShadowingTypeVarAreNotTouched: - - def m[S](self: S) -> S: -173 + def m(self) -> Self: -174 | type S = int +173 ~ def m(self) -> Self: | PYI019 [*] Use `Self` instead of custom TypeVar `_S` @@ -591,10 +622,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `_S` | help: Replace TypeVar `_S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 188 | class BadClassWithStringTypeHints: - - def bad_instance_method_with_string_annotations(self: "_S", arg: str) -> "_S": ... # PYI019 -189 + def bad_instance_method_with_string_annotations(self, arg: str) -> "Self": ... # PYI019 -190 | +189 ~ def bad_instance_method_with_string_annotations(self, arg: str) -> "Self": ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `_S` @@ -605,10 +637,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `_S` | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `_S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 191 | @classmethod - - def bad_class_method_with_string_annotations(cls: "type[_S]") -> "_S": ... # PYI019 -192 + def bad_class_method_with_string_annotations(cls) -> "Self": ... # PYI019 -193 | +192 ~ def bad_class_method_with_string_annotations(cls) -> "Self": ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `_S` @@ -619,10 +652,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `_S` | ^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `_S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 195 | @classmethod - - def bad_class_method_with_mixed_annotations_1(cls: "type[_S]") -> _S: ... # PYI019 -196 + def bad_class_method_with_mixed_annotations_1(cls) -> Self: ... # PYI019 -197 | +196 ~ def bad_class_method_with_mixed_annotations_1(cls) -> Self: ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `_S` @@ -633,10 +667,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `_S` | ^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `_S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 199 | @classmethod - - def bad_class_method_with_mixed_annotations_1(cls: type[_S]) -> "_S": ... # PYI019 -200 + def bad_class_method_with_mixed_annotations_1(cls) -> "Self": ... # PYI019 -201 | +200 ~ def bad_class_method_with_mixed_annotations_1(cls) -> "Self": ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -648,8 +683,9 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type, cast + 2 | + … 204 | @classmethod - - def m[S](cls: "type[S]") -> "type[S]": ... # PYI019 -205 + def m(cls) -> "type[Self]": ... # PYI019 -206 | +205 ~ def m(cls) -> "type[Self]": ... # PYI019 | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI019_PYI019_0.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI019_PYI019_0.pyi.snap index 05c83b71d94c6..fa7fc79127b46 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI019_PYI019_0.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI019_PYI019_0.pyi.snap @@ -9,10 +9,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `_S` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `_S` with `Self` | +1 ~ from typing import TypeVar, Self, Type +2 | +… 6 | class BadClass: - - def __new__(cls: type[_S], *args: str, **kwargs: int) -> _S: ... # PYI019 -7 + def __new__(cls, *args: str, **kwargs: int) -> Self: ... # PYI019 -8 | +7 ~ def __new__(cls, *args: str, **kwargs: int) -> Self: ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `_S` @@ -22,10 +23,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `_S` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `_S` with `Self` | -9 | - - def bad_instance_method(self: _S, arg: bytes) -> _S: ... # PYI019 -10 + def bad_instance_method(self, arg: bytes) -> Self: ... # PYI019 -11 | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … + 9 | +10 ~ def bad_instance_method(self, arg: bytes) -> Self: ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `_S` @@ -36,10 +38,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `_S` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `_S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 13 | @classmethod - - def bad_class_method(cls: type[_S], arg: int) -> _S: ... # PYI019 -14 + def bad_class_method(cls, arg: int) -> Self: ... # PYI019 -15 | +14 ~ def bad_class_method(cls, arg: int) -> Self: ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `_S` @@ -50,10 +53,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `_S` | ^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `_S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 17 | @classmethod - - def bad_posonly_class_method(cls: type[_S], /) -> _S: ... # PYI019 -18 + def bad_posonly_class_method(cls, /) -> Self: ... # PYI019 -19 | +18 ~ def bad_posonly_class_method(cls, /) -> Self: ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -65,10 +69,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 38 | class PEP695BadDunderNew[T]: - - def __new__[S](cls: type[S], *args: Any, ** kwargs: Any) -> S: ... # PYI019 -39 + def __new__(cls, *args: Any, ** kwargs: Any) -> Self: ... # PYI019 -40 | +39 ~ def __new__(cls, *args: Any, ** kwargs: Any) -> Self: ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -78,10 +83,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | ^^^^^^^^^^^^^^^^^ help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 41 | - - def generic_instance_method[S](self: S) -> S: ... # PYI019 -42 + def generic_instance_method(self) -> Self: ... # PYI019 -43 | +42 ~ def generic_instance_method(self) -> Self: ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -93,10 +99,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | ^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 53 | @foo_classmethod - - def foo[S](cls: type[S]) -> S: ... # PYI019 -54 + def foo(cls) -> Self: ... # PYI019 -55 | +54 ~ def foo(cls) -> Self: ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -110,10 +117,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 60 | class PEP695Fix: - - def __new__[S: PEP695Fix](cls: type[S]) -> S: ... -61 + def __new__(cls) -> Self: ... -62 | +61 ~ def __new__(cls) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -128,10 +136,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 62 | - - def __init_subclass__[S](cls: type[S]) -> S: ... -63 + def __init_subclass__(cls) -> Self: ... -64 | +63 ~ def __init_subclass__(cls) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -146,10 +155,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 64 | - - def __neg__[S: PEP695Fix](self: S) -> S: ... -65 + def __neg__(self) -> Self: ... -66 | +65 ~ def __neg__(self) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -164,10 +174,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 66 | - - def __pos__[S](self: S) -> S: ... -67 + def __pos__(self) -> Self: ... -68 | +67 ~ def __pos__(self) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -182,10 +193,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 68 | - - def __add__[S: PEP695Fix](self: S, other: S) -> S: ... -69 + def __add__(self, other: Self) -> Self: ... -70 | +69 ~ def __add__(self, other: Self) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -200,10 +212,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 70 | - - def __sub__[S](self: S, other: S) -> S: ... -71 + def __sub__(self, other: Self) -> Self: ... -72 | +71 ~ def __sub__(self, other: Self) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -217,10 +230,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 73 | @classmethod - - def class_method_bound[S: PEP695Fix](cls: type[S]) -> S: ... -74 + def class_method_bound(cls) -> Self: ... -75 | +74 ~ def class_method_bound(cls) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -234,10 +248,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 76 | @classmethod - - def class_method_unbound[S](cls: type[S]) -> S: ... -77 + def class_method_unbound(cls) -> Self: ... -78 | +77 ~ def class_method_unbound(cls) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -252,10 +267,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 78 | - - def instance_method_bound[S: PEP695Fix](self: S) -> S: ... -79 + def instance_method_bound(self) -> Self: ... -80 | +79 ~ def instance_method_bound(self) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -270,10 +286,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 80 | - - def instance_method_unbound[S](self: S) -> S: ... -81 + def instance_method_unbound(self) -> Self: ... -82 | +81 ~ def instance_method_unbound(self) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -288,10 +305,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 82 | - - def instance_method_bound_with_another_parameter[S: PEP695Fix](self: S, other: S) -> S: ... -83 + def instance_method_bound_with_another_parameter(self, other: Self) -> Self: ... -84 | +83 ~ def instance_method_bound_with_another_parameter(self, other: Self) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -306,10 +324,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 84 | - - def instance_method_unbound_with_another_parameter[S](self: S, other: S) -> S: ... -85 + def instance_method_unbound_with_another_parameter(self, other: Self) -> Self: ... -86 | +85 ~ def instance_method_unbound_with_another_parameter(self, other: Self) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -324,10 +343,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 86 | - - def multiple_type_vars[S, *Ts, T](self: S, other: S, /, *args: *Ts, a: T, b: list[T]) -> S: ... -87 + def multiple_type_vars[*Ts, T](self, other: Self, /, *args: *Ts, a: T, b: list[T]) -> Self: ... -88 | +87 ~ def multiple_type_vars[*Ts, T](self, other: Self, /, *args: *Ts, a: T, b: list[T]) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `_S695` @@ -339,10 +359,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `_S695` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `_S695` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 88 | - - def mixing_old_and_new_style_type_vars[T](self: _S695, a: T, b: T) -> _S695: ... -89 + def mixing_old_and_new_style_type_vars[T](self, a: T, b: T) -> Self: ... -90 | +89 ~ def mixing_old_and_new_style_type_vars[T](self, a: T, b: T) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -356,10 +377,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 93 | @classmethod - - def m[S](cls: type[S], /) -> S[int]: ... -94 + def m(cls, /) -> Self[int]: ... -95 | def n(self: S) -> S[int]: ... +94 ~ def m(cls, /) -> Self[int]: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -371,10 +393,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 113 | @classmethod - - def m[S](cls: type[S]) -> type[S]: ... # PYI019 -114 + def m(cls) -> type[Self]: ... # PYI019 -115 | +114 ~ def m(cls) -> type[Self]: ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -385,10 +408,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | ^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 117 | class PEP695TypeParameterAtTheVeryEndOfTheList: - - def f[T, S](self: S) -> S: ... -118 + def f[T](self) -> Self: ... -119 | +118 ~ def f[T](self) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `_S695` @@ -401,10 +425,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `_S695` | help: Replace TypeVar `_S695` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 121 | class PEP695Again: - - def mixing_and_nested[T](self: _S695, a: list[_S695], b: dict[_S695, str | T | set[_S695]]) -> _S695: ... -122 + def mixing_and_nested[T](self, a: list[Self], b: dict[Self, str | T | set[Self]]) -> Self: ... -123 | def also_uses_s695_but_should_not_be_edited(self, v: set[tuple[_S695]]) -> _S695: ... +122 ~ def mixing_and_nested[T](self, a: list[Self], b: dict[Self, str | T | set[Self]]) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -425,19 +450,15 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 125 | @classmethod - - def comment_in_fix_range[T, S]( - - cls: type[ # Lorem ipsum - - S - - ], -126 + def comment_in_fix_range[T]( -127 + cls, +126 ~ def comment_in_fix_range[T]( +127 ~ cls, 128 | a: T, - - b: tuple[S, T] - - ) -> S: ... -129 + b: tuple[Self, T] -130 + ) -> Self: ... -131 | +129 ~ b: tuple[Self, T] +130 ~ ) -> Self: ... | note: This is an unsafe fix and may change runtime behavior @@ -458,20 +479,18 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | |__________^ help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 133 | - - def comment_outside_fix_range[T, S]( - - self: S, -134 + def comment_outside_fix_range[T]( -135 + self, +134 ~ def comment_outside_fix_range[T]( +135 ~ self, 136 | a: T, 137 | b: tuple[ 138 | # Lorem ipsum - - S, T -139 + Self, T +139 ~ Self, T 140 | ] - - ) -> S: ... -141 + ) -> Self: ... -142 | +141 ~ ) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -485,10 +504,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 144 | class SelfNotUsedInReturnAnnotation: - - def m[S](self: S, other: S) -> int: ... -145 + def m(self, other: Self) -> int: ... -146 | @classmethod +145 ~ def m(self, other: Self) -> int: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -500,10 +520,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 146 | @classmethod - - def n[S](cls: type[S], other: S) -> int: ... -147 + def n(cls, other: Self) -> int: ... -148 | +147 ~ def n(cls, other: Self) -> int: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -517,10 +538,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 160 | class NoReturnAnnotations: - - def m[S](self: S, other: S): ... -161 + def m(self, other: Self): ... -162 | @classmethod +161 ~ def m(self, other: Self): ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -535,10 +557,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 162 | @classmethod - - def n[S](cls: type[S], other: S): ... -163 + def n(cls, other: Self): ... -164 | +163 ~ def n(cls, other: Self): ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -551,10 +574,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 165 | class MultipleBoundParameters: - - def m[S: int, T: int](self: S, other: T) -> S: ... -166 + def m[T: int](self, other: T) -> Self: ... -167 | def n[T: (int, str), S: (int, str)](self: S, other: T) -> S: ... +166 ~ def m[T: int](self, other: T) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -566,10 +590,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 166 | def m[S: int, T: int](self: S, other: T) -> S: ... - - def n[T: (int, str), S: (int, str)](self: S, other: T) -> S: ... -167 + def n[T: (int, str)](self, other: T) -> Self: ... -168 | +167 ~ def n[T: (int, str)](self, other: T) -> Self: ... | PYI019 [*] Use `Self` instead of custom TypeVar `_S` @@ -583,10 +608,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `_S` | help: Replace TypeVar `_S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 180 | class BadClassWithStringTypeHints: - - def bad_instance_method_with_string_annotations(self: "_S", arg: str) -> "_S": ... # PYI019 -181 + def bad_instance_method_with_string_annotations(self, arg: str) -> "Self": ... # PYI019 -182 | +181 ~ def bad_instance_method_with_string_annotations(self, arg: str) -> "Self": ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `_S` @@ -597,10 +623,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `_S` | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `_S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 183 | @classmethod - - def bad_class_method_with_string_annotations(cls: "type[_S]") -> "_S": ... # PYI019 -184 + def bad_class_method_with_string_annotations(cls) -> "Self": ... # PYI019 -185 | +184 ~ def bad_class_method_with_string_annotations(cls) -> "Self": ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `_S` @@ -611,10 +638,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `_S` | ^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `_S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 187 | @classmethod - - def bad_class_method_with_mixed_annotations_1(cls: "type[_S]") -> _S: ... # PYI019 -188 + def bad_class_method_with_mixed_annotations_1(cls) -> Self: ... # PYI019 -189 | +188 ~ def bad_class_method_with_mixed_annotations_1(cls) -> Self: ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `_S` @@ -625,10 +653,11 @@ PYI019 [*] Use `Self` instead of custom TypeVar `_S` | ^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `_S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 191 | @classmethod - - def bad_class_method_with_mixed_annotations_1(cls: type[_S]) -> "_S": ... # PYI019 -192 + def bad_class_method_with_mixed_annotations_1(cls) -> "Self": ... # PYI019 -193 | +192 ~ def bad_class_method_with_mixed_annotations_1(cls) -> "Self": ... # PYI019 | PYI019 [*] Use `Self` instead of custom TypeVar `S` @@ -640,8 +669,9 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace TypeVar `S` with `Self` | + 1 ~ from typing import TypeVar, Self, Type + 2 | + … 196 | @classmethod - - def m[S](cls: "type[S]") -> "type[S]": ... # PYI019 -197 + def m(cls) -> "type[Self]": ... # PYI019 -198 | +197 ~ def m(cls) -> "type[Self]": ... # PYI019 | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI019_PYI019_1.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI019_PYI019_1.pyi.snap index fbf3fc8400723..154c098e574de 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI019_PYI019_1.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI019_PYI019_1.pyi.snap @@ -9,7 +9,8 @@ PYI019 [*] Use `Self` instead of custom TypeVar `S` | ^^^^^^^^^^^^^^^^^ help: Replace TypeVar `S` with `Self` | +1 ~ import typing +2 | 3 | class F: - - def m[S](self: S) -> S: ... -4 + def m(self) -> typing.Self: ... +4 ~ def m(self) -> typing.Self: ... | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI020_PYI020.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI020_PYI020.pyi.snap index 8b95f0163b2a7..dd2eaec2255fd 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI020_PYI020.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI020_PYI020.pyi.snap @@ -13,10 +13,8 @@ PYI020 [*] Quoted annotations should not be included in stubs | help: Remove quotes | -6 | - - def f(x: "int"): ... # Y020 Quoted annotations should never be used in stubs +7 - def f(x: "int"): ... # Y020 Quoted annotations should never be used in stubs 7 + def f(x: int): ... # Y020 Quoted annotations should never be used in stubs -8 | def g(x: list["int"]): ... # Y020 Quoted annotations should never be used in stubs | PYI020 [*] Quoted annotations should not be included in stubs @@ -29,10 +27,8 @@ PYI020 [*] Quoted annotations should not be included in stubs | help: Remove quotes | -7 | def f(x: "int"): ... # Y020 Quoted annotations should never be used in stubs - - def g(x: list["int"]): ... # Y020 Quoted annotations should never be used in stubs +8 - def g(x: list["int"]): ... # Y020 Quoted annotations should never be used in stubs 8 + def g(x: list[int]): ... # Y020 Quoted annotations should never be used in stubs -9 | _T = TypeVar("_T", bound="int") # Y020 Quoted annotations should never be used in stubs | PYI020 [*] Quoted annotations should not be included in stubs @@ -46,12 +42,10 @@ PYI020 [*] Quoted annotations should not be included in stubs 11 | def h(w: Literal["a", "b"], x: typing.Literal["c"], y: typing_extensions.Literal["d"], z: _T) -> _T: ... | help: Remove quotes - | -8 | def g(x: list["int"]): ... # Y020 Quoted annotations should never be used in stubs - - _T = TypeVar("_T", bound="int") # Y020 Quoted annotations should never be used in stubs -9 + _T = TypeVar("_T", bound=int) # Y020 Quoted annotations should never be used in stubs -10 | - | + | +9 - _T = TypeVar("_T", bound="int") # Y020 Quoted annotations should never be used in stubs +9 + _T = TypeVar("_T", bound=int) # Y020 Quoted annotations should never be used in stubs + | PYI020 [*] Quoted annotations should not be included in stubs --> PYI020.pyi:13:12 @@ -64,10 +58,8 @@ PYI020 [*] Quoted annotations should not be included in stubs | help: Remove quotes | -12 | - - def j() -> "int": ... # Y020 Quoted annotations should never be used in stubs +13 - def j() -> "int": ... # Y020 Quoted annotations should never be used in stubs 13 + def j() -> int: ... # Y020 Quoted annotations should never be used in stubs -14 | Alias: TypeAlias = list["int"] # Y020 Quoted annotations should never be used in stubs | PYI020 [*] Quoted annotations should not be included in stubs @@ -81,10 +73,8 @@ PYI020 [*] Quoted annotations should not be included in stubs | help: Remove quotes | -13 | def j() -> "int": ... # Y020 Quoted annotations should never be used in stubs - - Alias: TypeAlias = list["int"] # Y020 Quoted annotations should never be used in stubs +14 - Alias: TypeAlias = list["int"] # Y020 Quoted annotations should never be used in stubs 14 + Alias: TypeAlias = list[int] # Y020 Quoted annotations should never be used in stubs -15 | | PYI020 [*] Quoted annotations should not be included in stubs @@ -98,10 +88,8 @@ PYI020 [*] Quoted annotations should not be included in stubs | help: Remove quotes | -15 | - - class Child(list["int"]): # Y020 Quoted annotations should never be used in stubs +16 - class Child(list["int"]): # Y020 Quoted annotations should never be used in stubs 16 + class Child(list[int]): # Y020 Quoted annotations should never be used in stubs -17 | """Documented and guaranteed useful.""" # Y021 Docstrings should not be included in stubs | PYI020 [*] Quoted annotations should not be included in stubs @@ -115,10 +103,8 @@ PYI020 [*] Quoted annotations should not be included in stubs | help: Remove quotes | -19 | if sys.platform == "linux": - - f: "int" # Y020 Quoted annotations should never be used in stubs +20 - f: "int" # Y020 Quoted annotations should never be used in stubs 20 + f: int # Y020 Quoted annotations should never be used in stubs -21 | elif sys.platform == "win32": | PYI020 [*] Quoted annotations should not be included in stubs @@ -133,10 +119,8 @@ PYI020 [*] Quoted annotations should not be included in stubs | help: Remove quotes | -21 | elif sys.platform == "win32": - - f: "str" # Y020 Quoted annotations should never be used in stubs +22 - f: "str" # Y020 Quoted annotations should never be used in stubs 22 + f: str # Y020 Quoted annotations should never be used in stubs -23 | else: | PYI020 [*] Quoted annotations should not be included in stubs @@ -151,8 +135,6 @@ PYI020 [*] Quoted annotations should not be included in stubs | help: Remove quotes | -23 | else: - - f: "bytes" # Y020 Quoted annotations should never be used in stubs +24 - f: "bytes" # Y020 Quoted annotations should never be used in stubs 24 + f: bytes # Y020 Quoted annotations should never be used in stubs -25 | | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI021_PYI021.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI021_PYI021.pyi.snap index 998e64986e1a1..5f90a97970818 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI021_PYI021.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI021_PYI021.pyi.snap @@ -11,9 +11,8 @@ PYI021 [*] Docstrings should not be included in stubs | help: Remove docstring | - - """foo""" # ERROR PYI021 +1 - """foo""" # ERROR PYI021 1 + # ERROR PYI021 -2 | | note: This is an unsafe fix and may change runtime behavior @@ -28,10 +27,8 @@ PYI021 [*] Docstrings should not be included in stubs | help: Remove docstring | -3 | def foo(): - - """foo""" # ERROR PYI021 +4 - """foo""" # ERROR PYI021 4 + ... # ERROR PYI021 -5 | | note: This is an unsafe fix and may change runtime behavior @@ -46,10 +43,8 @@ PYI021 [*] Docstrings should not be included in stubs | help: Remove docstring | -6 | class Bar: - - """bar""" # ERROR PYI021 +7 - """bar""" # ERROR PYI021 7 + ... # ERROR PYI021 -8 | | note: This is an unsafe fix and may change runtime behavior @@ -64,10 +59,8 @@ PYI021 [*] Docstrings should not be included in stubs | help: Remove docstring | -9 | class Qux: - - """qux""" # ERROR PYI021 +10 - """qux""" # ERROR PYI021 10 + # ERROR PYI021 -11 | | note: This is an unsafe fix and may change runtime behavior @@ -85,12 +78,9 @@ PYI021 [*] Docstrings should not be included in stubs | help: Remove docstring | -14 | class Baz: - - """Multiline docstring - - - - Lorem ipsum dolor sit amet - - """ -15 + -16 | +15 - """Multiline docstring +16 - +17 - Lorem ipsum dolor sit amet +18 - """ | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_1.py.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_1.py.snap index c9b60ae0d1ebc..92dbb11e452a0 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_1.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_1.py.snap @@ -9,11 +9,8 @@ PYI025 [*] Use `from collections.abc import Set as AbstractSet` to avoid confusi | ^^^ help: Alias `Set` to `AbstractSet` | -9 | def f(): - - from collections.abc import Set # PYI025 -10 + from collections.abc import Set as AbstractSet # PYI025 -11 | - | +10 | from collections.abc import Set as AbstractSet # PYI025 + | ++++++++++++++ PYI025 [*] Use `from collections.abc import Set as AbstractSet` to avoid confusion with the `set` builtin --> PYI025_1.py:14:51 @@ -26,14 +23,10 @@ PYI025 [*] Use `from collections.abc import Set as AbstractSet` to avoid confusi | help: Alias `Set` to `AbstractSet` | -13 | def f(): - - from collections.abc import Container, Sized, Set, ValuesView # PYI025 -14 + from collections.abc import Container, Sized, Set as AbstractSet, ValuesView # PYI025 +14 ~ from collections.abc import Container, Sized, Set as AbstractSet, ValuesView # PYI025 15 | - - GLOBAL: Set[int] = set() -16 + GLOBAL: AbstractSet[int] = set() +16 ~ GLOBAL: AbstractSet[int] = set() 17 | 18 | class Class: - - member: Set[int] -19 + member: AbstractSet[int] +19 ~ member: AbstractSet[int] | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_1.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_1.pyi.snap index ecf214efaf370..f857db1838aa0 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_1.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_1.pyi.snap @@ -12,11 +12,8 @@ PYI025 [*] Use `from collections.abc import Set as AbstractSet` to avoid confusi | help: Alias `Set` to `AbstractSet` | -7 | def f(): - - from collections.abc import Set # PYI025 -8 + from collections.abc import Set as AbstractSet # PYI025 -9 | - | +8 | from collections.abc import Set as AbstractSet # PYI025 + | ++++++++++++++ PYI025 [*] Use `from collections.abc import Set as AbstractSet` to avoid confusion with the `set` builtin --> PYI025_1.pyi:11:51 @@ -29,11 +26,8 @@ PYI025 [*] Use `from collections.abc import Set as AbstractSet` to avoid confusi | help: Alias `Set` to `AbstractSet` | -10 | def f(): - - from collections.abc import Container, Sized, Set, ValuesView # PYI025 -11 + from collections.abc import Container, Sized, Set as AbstractSet, ValuesView # PYI025 -12 | - | +11 | from collections.abc import Container, Sized, Set as AbstractSet, ValuesView # PYI025 + | ++++++++++++++ PYI025 [*] Use `from collections.abc import Set as AbstractSet` to avoid confusion with the `set` builtin --> PYI025_1.pyi:16:37 @@ -47,22 +41,16 @@ PYI025 [*] Use `from collections.abc import Set as AbstractSet` to avoid confusi | help: Alias `Set` to `AbstractSet` | -15 | if True: - - from collections.abc import Set -16 + from collections.abc import Set as AbstractSet +16 ~ from collections.abc import Set as AbstractSet 17 | else: - - Set = 1 -18 + AbstractSet = 1 +18 ~ AbstractSet = 1 19 | --------------------------------------------------------------------------------- + … 23 | - - del Set -24 + del AbstractSet +24 ~ del AbstractSet 25 | 26 | def f(): - - print(Set) -27 + print(AbstractSet) -28 | +27 ~ print(AbstractSet) | PYI025 [*] Use `from collections.abc import Set as AbstractSet` to avoid confusion with the `set` builtin @@ -77,28 +65,20 @@ PYI025 [*] Use `from collections.abc import Set as AbstractSet` to avoid confusi | help: Alias `Set` to `AbstractSet` | -19 | - - x: Set = set() -20 + x: AbstractSet = set() +20 ~ x: AbstractSet = set() 21 | - - x: Set -22 + x: AbstractSet +22 ~ x: AbstractSet 23 | --------------------------------------------------------------------------------- + … 32 | - - from collections.abc import Set -33 + from collections.abc import Set as AbstractSet +33 ~ from collections.abc import Set as AbstractSet 34 | 35 | def f(): 36 | """Test: global symbol renaming.""" - - global Set -37 + global AbstractSet +37 ~ global AbstractSet 38 | - - Set = 1 - - print(Set) -39 + AbstractSet = 1 -40 + print(AbstractSet) -41 | +39 ~ AbstractSet = 1 +40 ~ print(AbstractSet) | PYI025 [*] Use `from collections.abc import Set as AbstractSet` to avoid confusion with the `set` builtin @@ -113,16 +93,11 @@ PYI025 [*] Use `from collections.abc import Set as AbstractSet` to avoid confusi | help: Alias `Set` to `AbstractSet` | -43 | """Test: nonlocal symbol renaming.""" - - from collections.abc import Set -44 + from collections.abc import Set as AbstractSet +44 ~ from collections.abc import Set as AbstractSet 45 | 46 | def g(): - - nonlocal Set -47 + nonlocal AbstractSet +47 ~ nonlocal AbstractSet 48 | - - Set = 1 - - print(Set) -49 + AbstractSet = 1 -50 + print(AbstractSet) +49 ~ AbstractSet = 1 +50 ~ print(AbstractSet) | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_2.py.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_2.py.snap index e9d84d177adfa..5e4c0cb17ec0b 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_2.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_2.py.snap @@ -13,23 +13,17 @@ PYI025 [*] Use `from collections.abc import Set as AbstractSet` to avoid confusi | help: Alias `Set` to `AbstractSet` | -2 | - - from collections.abc import Set -3 + from collections.abc import Set as AbstractSet -4 | - - __all__ = ["Set"] -5 + __all__ = ["AbstractSet"] -6 | -7 | if True: - - __all__ += [r'''Set'''] -8 + __all__ += ["AbstractSet"] -9 | + 3 ~ from collections.abc import Set as AbstractSet + 4 | + 5 ~ __all__ = ["AbstractSet"] + 6 | + 7 | if True: + 8 ~ __all__ += ["AbstractSet"] + 9 | 10 | if 1: - - __all__ += ["S" "e" "t"] -11 + __all__ += ["AbstractSet"] +11 ~ __all__ += ["AbstractSet"] 12 | 13 | if not False: - - __all__ += ["Se" 't'] -14 + __all__ += ["AbstractSet"] +14 ~ __all__ += ["AbstractSet"] | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_2.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_2.pyi.snap index 5687e50609e8e..ed5aadbf5f78b 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_2.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_2.pyi.snap @@ -13,23 +13,17 @@ PYI025 [*] Use `from collections.abc import Set as AbstractSet` to avoid confusi | help: Alias `Set` to `AbstractSet` | -2 | - - from collections.abc import Set -3 + from collections.abc import Set as AbstractSet -4 | - - __all__ = ["Set"] -5 + __all__ = ["AbstractSet"] -6 | -7 | if True: - - __all__ += [r'''Set'''] -8 + __all__ += ["AbstractSet"] -9 | + 3 ~ from collections.abc import Set as AbstractSet + 4 | + 5 ~ __all__ = ["AbstractSet"] + 6 | + 7 | if True: + 8 ~ __all__ += ["AbstractSet"] + 9 | 10 | if 1: - - __all__ += ["S" "e" "t"] -11 + __all__ += ["AbstractSet"] +11 ~ __all__ += ["AbstractSet"] 12 | 13 | if not False: - - __all__ += ["Se" 't'] -14 + __all__ += ["AbstractSet"] +14 ~ __all__ += ["AbstractSet"] | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_3.py.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_3.py.snap index 53947d49061b1..ecf461b74d3d0 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_3.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_3.py.snap @@ -10,8 +10,6 @@ PYI025 [*] Use `from collections.abc import Set as AbstractSet` to avoid confusi | ^^^ help: Alias `Set` to `AbstractSet` | -5 | - - from collections.abc import Set as Set # PYI025 triggered but fix is not marked as safe -6 + from collections.abc import Set as AbstractSet # PYI025 triggered but fix is not marked as safe - | +6 | from collections.abc import Set as AbstractSet # PYI025 triggered but fix is not marked as safe + | ++++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_3.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_3.pyi.snap index 8411cbc8b5945..4471dae8d3a0a 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_3.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI025_PYI025_3.pyi.snap @@ -10,8 +10,6 @@ PYI025 [*] Use `from collections.abc import Set as AbstractSet` to avoid confusi | ^^^ help: Alias `Set` to `AbstractSet` | -5 | - - from collections.abc import Set as Set # PYI025 triggered but fix is not marked as safe -6 + from collections.abc import Set as AbstractSet # PYI025 triggered but fix is not marked as safe - | +6 | from collections.abc import Set as AbstractSet # PYI025 triggered but fix is not marked as safe + | ++++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI026_PYI026.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI026_PYI026.pyi.snap index 4289bafea5bee..f35ca7a65d260 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI026_PYI026.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI026_PYI026.pyi.snap @@ -13,12 +13,9 @@ PYI026 [*] Use `typing.TypeAlias` for type alias, e.g., `NewAny: TypeAlias = Any | help: Add `TypeAlias` annotation | - - from typing import Literal, Any -1 + from typing import Literal, Any, TypeAlias +1 ~ from typing import Literal, Any, TypeAlias 2 | - - NewAny = Any -3 + NewAny: TypeAlias = Any -4 | OptionalStr = typing.Optional[str] +3 ~ NewAny: TypeAlias = Any | PYI026 [*] Use `typing.TypeAlias` for type alias, e.g., `OptionalStr: TypeAlias = typing.Optional[str]` @@ -32,13 +29,10 @@ PYI026 [*] Use `typing.TypeAlias` for type alias, e.g., `OptionalStr: TypeAlias | help: Add `TypeAlias` annotation | - - from typing import Literal, Any -1 + from typing import Literal, Any, TypeAlias +1 ~ from typing import Literal, Any, TypeAlias 2 | 3 | NewAny = Any - - OptionalStr = typing.Optional[str] -4 + OptionalStr: TypeAlias = typing.Optional[str] -5 | Foo = Literal["foo"] +4 ~ OptionalStr: TypeAlias = typing.Optional[str] | PYI026 [*] Use `typing.TypeAlias` for type alias, e.g., `Foo: TypeAlias = Literal["foo"]` @@ -53,14 +47,11 @@ PYI026 [*] Use `typing.TypeAlias` for type alias, e.g., `Foo: TypeAlias = Litera | help: Add `TypeAlias` annotation | - - from typing import Literal, Any -1 + from typing import Literal, Any, TypeAlias +1 ~ from typing import Literal, Any, TypeAlias 2 | 3 | NewAny = Any 4 | OptionalStr = typing.Optional[str] - - Foo = Literal["foo"] -5 + Foo: TypeAlias = Literal["foo"] -6 | IntOrStr = int | str +5 ~ Foo: TypeAlias = Literal["foo"] | PYI026 [*] Use `typing.TypeAlias` for type alias, e.g., `IntOrStr: TypeAlias = int | str` @@ -74,15 +65,11 @@ PYI026 [*] Use `typing.TypeAlias` for type alias, e.g., `IntOrStr: TypeAlias = i | help: Add `TypeAlias` annotation | - - from typing import Literal, Any -1 + from typing import Literal, Any, TypeAlias +1 ~ from typing import Literal, Any, TypeAlias 2 | -3 | NewAny = Any -4 | OptionalStr = typing.Optional[str] +… 5 | Foo = Literal["foo"] - - IntOrStr = int | str -6 + IntOrStr: TypeAlias = int | str -7 | AliasNone = None +6 ~ IntOrStr: TypeAlias = int | str | PYI026 [*] Use `typing.TypeAlias` for type alias, e.g., `AliasNone: TypeAlias = None` @@ -97,14 +84,11 @@ PYI026 [*] Use `typing.TypeAlias` for type alias, e.g., `AliasNone: TypeAlias = | help: Add `TypeAlias` annotation | - - from typing import Literal, Any -1 + from typing import Literal, Any, TypeAlias +1 ~ from typing import Literal, Any, TypeAlias 2 | --------------------------------------------------------------------------------- +… 6 | IntOrStr = int | str - - AliasNone = None -7 + AliasNone: TypeAlias = None -8 | +7 ~ AliasNone: TypeAlias = None | PYI026 [*] Use `typing.TypeAlias` for type alias, e.g., `FLAG_THIS: TypeAlias = None` @@ -118,12 +102,9 @@ PYI026 [*] Use `typing.TypeAlias` for type alias, e.g., `FLAG_THIS: TypeAlias = | help: Add `TypeAlias` annotation | - - from typing import Literal, Any -1 + from typing import Literal, Any, TypeAlias -2 | --------------------------------------------------------------------------------- + 1 ~ from typing import Literal, Any, TypeAlias + 2 | + … 16 | class NotAnEnum: - - FLAG_THIS = None -17 + FLAG_THIS: TypeAlias = None -18 | +17 ~ FLAG_THIS: TypeAlias = None | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI029_PYI029.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI029_PYI029.pyi.snap index 17e0f21b2032a..7568025eb982d 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI029_PYI029.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI029_PYI029.pyi.snap @@ -12,10 +12,8 @@ PYI029 [*] Defining `__str__` in a stub is almost always redundant | help: Remove definition of `__str__` | -9 | class ShouldRemoveSingle: - - def __str__(self) -> builtins.str: ... # Error: PYI029 +10 - def __str__(self) -> builtins.str: ... # Error: PYI029 10 + pass # Error: PYI029 -11 | | PYI029 [*] Defining `__repr__` in a stub is almost always redundant @@ -28,9 +26,7 @@ PYI029 [*] Defining `__repr__` in a stub is almost always redundant | help: Remove definition of `__repr__` | -12 | class ShouldRemove: - - def __repr__(self) -> str: ... # Error: PYI029 -13 | def __str__(self) -> builtins.str: ... # Error: PYI029 +13 - def __repr__(self) -> str: ... # Error: PYI029 | PYI029 [*] Defining `__str__` in a stub is almost always redundant @@ -45,7 +41,5 @@ PYI029 [*] Defining `__str__` in a stub is almost always redundant | help: Remove definition of `__str__` | -13 | def __repr__(self) -> str: ... # Error: PYI029 - - def __str__(self) -> builtins.str: ... # Error: PYI029 -14 | +14 - def __str__(self) -> builtins.str: ... # Error: PYI029 | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI030_PYI030.py.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI030_PYI030.py.snap index 56362992b0868..c9545860e548e 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI030_PYI030.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI030_PYI030.py.snap @@ -11,12 +11,10 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite 11 | # Should emit for union types in arguments. | help: Replace with a single `Literal` - | -8 | # Should emit for duplicate field types. - - field2: Literal[1] | Literal[2] # Error -9 + field2: Literal[1, 2] # Error -10 | - | + | +9 - field2: Literal[1] | Literal[2] # Error +9 + field2: Literal[1, 2] # Error + | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` --> PYI030.py:12:17 @@ -28,10 +26,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -11 | # Should emit for union types in arguments. - - def func1(arg1: Literal[1] | Literal[2]): # Error +12 - def func1(arg1: Literal[1] | Literal[2]): # Error 12 + def func1(arg1: Literal[1, 2]): # Error -13 | print(arg1) | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -44,10 +40,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -16 | # Should emit for unions in return types. - - def func2() -> Literal[1] | Literal[2]: # Error +17 - def func2() -> Literal[1] | Literal[2]: # Error 17 + def func2() -> Literal[1, 2]: # Error -18 | return "my Literal[1]ing" | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -61,10 +55,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -21 | # Should emit in longer unions, even if not directly adjacent. - - field3: Literal[1] | Literal[2] | str # Error +22 - field3: Literal[1] | Literal[2] | str # Error 22 + field3: Literal[1, 2] | str # Error -23 | field4: str | Literal[1] | Literal[2] # Error | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -79,10 +71,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -22 | field3: Literal[1] | Literal[2] | str # Error - - field4: str | Literal[1] | Literal[2] # Error +23 - field4: str | Literal[1] | Literal[2] # Error 23 + field4: Literal[1, 2] | str # Error -24 | field5: Literal[1] | str | Literal[2] # Error | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -96,10 +86,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -23 | field4: str | Literal[1] | Literal[2] # Error - - field5: Literal[1] | str | Literal[2] # Error +24 - field5: Literal[1] | str | Literal[2] # Error 24 + field5: Literal[1, 2] | str # Error -25 | field6: Literal[1] | bool | Literal[2] | str # Error | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -114,10 +102,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -24 | field5: Literal[1] | str | Literal[2] # Error - - field6: Literal[1] | bool | Literal[2] | str # Error +25 - field6: Literal[1] | bool | Literal[2] | str # Error 25 + field6: Literal[1, 2] | bool | str # Error -26 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -131,10 +117,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -27 | # Should emit for non-type unions. - - field7 = Literal[1] | Literal[2] # Error +28 - field7 = Literal[1] | Literal[2] # Error 28 + field7 = Literal[1, 2] # Error -29 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -148,10 +132,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -30 | # Should emit for parenthesized unions. - - field8: Literal[1] | (Literal[2] | str) # Error +31 - field8: Literal[1] | (Literal[2] | str) # Error 31 + field8: Literal[1, 2] | str # Error -32 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -164,10 +146,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -33 | # Should handle user parentheses when fixing. - - field9: Literal[1] | (Literal[2] | str) # Error +34 - field9: Literal[1] | (Literal[2] | str) # Error 34 + field9: Literal[1, 2] | str # Error -35 | field10: (Literal[1] | str) | Literal[2] # Error | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -182,10 +162,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -34 | field9: Literal[1] | (Literal[2] | str) # Error - - field10: (Literal[1] | str) | Literal[2] # Error +35 - field10: (Literal[1] | str) | Literal[2] # Error 35 + field10: Literal[1, 2] | str # Error -36 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -199,10 +177,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -37 | # Should emit for union in generic parent type. - - field11: dict[Literal[1] | Literal[2], str] # Error +38 - field11: dict[Literal[1] | Literal[2], str] # Error 38 + field11: dict[Literal[1, 2], str] # Error -39 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2, 3]` @@ -215,10 +191,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -40 | # Should emit for unions with more than two cases - - field12: Literal[1] | Literal[2] | Literal[3] # Error +41 - field12: Literal[1] | Literal[2] | Literal[3] # Error 41 + field12: Literal[1, 2, 3] # Error -42 | field13: Literal[1] | Literal[2] | Literal[3] | Literal[4] # Error | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2, 3, 4]` @@ -233,10 +207,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -41 | field12: Literal[1] | Literal[2] | Literal[3] # Error - - field13: Literal[1] | Literal[2] | Literal[3] | Literal[4] # Error +42 - field13: Literal[1] | Literal[2] | Literal[3] | Literal[4] # Error 42 + field13: Literal[1, 2, 3, 4] # Error -43 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2, 3]` @@ -250,10 +222,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -44 | # Should emit for unions with more than two cases, even if not directly adjacent - - field14: Literal[1] | Literal[2] | str | Literal[3] # Error +45 - field14: Literal[1] | Literal[2] | str | Literal[3] # Error 45 + field14: Literal[1, 2, 3] | str # Error -46 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, "foo", True]` @@ -267,10 +237,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -47 | # Should emit for unions with mixed literal internal types - - field15: Literal[1] | Literal["foo"] | Literal[True] # Error +48 - field15: Literal[1] | Literal["foo"] | Literal[True] # Error 48 + field15: Literal[1, "foo", True] # Error -49 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 1]` @@ -284,10 +252,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -50 | # Shouldn't emit for duplicate field types with same value; covered by Y016 - - field16: Literal[1] | Literal[1] # OK +51 - field16: Literal[1] | Literal[1] # OK 51 + field16: Literal[1, 1] # OK -52 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -301,10 +267,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -59 | # Should respect name of literal type used - - field19: typing.Literal[1] | typing.Literal[2] # Error +60 - field19: typing.Literal[1] | typing.Literal[2] # Error 60 + field19: typing.Literal[1, 2] # Error -61 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -324,15 +288,13 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -62 | # Should emit in cases with newlines - - field20: typing.Union[ - - Literal[ - - 1 # test - - ], - - Literal[2], - - ] # Error, newline and comment will not be emitted in message +63 - field20: typing.Union[ +64 - Literal[ +65 - 1 # test +66 - ], +67 - Literal[2], +68 - ] # Error, newline and comment will not be emitted in message 63 + field20: Literal[1, 2] # Error, newline and comment will not be emitted in message -64 | | note: This is an unsafe fix and may change runtime behavior @@ -347,10 +309,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -70 | # Should handle multiple unions with multiple members - - field21: Literal[1, 2] | Literal[3, 4] # Error +71 - field21: Literal[1, 2] | Literal[3, 4] # Error 71 + field21: Literal[1, 2, 3, 4] # Error -72 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -364,10 +324,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -73 | # Should emit in cases with `typing.Union` instead of `|` - - field22: typing.Union[Literal[1], Literal[2]] # Error +74 - field22: typing.Union[Literal[1], Literal[2]] # Error 74 + field22: Literal[1, 2] # Error -75 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -381,10 +339,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -76 | # Should emit in cases with `typing_extensions.Literal` - - field23: typing_extensions.Literal[1] | typing_extensions.Literal[2] # Error +77 - field23: typing_extensions.Literal[1] | typing_extensions.Literal[2] # Error 77 + field23: typing_extensions.Literal[1, 2] # Error -78 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -398,10 +354,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -79 | # Should emit in cases with nested `typing.Union` - - field24: typing.Union[Literal[1], typing.Union[Literal[2], str]] # Error +80 - field24: typing.Union[Literal[1], typing.Union[Literal[2], str]] # Error 80 + field24: typing.Union[Literal[1, 2], str] # Error -81 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -415,10 +369,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -82 | # Should emit in cases with mixed `typing.Union` and `|` - - field25: typing.Union[Literal[1], Literal[2] | str] # Error +83 - field25: typing.Union[Literal[1], Literal[2] | str] # Error 83 + field25: typing.Union[Literal[1, 2], str] # Error -84 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2, 3, 4]` @@ -432,10 +384,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -85 | # Should emit only once in cases with multiple nested `typing.Union` - - field24: typing.Union[Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]]] # Error +86 - field24: typing.Union[Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]]] # Error 86 + field24: Literal[1, 2, 3, 4] # Error -87 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2, 3, 4]` @@ -449,10 +399,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -88 | # Should use the first literal subscript attribute when fixing - - field25: typing.Union[typing_extensions.Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]], str] # Error +89 - field25: typing.Union[typing_extensions.Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]], str] # Error 89 + field25: typing.Union[typing_extensions.Literal[1, 2, 3, 4], str] # Error -90 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal["a", "b"]` @@ -467,10 +415,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -92 | - - InlineOption = Literal["a"] | Literal["b"] | IO[str] +93 - InlineOption = Literal["a"] | Literal["b"] | IO[str] 93 + InlineOption = Literal["a", "b"] | IO[str] -94 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal["a", "b", "c", "d"]` @@ -486,14 +432,12 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite 102 | field27: ( | help: Replace with a single `Literal` - | -97 | # First comment - - Literal["a", "b"] - - # Second comment - - | Literal["c", "d"] -98 + Literal["a", "b", "c", "d"] -99 | ) - | + | + 98 - Literal["a", "b"] + 99 - # Second comment +100 - | Literal["c", "d"] + 98 + Literal["a", "b", "c", "d"] + | note: This is an unsafe fix and may change runtime behavior PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal["a", "b", "c", "d"]` @@ -508,10 +452,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -102 | field27: ( - - Literal["a", "b"] # First comment - - | Literal["c", "d"] # Second comment +103 - Literal["a", "b"] # First comment +104 - | Literal["c", "d"] # Second comment 103 + Literal["a", "b", "c", "d"] # Second comment -104 | ) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI030_PYI030.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI030_PYI030.pyi.snap index f809d8dbe0188..0b2d9ff5fd07a 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI030_PYI030.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI030_PYI030.pyi.snap @@ -11,12 +11,10 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite 11 | # Should emit for union types in arguments. | help: Replace with a single `Literal` - | -8 | # Should emit for duplicate field types. - - field2: Literal[1] | Literal[2] # Error -9 + field2: Literal[1, 2] # Error -10 | - | + | +9 - field2: Literal[1] | Literal[2] # Error +9 + field2: Literal[1, 2] # Error + | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` --> PYI030.pyi:12:17 @@ -28,10 +26,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -11 | # Should emit for union types in arguments. - - def func1(arg1: Literal[1] | Literal[2]): # Error +12 - def func1(arg1: Literal[1] | Literal[2]): # Error 12 + def func1(arg1: Literal[1, 2]): # Error -13 | print(arg1) | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -44,10 +40,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -16 | # Should emit for unions in return types. - - def func2() -> Literal[1] | Literal[2]: # Error +17 - def func2() -> Literal[1] | Literal[2]: # Error 17 + def func2() -> Literal[1, 2]: # Error -18 | return "my Literal[1]ing" | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -61,10 +55,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -21 | # Should emit in longer unions, even if not directly adjacent. - - field3: Literal[1] | Literal[2] | str # Error +22 - field3: Literal[1] | Literal[2] | str # Error 22 + field3: Literal[1, 2] | str # Error -23 | field4: str | Literal[1] | Literal[2] # Error | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -79,10 +71,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -22 | field3: Literal[1] | Literal[2] | str # Error - - field4: str | Literal[1] | Literal[2] # Error +23 - field4: str | Literal[1] | Literal[2] # Error 23 + field4: Literal[1, 2] | str # Error -24 | field5: Literal[1] | str | Literal[2] # Error | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -96,10 +86,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -23 | field4: str | Literal[1] | Literal[2] # Error - - field5: Literal[1] | str | Literal[2] # Error +24 - field5: Literal[1] | str | Literal[2] # Error 24 + field5: Literal[1, 2] | str # Error -25 | field6: Literal[1] | bool | Literal[2] | str # Error | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -114,10 +102,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -24 | field5: Literal[1] | str | Literal[2] # Error - - field6: Literal[1] | bool | Literal[2] | str # Error +25 - field6: Literal[1] | bool | Literal[2] | str # Error 25 + field6: Literal[1, 2] | bool | str # Error -26 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -131,10 +117,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -27 | # Should emit for non-type unions. - - field7 = Literal[1] | Literal[2] # Error +28 - field7 = Literal[1] | Literal[2] # Error 28 + field7 = Literal[1, 2] # Error -29 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -148,10 +132,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -30 | # Should emit for parenthesized unions. - - field8: Literal[1] | (Literal[2] | str) # Error +31 - field8: Literal[1] | (Literal[2] | str) # Error 31 + field8: Literal[1, 2] | str # Error -32 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -164,10 +146,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -33 | # Should handle user parentheses when fixing. - - field9: Literal[1] | (Literal[2] | str) # Error +34 - field9: Literal[1] | (Literal[2] | str) # Error 34 + field9: Literal[1, 2] | str # Error -35 | field10: (Literal[1] | str) | Literal[2] # Error | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -182,10 +162,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -34 | field9: Literal[1] | (Literal[2] | str) # Error - - field10: (Literal[1] | str) | Literal[2] # Error +35 - field10: (Literal[1] | str) | Literal[2] # Error 35 + field10: Literal[1, 2] | str # Error -36 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -199,10 +177,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -37 | # Should emit for union in generic parent type. - - field11: dict[Literal[1] | Literal[2], str] # Error +38 - field11: dict[Literal[1] | Literal[2], str] # Error 38 + field11: dict[Literal[1, 2], str] # Error -39 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2, 3]` @@ -215,10 +191,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -40 | # Should emit for unions with more than two cases - - field12: Literal[1] | Literal[2] | Literal[3] # Error +41 - field12: Literal[1] | Literal[2] | Literal[3] # Error 41 + field12: Literal[1, 2, 3] # Error -42 | field13: Literal[1] | Literal[2] | Literal[3] | Literal[4] # Error | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2, 3, 4]` @@ -233,10 +207,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -41 | field12: Literal[1] | Literal[2] | Literal[3] # Error - - field13: Literal[1] | Literal[2] | Literal[3] | Literal[4] # Error +42 - field13: Literal[1] | Literal[2] | Literal[3] | Literal[4] # Error 42 + field13: Literal[1, 2, 3, 4] # Error -43 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2, 3]` @@ -250,10 +222,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -44 | # Should emit for unions with more than two cases, even if not directly adjacent - - field14: Literal[1] | Literal[2] | str | Literal[3] # Error +45 - field14: Literal[1] | Literal[2] | str | Literal[3] # Error 45 + field14: Literal[1, 2, 3] | str # Error -46 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, "foo", True]` @@ -267,10 +237,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -47 | # Should emit for unions with mixed literal internal types - - field15: Literal[1] | Literal["foo"] | Literal[True] # Error +48 - field15: Literal[1] | Literal["foo"] | Literal[True] # Error 48 + field15: Literal[1, "foo", True] # Error -49 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 1]` @@ -284,10 +252,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -50 | # Shouldn't emit for duplicate field types with same value; covered by Y016 - - field16: Literal[1] | Literal[1] # OK +51 - field16: Literal[1] | Literal[1] # OK 51 + field16: Literal[1, 1] # OK -52 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -301,10 +267,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -59 | # Should respect name of literal type used - - field19: typing.Literal[1] | typing.Literal[2] # Error +60 - field19: typing.Literal[1] | typing.Literal[2] # Error 60 + field19: typing.Literal[1, 2] # Error -61 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -324,15 +288,13 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -62 | # Should emit in cases with newlines - - field20: typing.Union[ - - Literal[ - - 1 # test - - ], - - Literal[2], - - ] # Error, newline and comment will not be emitted in message +63 - field20: typing.Union[ +64 - Literal[ +65 - 1 # test +66 - ], +67 - Literal[2], +68 - ] # Error, newline and comment will not be emitted in message 63 + field20: Literal[1, 2] # Error, newline and comment will not be emitted in message -64 | | note: This is an unsafe fix and may change runtime behavior @@ -347,10 +309,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -70 | # Should handle multiple unions with multiple members - - field21: Literal[1, 2] | Literal[3, 4] # Error +71 - field21: Literal[1, 2] | Literal[3, 4] # Error 71 + field21: Literal[1, 2, 3, 4] # Error -72 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -364,10 +324,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -73 | # Should emit in cases with `typing.Union` instead of `|` - - field22: typing.Union[Literal[1], Literal[2]] # Error +74 - field22: typing.Union[Literal[1], Literal[2]] # Error 74 + field22: Literal[1, 2] # Error -75 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -381,10 +339,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -76 | # Should emit in cases with `typing_extensions.Literal` - - field23: typing_extensions.Literal[1] | typing_extensions.Literal[2] # Error +77 - field23: typing_extensions.Literal[1] | typing_extensions.Literal[2] # Error 77 + field23: typing_extensions.Literal[1, 2] # Error -78 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -398,10 +354,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -79 | # Should emit in cases with nested `typing.Union` - - field24: typing.Union[Literal[1], typing.Union[Literal[2], str]] # Error +80 - field24: typing.Union[Literal[1], typing.Union[Literal[2], str]] # Error 80 + field24: typing.Union[Literal[1, 2], str] # Error -81 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2]` @@ -415,10 +369,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -82 | # Should emit in cases with mixed `typing.Union` and `|` - - field25: typing.Union[Literal[1], Literal[2] | str] # Error +83 - field25: typing.Union[Literal[1], Literal[2] | str] # Error 83 + field25: typing.Union[Literal[1, 2], str] # Error -84 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2, 3, 4]` @@ -432,10 +384,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -85 | # Should emit only once in cases with multiple nested `typing.Union` - - field24: typing.Union[Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]]] # Error +86 - field24: typing.Union[Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]]] # Error 86 + field24: Literal[1, 2, 3, 4] # Error -87 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal[1, 2, 3, 4]` @@ -449,10 +399,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -88 | # Should use the first literal subscript attribute when fixing - - field25: typing.Union[typing_extensions.Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]], str] # Error +89 - field25: typing.Union[typing_extensions.Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]], str] # Error 89 + field25: typing.Union[typing_extensions.Literal[1, 2, 3, 4], str] # Error -90 | | PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Literal["a", "b", "c", "d"]` @@ -469,12 +417,10 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -93 | # First comment - - Literal["a", "b"] - - # Second comment - - | Literal["c", "d"] +94 - Literal["a", "b"] +95 - # Second comment +96 - | Literal["c", "d"] 94 + Literal["a", "b", "c", "d"] -95 | ) | note: This is an unsafe fix and may change runtime behavior @@ -490,10 +436,8 @@ PYI030 [*] Multiple literal members in a union. Use a single literal, e.g. `Lite | help: Replace with a single `Literal` | -98 | field27: ( - - Literal["a", "b"] # First comment - - | Literal["c", "d"] # Second comment -99 + Literal["a", "b", "c", "d"] # Second comment -100 | ) + 99 - Literal["a", "b"] # First comment +100 - | Literal["c", "d"] # Second comment + 99 + Literal["a", "b", "c", "d"] # Second comment | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI032_PYI032.py.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI032_PYI032.py.snap index a1234728cdb53..9a92f53fd3e35 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI032_PYI032.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI032_PYI032.py.snap @@ -11,10 +11,8 @@ PYI032 [*] Prefer `object` to `Any` for the second parameter to `__eq__` | help: Replace with `object` | -5 | class Bad: - - def __eq__(self, other: Any) -> bool: ... # PYI032 +6 - def __eq__(self, other: Any) -> bool: ... # PYI032 6 + def __eq__(self, other: object) -> bool: ... # PYI032 -7 | def __ne__(self, other: typing.Any) -> typing.Any: ... # PYI032 | PYI032 [*] Prefer `object` to `Any` for the second parameter to `__ne__` @@ -26,10 +24,8 @@ PYI032 [*] Prefer `object` to `Any` for the second parameter to `__ne__` | ^^^^^^^^^^ help: Replace with `object` | -6 | def __eq__(self, other: Any) -> bool: ... # PYI032 - - def __ne__(self, other: typing.Any) -> typing.Any: ... # PYI032 +7 - def __ne__(self, other: typing.Any) -> typing.Any: ... # PYI032 7 + def __ne__(self, other: object) -> typing.Any: ... # PYI032 -8 | | PYI032 [*] Prefer `object` to `Any` for the second parameter to `__eq__` @@ -42,10 +38,8 @@ PYI032 [*] Prefer `object` to `Any` for the second parameter to `__eq__` | help: Replace with `object` | -26 | class BadStringized: - - def __eq__(self, other: "Any") -> bool: ... # PYI032 +27 - def __eq__(self, other: "Any") -> bool: ... # PYI032 27 + def __eq__(self, other: object) -> bool: ... # PYI032 -28 | def __ne__(self, other: "Any") -> bool: ... # PYI032 | PYI032 [*] Prefer `object` to `Any` for the second parameter to `__ne__` @@ -57,7 +51,6 @@ PYI032 [*] Prefer `object` to `Any` for the second parameter to `__ne__` | ^^^^^ help: Replace with `object` | -27 | def __eq__(self, other: "Any") -> bool: ... # PYI032 - - def __ne__(self, other: "Any") -> bool: ... # PYI032 +28 - def __ne__(self, other: "Any") -> bool: ... # PYI032 28 + def __ne__(self, other: object) -> bool: ... # PYI032 | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI032_PYI032.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI032_PYI032.pyi.snap index bd1e6cc98ceed..1c83b579d9952 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI032_PYI032.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI032_PYI032.pyi.snap @@ -11,10 +11,8 @@ PYI032 [*] Prefer `object` to `Any` for the second parameter to `__eq__` | help: Replace with `object` | -5 | class Bad: - - def __eq__(self, other: Any) -> bool: ... # PYI032 +6 - def __eq__(self, other: Any) -> bool: ... # PYI032 6 + def __eq__(self, other: object) -> bool: ... # PYI032 -7 | def __ne__(self, other: typing.Any) -> typing.Any: ... # PYI032 | PYI032 [*] Prefer `object` to `Any` for the second parameter to `__ne__` @@ -26,10 +24,8 @@ PYI032 [*] Prefer `object` to `Any` for the second parameter to `__ne__` | ^^^^^^^^^^ help: Replace with `object` | -6 | def __eq__(self, other: Any) -> bool: ... # PYI032 - - def __ne__(self, other: typing.Any) -> typing.Any: ... # PYI032 +7 - def __ne__(self, other: typing.Any) -> typing.Any: ... # PYI032 7 + def __ne__(self, other: object) -> typing.Any: ... # PYI032 -8 | | PYI032 [*] Prefer `object` to `Any` for the second parameter to `__eq__` @@ -42,10 +38,8 @@ PYI032 [*] Prefer `object` to `Any` for the second parameter to `__eq__` | help: Replace with `object` | -25 | class BadStringized: - - def __eq__(self, other: "Any") -> bool: ... # PYI032 +26 - def __eq__(self, other: "Any") -> bool: ... # PYI032 26 + def __eq__(self, other: object) -> bool: ... # PYI032 -27 | def __ne__(self, other: "Any") -> bool: ... # PYI032 | PYI032 [*] Prefer `object` to `Any` for the second parameter to `__ne__` @@ -57,7 +51,6 @@ PYI032 [*] Prefer `object` to `Any` for the second parameter to `__ne__` | ^^^^^ help: Replace with `object` | -26 | def __eq__(self, other: "Any") -> bool: ... # PYI032 - - def __ne__(self, other: "Any") -> bool: ... # PYI032 +27 - def __ne__(self, other: "Any") -> bool: ... # PYI032 27 + def __ne__(self, other: object) -> bool: ... # PYI032 | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI034_PYI034.py.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI034_PYI034.py.snap index e812b69d2d7c7..a1bd3ebb10e2a 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI034_PYI034.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI034_PYI034.py.snap @@ -12,10 +12,11 @@ PYI034 [*] `__new__` methods in classes like `Bad` usually return `self` at runt | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 20 | ): # Y040 Do not inherit from "object" explicitly, as it is redundant in Python 3 - - def __new__(cls, *args: Any, **kwargs: Any) -> Bad: -21 + def __new__(cls, *args: Any, **kwargs: Any) -> typing.Self: -22 | ... # Y034 "__new__" methods usually return "self" at runtime. Consider using "typing_extensions.Self" in "Bad.__new__", e.g. "def __new__(cls, *args: Any, **kwargs: Any) -> Self: ..." +21 ~ def __new__(cls, *args: Any, **kwargs: Any) -> typing.Self: | note: This is an unsafe fix and may change runtime behavior @@ -30,10 +31,11 @@ PYI034 [*] `__enter__` methods in classes like `Bad` usually return `self` at ru | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 35 | - - def __enter__(self) -> Bad: -36 + def __enter__(self) -> typing.Self: -37 | ... # Y034 "__enter__" methods in classes like "Bad" usually return "self" at runtime. Consider using "typing_extensions.Self" in "Bad.__enter__", e.g. "def __enter__(self) -> Self: ..." +36 ~ def __enter__(self) -> typing.Self: | note: This is an unsafe fix and may change runtime behavior @@ -48,10 +50,11 @@ PYI034 [*] `__aenter__` methods in classes like `Bad` usually return `self` at r | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 38 | - - async def __aenter__(self) -> Bad: -39 + async def __aenter__(self) -> typing.Self: -40 | ... # Y034 "__aenter__" methods in classes like "Bad" usually return "self" at runtime. Consider using "typing_extensions.Self" in "Bad.__aenter__", e.g. "async def __aenter__(self) -> Self: ..." +39 ~ async def __aenter__(self) -> typing.Self: | note: This is an unsafe fix and may change runtime behavior @@ -66,10 +69,11 @@ PYI034 [*] `__iadd__` methods in classes like `Bad` usually return `self` at run | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 41 | - - def __iadd__(self, other: Bad) -> Bad: -42 + def __iadd__(self, other: Bad) -> typing.Self: -43 | ... # Y034 "__iadd__" methods in classes like "Bad" usually return "self" at runtime. Consider using "typing_extensions.Self" in "Bad.__iadd__", e.g. "def __iadd__(self, other: Bad) -> Self: ..." +42 ~ def __iadd__(self, other: Bad) -> typing.Self: | note: This is an unsafe fix and may change runtime behavior @@ -83,10 +87,11 @@ PYI034 [*] `__iter__` methods in classes like `BadIterator1` usually return `sel | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 164 | class BadIterator1(Iterator[int]): - - def __iter__(self) -> Iterator[int]: -165 + def __iter__(self) -> typing.Self: -166 | ... # Y034 "__iter__" methods in classes like "BadIterator1" usually return "self" at runtime. Consider using "typing_extensions.Self" in "BadIterator1.__iter__", e.g. "def __iter__(self) -> Self: ..." +165 ~ def __iter__(self) -> typing.Self: | note: This is an unsafe fix and may change runtime behavior @@ -101,10 +106,11 @@ PYI034 [*] `__iter__` methods in classes like `BadIterator2` usually return `sel | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 171 | ): # Y022 Use "collections.abc.Iterator[T]" instead of "typing.Iterator[T]" (PEP 585 syntax) - - def __iter__(self) -> Iterator[int]: -172 + def __iter__(self) -> typing.Self: -173 | ... # Y034 "__iter__" methods in classes like "BadIterator2" usually return "self" at runtime. Consider using "typing_extensions.Self" in "BadIterator2.__iter__", e.g. "def __iter__(self) -> Self: ..." +172 ~ def __iter__(self) -> typing.Self: | note: This is an unsafe fix and may change runtime behavior @@ -119,10 +125,11 @@ PYI034 [*] `__iter__` methods in classes like `BadIterator3` usually return `sel | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 178 | ): # Y022 Use "collections.abc.Iterator[T]" instead of "typing.Iterator[T]" (PEP 585 syntax) - - def __iter__(self) -> collections.abc.Iterator[int]: -179 + def __iter__(self) -> typing.Self: -180 | ... # Y034 "__iter__" methods in classes like "BadIterator3" usually return "self" at runtime. Consider using "typing_extensions.Self" in "BadIterator3.__iter__", e.g. "def __iter__(self) -> Self: ..." +179 ~ def __iter__(self) -> typing.Self: | note: This is an unsafe fix and may change runtime behavior @@ -137,10 +144,11 @@ PYI034 [*] `__iter__` methods in classes like `BadIterator4` usually return `sel | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 184 | # Note: *Iterable*, not *Iterator*, returned! - - def __iter__(self) -> Iterable[int]: -185 + def __iter__(self) -> typing.Self: -186 | ... # Y034 "__iter__" methods in classes like "BadIterator4" usually return "self" at runtime. Consider using "typing_extensions.Self" in "BadIterator4.__iter__", e.g. "def __iter__(self) -> Self: ..." +185 ~ def __iter__(self) -> typing.Self: | note: This is an unsafe fix and may change runtime behavior @@ -154,10 +162,11 @@ PYI034 [*] `__aiter__` methods in classes like `BadAsyncIterator` usually return | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 194 | class BadAsyncIterator(collections.abc.AsyncIterator[str]): - - def __aiter__(self) -> typing.AsyncIterator[str]: -195 + def __aiter__(self) -> typing.Self: -196 | ... # Y034 "__aiter__" methods in classes like "BadAsyncIterator" usually return "self" at runtime. Consider using "typing_extensions.Self" in "BadAsyncIterator.__aiter__", e.g. "def __aiter__(self) -> Self: ..." # Y022 Use "collections.abc.AsyncIterator[T]" instead of "typing.AsyncIterator[T]" (PEP 585 syntax) +195 ~ def __aiter__(self) -> typing.Self: | note: This is an unsafe fix and may change runtime behavior @@ -171,10 +180,11 @@ PYI034 [*] `__iter__` methods in classes like `SubclassOfBadIterator3` usually r | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 198 | class SubclassOfBadIterator3(BadIterator3): - - def __iter__(self) -> Iterator[int]: # Y034 -199 + def __iter__(self) -> typing.Self: # Y034 -200 | ... +199 ~ def __iter__(self) -> typing.Self: # Y034 | note: This is an unsafe fix and may change runtime behavior @@ -188,10 +198,11 @@ PYI034 [*] `__aiter__` methods in classes like `SubclassOfBadAsyncIterator` usua | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 202 | class SubclassOfBadAsyncIterator(BadAsyncIterator): - - def __aiter__(self) -> collections.abc.AsyncIterator[str]: # Y034 -203 + def __aiter__(self) -> typing.Self: # Y034 -204 | ... +203 ~ def __aiter__(self) -> typing.Self: # Y034 | note: This is an unsafe fix and may change runtime behavior @@ -205,10 +216,11 @@ PYI034 [*] `__new__` methods in classes like `NonGeneric1` usually return `self` | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 326 | class NonGeneric1(tuple): - - def __new__(cls: type[NonGeneric1], *args, **kwargs) -> NonGeneric1: ... -327 + def __new__(cls, *args, **kwargs) -> typing.Self: ... -328 | def __enter__(self: NonGeneric1) -> NonGeneric1: ... +327 ~ def __new__(cls, *args, **kwargs) -> typing.Self: ... | note: This is an unsafe fix and may change runtime behavior @@ -224,10 +236,11 @@ PYI034 [*] `__enter__` methods in classes like `NonGeneric1` usually return `sel | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 327 | def __new__(cls: type[NonGeneric1], *args, **kwargs) -> NonGeneric1: ... - - def __enter__(self: NonGeneric1) -> NonGeneric1: ... -328 + def __enter__(self) -> typing.Self: ... -329 | +328 ~ def __enter__(self) -> typing.Self: ... | note: This is an unsafe fix and may change runtime behavior @@ -242,10 +255,11 @@ PYI034 [*] `__new__` methods in classes like `NonGeneric2` usually return `self` | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 330 | class NonGeneric2(tuple): - - def __new__(cls: Type[NonGeneric2]) -> NonGeneric2: ... -331 + def __new__(cls) -> typing.Self: ... -332 | +331 ~ def __new__(cls) -> typing.Self: ... | note: This is an unsafe fix and may change runtime behavior @@ -259,10 +273,11 @@ PYI034 [*] `__new__` methods in classes like `Generic1` usually return `self` at | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 333 | class Generic1[T](list): - - def __new__(cls: type[Generic1]) -> Generic1: ... -334 + def __new__(cls) -> typing.Self: ... -335 | def __enter__(self: Generic1) -> Generic1: ... +334 ~ def __new__(cls) -> typing.Self: ... | note: This is a display-only fix and is likely to be incorrect @@ -275,10 +290,11 @@ PYI034 [*] `__enter__` methods in classes like `Generic1` usually return `self` | ^^^^^^^^^ help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 334 | def __new__(cls: type[Generic1]) -> Generic1: ... - - def __enter__(self: Generic1) -> Generic1: ... -335 + def __enter__(self) -> typing.Self: ... -336 | +335 ~ def __enter__(self) -> typing.Self: ... | note: This is a display-only fix and is likely to be incorrect @@ -292,10 +308,11 @@ PYI034 [*] `__new__` methods in classes like `Generic2` usually return `self` at | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 344 | class Generic2(Generic[T]): - - def __new__(cls: type[Generic2]) -> Generic2: ... -345 + def __new__(cls) -> typing.Self: ... -346 | def __enter__(self: Generic2) -> Generic2: ... +345 ~ def __new__(cls) -> typing.Self: ... | note: This is a display-only fix and is likely to be incorrect @@ -311,10 +328,11 @@ PYI034 [*] `__enter__` methods in classes like `Generic2` usually return `self` | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 345 | def __new__(cls: type[Generic2]) -> Generic2: ... - - def __enter__(self: Generic2) -> Generic2: ... -346 + def __enter__(self) -> typing.Self: ... -347 | +346 ~ def __enter__(self) -> typing.Self: ... | note: This is a display-only fix and is likely to be incorrect @@ -328,10 +346,11 @@ PYI034 [*] `__new__` methods in classes like `Generic3` usually return `self` at | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 348 | class Generic3(tuple[*Ts]): - - def __new__(cls: type[Generic3]) -> Generic3: ... -349 + def __new__(cls) -> typing.Self: ... -350 | def __enter__(self: Generic3) -> Generic3: ... +349 ~ def __new__(cls) -> typing.Self: ... | note: This is a display-only fix and is likely to be incorrect @@ -347,10 +366,11 @@ PYI034 [*] `__enter__` methods in classes like `Generic3` usually return `self` | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 349 | def __new__(cls: type[Generic3]) -> Generic3: ... - - def __enter__(self: Generic3) -> Generic3: ... -350 + def __enter__(self) -> typing.Self: ... -351 | +350 ~ def __enter__(self) -> typing.Self: ... | note: This is a display-only fix and is likely to be incorrect @@ -364,10 +384,11 @@ PYI034 [*] `__new__` methods in classes like `Generic4` usually return `self` at | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 352 | class Generic4(collections.abc.Callable[P, ...]): - - def __new__(cls: type[Generic4]) -> Generic4: ... -353 + def __new__(cls) -> typing.Self: ... -354 | def __enter__(self: Generic4) -> Generic4: ... +353 ~ def __new__(cls) -> typing.Self: ... | note: This is a display-only fix and is likely to be incorrect @@ -383,10 +404,11 @@ PYI034 [*] `__enter__` methods in classes like `Generic4` usually return `self` | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 353 | def __new__(cls: type[Generic4]) -> Generic4: ... - - def __enter__(self: Generic4) -> Generic4: ... -354 + def __enter__(self) -> typing.Self: ... -355 | +354 ~ def __enter__(self) -> typing.Self: ... | note: This is a display-only fix and is likely to be incorrect @@ -400,10 +422,11 @@ PYI034 [*] `__new__` methods in classes like `Generic5` usually return `self` at | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 358 | class Generic5(list[PotentialTypeVar]): - - def __new__(cls: type[Generic5]) -> Generic5: ... -359 + def __new__(cls) -> typing.Self: ... -360 | def __enter__(self: Generic5) -> Generic5: ... +359 ~ def __new__(cls) -> typing.Self: ... | note: This is an unsafe fix and may change runtime behavior @@ -416,10 +439,11 @@ PYI034 [*] `__enter__` methods in classes like `Generic5` usually return `self` | ^^^^^^^^^ help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 359 | def __new__(cls: type[Generic5]) -> Generic5: ... - - def __enter__(self: Generic5) -> Generic5: ... -360 + def __enter__(self) -> typing.Self: ... -361 | +360 ~ def __enter__(self) -> typing.Self: ... | note: This is an unsafe fix and may change runtime behavior @@ -434,10 +458,11 @@ PYI034 [*] `__new__` methods in classes like `UsesStringizedForwardReferences` u | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 390 | class UsesStringizedForwardReferences: - - def __new__(cls) -> "UsesStringizedForwardReferences": ... # PYI034 -391 + def __new__(cls) -> typing.Self: ... # PYI034 -392 | def __enter__(self) -> "UsesStringizedForwardReferences": ... # PYI034 +391 ~ def __new__(cls) -> typing.Self: ... # PYI034 | note: This is an unsafe fix and may change runtime behavior @@ -453,10 +478,11 @@ PYI034 [*] `__enter__` methods in classes like `UsesStringizedForwardReferences` | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 391 | def __new__(cls) -> "UsesStringizedForwardReferences": ... # PYI034 - - def __enter__(self) -> "UsesStringizedForwardReferences": ... # PYI034 -392 + def __enter__(self) -> typing.Self: ... # PYI034 -393 | async def __aenter__(self) -> "UsesStringizedForwardReferences": ... # PYI034 +392 ~ def __enter__(self) -> typing.Self: ... # PYI034 | note: This is an unsafe fix and may change runtime behavior @@ -471,10 +497,11 @@ PYI034 [*] `__aenter__` methods in classes like `UsesStringizedForwardReferences | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 392 | def __enter__(self) -> "UsesStringizedForwardReferences": ... # PYI034 - - async def __aenter__(self) -> "UsesStringizedForwardReferences": ... # PYI034 -393 + async def __aenter__(self) -> typing.Self: ... # PYI034 -394 | def __iadd__(self, other) -> "UsesStringizedForwardReferences": ... # PYI034 +393 ~ async def __aenter__(self) -> typing.Self: ... # PYI034 | note: This is an unsafe fix and may change runtime behavior @@ -487,9 +514,10 @@ PYI034 [*] `__iadd__` methods in classes like `UsesStringizedForwardReferences` | ^^^^^^^^ help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 393 | async def __aenter__(self) -> "UsesStringizedForwardReferences": ... # PYI034 - - def __iadd__(self, other) -> "UsesStringizedForwardReferences": ... # PYI034 -394 + def __iadd__(self, other) -> typing.Self: ... # PYI034 -395 | +394 ~ def __iadd__(self, other) -> typing.Self: ... # PYI034 | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI034_PYI034.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI034_PYI034.pyi.snap index bec2f0f25d680..241f49df46fd0 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI034_PYI034.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI034_PYI034.pyi.snap @@ -13,10 +13,11 @@ PYI034 [*] `__new__` methods in classes like `Bad` usually return `self` at runt | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 21 | cls, *args: Any, **kwargs: Any - - ) -> Bad: ... # Y034 "__new__" methods usually return "self" at runtime. Consider using "typing_extensions.Self" in "Bad.__new__", e.g. "def __new__(cls, *args: Any, **kwargs: Any) -> Self: ..." -22 + ) -> typing.Self: ... # Y034 "__new__" methods usually return "self" at runtime. Consider using "typing_extensions.Self" in "Bad.__new__", e.g. "def __new__(cls, *args: Any, **kwargs: Any) -> Self: ..." -23 | def __repr__( +22 ~ ) -> typing.Self: ... # Y034 "__new__" methods usually return "self" at runtime. Consider using "typing_extensions.Self" in "Bad.__new__", e.g. "def __new__(cls, *args: Any, **kwargs: Any) -> Self: ..." | note: This is an unsafe fix and may change runtime behavior @@ -32,10 +33,11 @@ PYI034 [*] `__enter__` methods in classes like `Bad` usually return `self` at ru | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 36 | self, - - ) -> Bad: ... # Y034 "__enter__" methods in classes like "Bad" usually return "self" at runtime. Consider using "typing_extensions.Self" in "Bad.__enter__", e.g. "def __enter__(self) -> Self: ..." -37 + ) -> typing.Self: ... # Y034 "__enter__" methods in classes like "Bad" usually return "self" at runtime. Consider using "typing_extensions.Self" in "Bad.__enter__", e.g. "def __enter__(self) -> Self: ..." -38 | async def __aenter__( +37 ~ ) -> typing.Self: ... # Y034 "__enter__" methods in classes like "Bad" usually return "self" at runtime. Consider using "typing_extensions.Self" in "Bad.__enter__", e.g. "def __enter__(self) -> Self: ..." | note: This is an unsafe fix and may change runtime behavior @@ -51,10 +53,11 @@ PYI034 [*] `__aenter__` methods in classes like `Bad` usually return `self` at r | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 39 | self, - - ) -> Bad: ... # Y034 "__aenter__" methods in classes like "Bad" usually return "self" at runtime. Consider using "typing_extensions.Self" in "Bad.__aenter__", e.g. "async def __aenter__(self) -> Self: ..." -40 + ) -> typing.Self: ... # Y034 "__aenter__" methods in classes like "Bad" usually return "self" at runtime. Consider using "typing_extensions.Self" in "Bad.__aenter__", e.g. "async def __aenter__(self) -> Self: ..." -41 | def __iadd__( +40 ~ ) -> typing.Self: ... # Y034 "__aenter__" methods in classes like "Bad" usually return "self" at runtime. Consider using "typing_extensions.Self" in "Bad.__aenter__", e.g. "async def __aenter__(self) -> Self: ..." | note: This is an unsafe fix and may change runtime behavior @@ -70,10 +73,11 @@ PYI034 [*] `__iadd__` methods in classes like `Bad` usually return `self` at run | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 42 | self, other: Bad - - ) -> Bad: ... # Y034 "__iadd__" methods in classes like "Bad" usually return "self" at runtime. Consider using "typing_extensions.Self" in "Bad.__iadd__", e.g. "def __iadd__(self, other: Bad) -> Self: ..." -43 + ) -> typing.Self: ... # Y034 "__iadd__" methods in classes like "Bad" usually return "self" at runtime. Consider using "typing_extensions.Self" in "Bad.__iadd__", e.g. "def __iadd__(self, other: Bad) -> Self: ..." -44 | +43 ~ ) -> typing.Self: ... # Y034 "__iadd__" methods in classes like "Bad" usually return "self" at runtime. Consider using "typing_extensions.Self" in "Bad.__iadd__", e.g. "def __iadd__(self, other: Bad) -> Self: ..." | note: This is an unsafe fix and may change runtime behavior @@ -88,12 +92,11 @@ PYI034 [*] `__iter__` methods in classes like `BadIterator1` usually return `sel | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 105 | self, - - ) -> Iterator[ - - int - - ]: ... # Y034 "__iter__" methods in classes like "BadIterator1" usually return "self" at runtime. Consider using "typing_extensions.Self" in "BadIterator1.__iter__", e.g. "def __iter__(self) -> Self: ..." -106 + ) -> typing.Self: ... # Y034 "__iter__" methods in classes like "BadIterator1" usually return "self" at runtime. Consider using "typing_extensions.Self" in "BadIterator1.__iter__", e.g. "def __iter__(self) -> Self: ..." -107 | +106 ~ ) -> typing.Self: ... # Y034 "__iter__" methods in classes like "BadIterator1" usually return "self" at runtime. Consider using "typing_extensions.Self" in "BadIterator1.__iter__", e.g. "def __iter__(self) -> Self: ..." | note: This is an unsafe fix and may change runtime behavior @@ -109,12 +112,11 @@ PYI034 [*] `__iter__` methods in classes like `BadIterator2` usually return `sel | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 114 | self, - - ) -> Iterator[ - - int - - ]: ... # Y034 "__iter__" methods in classes like "BadIterator2" usually return "self" at runtime. Consider using "typing_extensions.Self" in "BadIterator2.__iter__", e.g. "def __iter__(self) -> Self: ..." -115 + ) -> typing.Self: ... # Y034 "__iter__" methods in classes like "BadIterator2" usually return "self" at runtime. Consider using "typing_extensions.Self" in "BadIterator2.__iter__", e.g. "def __iter__(self) -> Self: ..." -116 | +115 ~ ) -> typing.Self: ... # Y034 "__iter__" methods in classes like "BadIterator2" usually return "self" at runtime. Consider using "typing_extensions.Self" in "BadIterator2.__iter__", e.g. "def __iter__(self) -> Self: ..." | note: This is an unsafe fix and may change runtime behavior @@ -130,12 +132,11 @@ PYI034 [*] `__iter__` methods in classes like `BadIterator3` usually return `sel | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 123 | self, - - ) -> collections.abc.Iterator[ - - int - - ]: ... # Y034 "__iter__" methods in classes like "BadIterator3" usually return "self" at runtime. Consider using "typing_extensions.Self" in "BadIterator3.__iter__", e.g. "def __iter__(self) -> Self: ..." -124 + ) -> typing.Self: ... # Y034 "__iter__" methods in classes like "BadIterator3" usually return "self" at runtime. Consider using "typing_extensions.Self" in "BadIterator3.__iter__", e.g. "def __iter__(self) -> Self: ..." -125 | +124 ~ ) -> typing.Self: ... # Y034 "__iter__" methods in classes like "BadIterator3" usually return "self" at runtime. Consider using "typing_extensions.Self" in "BadIterator3.__iter__", e.g. "def __iter__(self) -> Self: ..." | note: This is an unsafe fix and may change runtime behavior @@ -151,12 +152,11 @@ PYI034 [*] `__iter__` methods in classes like `BadIterator4` usually return `sel | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 131 | self, - - ) -> Iterable[ - - int - - ]: ... # Y034 "__iter__" methods in classes like "BadIterator4" usually return "self" at runtime. Consider using "typing_extensions.Self" in "BadIterator4.__iter__", e.g. "def __iter__(self) -> Self: ..." -132 + ) -> typing.Self: ... # Y034 "__iter__" methods in classes like "BadIterator4" usually return "self" at runtime. Consider using "typing_extensions.Self" in "BadIterator4.__iter__", e.g. "def __iter__(self) -> Self: ..." -133 | +132 ~ ) -> typing.Self: ... # Y034 "__iter__" methods in classes like "BadIterator4" usually return "self" at runtime. Consider using "typing_extensions.Self" in "BadIterator4.__iter__", e.g. "def __iter__(self) -> Self: ..." | note: This is an unsafe fix and may change runtime behavior @@ -171,12 +171,11 @@ PYI034 [*] `__aiter__` methods in classes like `BadAsyncIterator` usually return | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 145 | self, - - ) -> typing.AsyncIterator[ - - str - - ]: ... # Y034 "__aiter__" methods in classes like "BadAsyncIterator" usually return "self" at runtime. Consider using "typing_extensions.Self" in "BadAsyncIterator.__aiter__", e.g. "def __aiter__(self) -> Self: ..." # Y022 Use "collections.abc.AsyncIterator[T]" instead of "typing.AsyncIterator[T]" (PEP 585 syntax) -146 + ) -> typing.Self: ... # Y034 "__aiter__" methods in classes like "BadAsyncIterator" usually return "self" at runtime. Consider using "typing_extensions.Self" in "BadAsyncIterator.__aiter__", e.g. "def __aiter__(self) -> Self: ..." # Y022 Use "collections.abc.AsyncIterator[T]" instead of "typing.AsyncIterator[T]" (PEP 585 syntax) -147 | +146 ~ ) -> typing.Self: ... # Y034 "__aiter__" methods in classes like "BadAsyncIterator" usually return "self" at runtime. Consider using "typing_extensions.Self" in "BadAsyncIterator.__aiter__", e.g. "def __aiter__(self) -> Self: ..." # Y022 Use "collections.abc.AsyncIterator[T]" instead of "typing.AsyncIterator[T]" (PEP 585 syntax) | note: This is an unsafe fix and may change runtime behavior @@ -190,10 +189,11 @@ PYI034 [*] `__new__` methods in classes like `NonGeneric1` usually return `self` | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 220 | class NonGeneric1(tuple): - - def __new__(cls: type[NonGeneric1], *args, **kwargs) -> NonGeneric1: ... -221 + def __new__(cls, *args, **kwargs) -> typing.Self: ... -222 | def __enter__(self: NonGeneric1) -> NonGeneric1: ... +221 ~ def __new__(cls, *args, **kwargs) -> typing.Self: ... | note: This is an unsafe fix and may change runtime behavior @@ -209,10 +209,11 @@ PYI034 [*] `__enter__` methods in classes like `NonGeneric1` usually return `sel | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 221 | def __new__(cls: type[NonGeneric1], *args, **kwargs) -> NonGeneric1: ... - - def __enter__(self: NonGeneric1) -> NonGeneric1: ... -222 + def __enter__(self) -> typing.Self: ... -223 | +222 ~ def __enter__(self) -> typing.Self: ... | note: This is an unsafe fix and may change runtime behavior @@ -227,10 +228,11 @@ PYI034 [*] `__new__` methods in classes like `NonGeneric2` usually return `self` | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 224 | class NonGeneric2(tuple): - - def __new__(cls: Type[NonGeneric2]) -> NonGeneric2: ... -225 + def __new__(cls) -> typing.Self: ... -226 | +225 ~ def __new__(cls) -> typing.Self: ... | note: This is an unsafe fix and may change runtime behavior @@ -244,10 +246,11 @@ PYI034 [*] `__new__` methods in classes like `Generic1` usually return `self` at | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 227 | class Generic1[T](list): - - def __new__(cls: type[Generic1]) -> Generic1: ... -228 + def __new__(cls) -> typing.Self: ... -229 | def __enter__(self: Generic1) -> Generic1: ... +228 ~ def __new__(cls) -> typing.Self: ... | note: This is a display-only fix and is likely to be incorrect @@ -260,10 +263,11 @@ PYI034 [*] `__enter__` methods in classes like `Generic1` usually return `self` | ^^^^^^^^^ help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 228 | def __new__(cls: type[Generic1]) -> Generic1: ... - - def __enter__(self: Generic1) -> Generic1: ... -229 + def __enter__(self) -> typing.Self: ... -230 | +229 ~ def __enter__(self) -> typing.Self: ... | note: This is a display-only fix and is likely to be incorrect @@ -277,10 +281,11 @@ PYI034 [*] `__new__` methods in classes like `Generic2` usually return `self` at | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 238 | class Generic2(Generic[T]): - - def __new__(cls: type[Generic2]) -> Generic2: ... -239 + def __new__(cls) -> typing.Self: ... -240 | def __enter__(self: Generic2) -> Generic2: ... +239 ~ def __new__(cls) -> typing.Self: ... | note: This is a display-only fix and is likely to be incorrect @@ -296,10 +301,11 @@ PYI034 [*] `__enter__` methods in classes like `Generic2` usually return `self` | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 239 | def __new__(cls: type[Generic2]) -> Generic2: ... - - def __enter__(self: Generic2) -> Generic2: ... -240 + def __enter__(self) -> typing.Self: ... -241 | +240 ~ def __enter__(self) -> typing.Self: ... | note: This is a display-only fix and is likely to be incorrect @@ -313,10 +319,11 @@ PYI034 [*] `__new__` methods in classes like `Generic3` usually return `self` at | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 242 | class Generic3(tuple[*Ts]): - - def __new__(cls: type[Generic3]) -> Generic3: ... -243 + def __new__(cls) -> typing.Self: ... -244 | def __enter__(self: Generic3) -> Generic3: ... +243 ~ def __new__(cls) -> typing.Self: ... | note: This is a display-only fix and is likely to be incorrect @@ -332,10 +339,11 @@ PYI034 [*] `__enter__` methods in classes like `Generic3` usually return `self` | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 243 | def __new__(cls: type[Generic3]) -> Generic3: ... - - def __enter__(self: Generic3) -> Generic3: ... -244 + def __enter__(self) -> typing.Self: ... -245 | +244 ~ def __enter__(self) -> typing.Self: ... | note: This is a display-only fix and is likely to be incorrect @@ -349,10 +357,11 @@ PYI034 [*] `__new__` methods in classes like `Generic4` usually return `self` at | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 246 | class Generic4(collections.abc.Callable[P, ...]): - - def __new__(cls: type[Generic4]) -> Generic4: ... -247 + def __new__(cls) -> typing.Self: ... -248 | def __enter__(self: Generic4) -> Generic4: ... +247 ~ def __new__(cls) -> typing.Self: ... | note: This is a display-only fix and is likely to be incorrect @@ -368,10 +377,11 @@ PYI034 [*] `__enter__` methods in classes like `Generic4` usually return `self` | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 247 | def __new__(cls: type[Generic4]) -> Generic4: ... - - def __enter__(self: Generic4) -> Generic4: ... -248 + def __enter__(self) -> typing.Self: ... -249 | +248 ~ def __enter__(self) -> typing.Self: ... | note: This is a display-only fix and is likely to be incorrect @@ -385,10 +395,11 @@ PYI034 [*] `__new__` methods in classes like `Generic5` usually return `self` at | help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 252 | class Generic5(list[PotentialTypeVar]): - - def __new__(cls: type[Generic5]) -> Generic5: ... -253 + def __new__(cls) -> typing.Self: ... -254 | def __enter__(self: Generic5) -> Generic5: ... +253 ~ def __new__(cls) -> typing.Self: ... | note: This is a display-only fix and is likely to be incorrect @@ -401,9 +412,10 @@ PYI034 [*] `__enter__` methods in classes like `Generic5` usually return `self` | ^^^^^^^^^ help: Use `Self` as return type | + 7 ~ import typing + 8 | from abc import ABCMeta, abstractmethod + … 253 | def __new__(cls: type[Generic5]) -> Generic5: ... - - def __enter__(self: Generic5) -> Generic5: ... -254 + def __enter__(self) -> typing.Self: ... -255 | +254 ~ def __enter__(self) -> typing.Self: ... | note: This is a display-only fix and is likely to be incorrect diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI036_PYI036.py.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI036_PYI036.py.snap index 62df2f165b6d2..6421d9468827a 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI036_PYI036.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI036_PYI036.py.snap @@ -11,10 +11,8 @@ PYI036 [*] Star-args in `__exit__` should be annotated with `object` | help: Annotate star-args with `object` | -53 | class BadOne: - - def __exit__(self, *args: Any) -> None: ... # PYI036: Bad star-args annotation +54 - def __exit__(self, *args: Any) -> None: ... # PYI036: Bad star-args annotation 54 + def __exit__(self, *args: object) -> None: ... # PYI036: Bad star-args annotation -55 | async def __aexit__(self) -> None: ... # PYI036: Missing args | PYI036 If there are no star-args, `__aexit__` should have at least 3 non-keyword-only args (excluding `self`) @@ -118,10 +116,8 @@ PYI036 [*] Star-args in `__exit__` should be annotated with `object` | help: Annotate star-args with `object` | -69 | class BadFive: - - def __exit__(self, typ: BaseException | None, *args: list[str]) -> bool: ... # PYI036: Bad star-args annotation +70 - def __exit__(self, typ: BaseException | None, *args: list[str]) -> bool: ... # PYI036: Bad star-args annotation 70 + def __exit__(self, typ: BaseException | None, *args: object) -> bool: ... # PYI036: Bad star-args annotation -71 | async def __aexit__(self, /, typ: type[BaseException] | None, *args: Any) -> Awaitable[None]: ... # PYI036: Bad star-args annotation | PYI036 [*] Star-args in `__aexit__` should be annotated with `object` @@ -136,10 +132,8 @@ PYI036 [*] Star-args in `__aexit__` should be annotated with `object` | help: Annotate star-args with `object` | -70 | def __exit__(self, typ: BaseException | None, *args: list[str]) -> bool: ... # PYI036: Bad star-args annotation - - async def __aexit__(self, /, typ: type[BaseException] | None, *args: Any) -> Awaitable[None]: ... # PYI036: Bad star-args annotation +71 - async def __aexit__(self, /, typ: type[BaseException] | None, *args: Any) -> Awaitable[None]: ... # PYI036: Bad star-args annotation 71 + async def __aexit__(self, /, typ: type[BaseException] | None, *args: object) -> Awaitable[None]: ... # PYI036: Bad star-args annotation -72 | | PYI036 All arguments after the first four in `__exit__` must have a default value diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI036_PYI036.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI036_PYI036.pyi.snap index fe50de855a522..3927d41aedf52 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI036_PYI036.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI036_PYI036.pyi.snap @@ -11,10 +11,8 @@ PYI036 [*] Star-args in `__exit__` should be annotated with `object` | help: Annotate star-args with `object` | -53 | class BadOne: - - def __exit__(self, *args: Any) -> None: ... # PYI036: Bad star-args annotation +54 - def __exit__(self, *args: Any) -> None: ... # PYI036: Bad star-args annotation 54 + def __exit__(self, *args: object) -> None: ... # PYI036: Bad star-args annotation -55 | async def __aexit__(self) -> None: ... # PYI036: Missing args | PYI036 If there are no star-args, `__aexit__` should have at least 3 non-keyword-only args (excluding `self`) @@ -129,10 +127,8 @@ PYI036 [*] Star-args in `__exit__` should be annotated with `object` | help: Annotate star-args with `object` | -69 | class BadFive: - - def __exit__(self, typ: BaseException | None, *args: list[str]) -> bool: ... # PYI036: Bad star-args annotation +70 - def __exit__(self, typ: BaseException | None, *args: list[str]) -> bool: ... # PYI036: Bad star-args annotation 70 + def __exit__(self, typ: BaseException | None, *args: object) -> bool: ... # PYI036: Bad star-args annotation -71 | async def __aexit__(self, /, typ: type[BaseException] | None, *args: Any) -> Awaitable[None]: ... # PYI036: Bad star-args annotation | PYI036 [*] Star-args in `__aexit__` should be annotated with `object` @@ -147,10 +143,8 @@ PYI036 [*] Star-args in `__aexit__` should be annotated with `object` | help: Annotate star-args with `object` | -70 | def __exit__(self, typ: BaseException | None, *args: list[str]) -> bool: ... # PYI036: Bad star-args annotation - - async def __aexit__(self, /, typ: type[BaseException] | None, *args: Any) -> Awaitable[None]: ... # PYI036: Bad star-args annotation +71 - async def __aexit__(self, /, typ: type[BaseException] | None, *args: Any) -> Awaitable[None]: ... # PYI036: Bad star-args annotation 71 + async def __aexit__(self, /, typ: type[BaseException] | None, *args: object) -> Awaitable[None]: ... # PYI036: Bad star-args annotation -72 | | PYI036 All arguments after the first four in `__exit__` must have a default value diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI041_PYI041_1.py.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI041_PYI041_1.py.snap index 55f4146359570..fbbfa6083f7d1 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI041_PYI041_1.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI041_PYI041_1.py.snap @@ -10,10 +10,8 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -22 | - - def f0(arg1: float | int) -> None: +23 - def f0(arg1: float | int) -> None: 23 + def f0(arg1: float) -> None: -24 | ... | PYI041 [*] Use `complex` instead of `float | complex` @@ -25,10 +23,8 @@ PYI041 [*] Use `complex` instead of `float | complex` | help: Remove redundant type | -26 | - - def f1(arg1: float, *, arg2: float | list[str] | type[bool] | complex) -> None: +27 - def f1(arg1: float, *, arg2: float | list[str] | type[bool] | complex) -> None: 27 + def f1(arg1: float, *, arg2: list[str] | type[bool] | complex) -> None: -28 | ... | PYI041 [*] Use `float` instead of `int | float` @@ -40,10 +36,8 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -30 | - - def f2(arg1: int, /, arg2: int | int | float) -> None: +31 - def f2(arg1: int, /, arg2: int | int | float) -> None: 31 + def f2(arg1: int, /, arg2: float) -> None: -32 | ... | PYI041 [*] Use `float` instead of `int | float` @@ -55,10 +49,8 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -34 | - - def f3(arg1: int, *args: Union[int | int | float]) -> None: +35 - def f3(arg1: int, *args: Union[int | int | float]) -> None: 35 + def f3(arg1: int, *args: float) -> None: -36 | ... | PYI041 [*] Use `float` instead of `int | float` @@ -70,10 +62,8 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -38 | - - async def f4(**kwargs: int | int | float) -> None: +39 - async def f4(**kwargs: int | int | float) -> None: 39 + async def f4(**kwargs: float) -> None: -40 | ... | PYI041 [*] Use `float` instead of `int | float` @@ -85,10 +75,8 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -42 | - - def f5(arg1: int, *args: Union[int, int, float]) -> None: +43 - def f5(arg1: int, *args: Union[int, int, float]) -> None: 43 + def f5(arg1: int, *args: float) -> None: -44 | ... | PYI041 [*] Use `float` instead of `int | float` @@ -100,10 +88,8 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -46 | - - def f6(arg1: int, *args: Union[Union[int, int, float]]) -> None: +47 - def f6(arg1: int, *args: Union[Union[int, int, float]]) -> None: 47 + def f6(arg1: int, *args: float) -> None: -48 | ... | PYI041 [*] Use `float` instead of `int | float` @@ -115,10 +101,8 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -50 | - - def f7(arg1: int, *args: Union[Union[Union[int, int, float]]]) -> None: +51 - def f7(arg1: int, *args: Union[Union[Union[int, int, float]]]) -> None: 51 + def f7(arg1: int, *args: float) -> None: -52 | ... | PYI041 [*] Use `float` instead of `int | float` @@ -130,10 +114,8 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -54 | - - def f8(arg1: int, *args: Union[Union[Union[int | int | float]]]) -> None: +55 - def f8(arg1: int, *args: Union[Union[Union[int | int | float]]]) -> None: 55 + def f8(arg1: int, *args: float) -> None: -56 | ... | PYI041 [*] Use `complex` instead of `int | float | complex` @@ -150,12 +132,10 @@ PYI041 [*] Use `complex` instead of `int | float | complex` | help: Remove redundant type | -59 | def f9( - - arg: Union[ # comment - - float, # another - - complex, int] +60 - arg: Union[ # comment +61 - float, # another +62 - complex, int] 60 + arg: complex -61 | ) -> None: | note: This is an unsafe fix and may change runtime behavior @@ -173,10 +153,8 @@ PYI041 [*] Use `complex` instead of `int | float | complex` | help: Remove redundant type | -67 | arg: ( - - int | # comment - - float | # another -68 | complex +68 - int | # comment +69 - float | # another | note: This is an unsafe fix and may change runtime behavior @@ -191,10 +169,8 @@ PYI041 [*] Use `complex` instead of `int | float | complex` | help: Remove redundant type | -79 | - - def bad(self, arg: int | float | complex) -> None: +80 - def bad(self, arg: int | float | complex) -> None: 80 + def bad(self, arg: complex) -> None: -81 | ... | PYI041 [*] Use `complex` instead of `int | float | complex` @@ -208,10 +184,8 @@ PYI041 [*] Use `complex` instead of `int | float | complex` | help: Remove redundant type | -82 | - - def bad2(self, arg: int | Union[float, complex]) -> None: +83 - def bad2(self, arg: int | Union[float, complex]) -> None: 83 + def bad2(self, arg: complex) -> None: -84 | ... | PYI041 [*] Use `complex` instead of `int | float | complex` @@ -225,10 +199,8 @@ PYI041 [*] Use `complex` instead of `int | float | complex` | help: Remove redundant type | -85 | - - def bad3(self, arg: Union[Union[float, complex], int]) -> None: +86 - def bad3(self, arg: Union[Union[float, complex], int]) -> None: 86 + def bad3(self, arg: complex) -> None: -87 | ... | PYI041 [*] Use `complex` instead of `int | float | complex` @@ -242,10 +214,8 @@ PYI041 [*] Use `complex` instead of `int | float | complex` | help: Remove redundant type | -88 | - - def bad4(self, arg: Union[float | complex, int]) -> None: +89 - def bad4(self, arg: Union[float | complex, int]) -> None: 89 + def bad4(self, arg: complex) -> None: -90 | ... | PYI041 [*] Use `complex` instead of `int | float | complex` @@ -259,10 +229,8 @@ PYI041 [*] Use `complex` instead of `int | float | complex` | help: Remove redundant type | -91 | - - def bad5(self, arg: int | (float | complex)) -> None: +92 - def bad5(self, arg: int | (float | complex)) -> None: 92 + def bad5(self, arg: complex) -> None: -93 | ... | PYI041 Use `float` instead of `int | float` @@ -288,10 +256,8 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -103 | - - def f2(self, arg: None | int | None | float = None) -> None: ... # PYI041 - with fix +104 - def f2(self, arg: None | int | None | float = None) -> None: ... # PYI041 - with fix 104 + def f2(self, arg: None | None | float = None) -> None: ... # PYI041 - with fix -105 | | PYI041 [*] Use `float` instead of `int | float` @@ -305,8 +271,6 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -110 | - - def f3(self, arg: None | float | None | int | None = None) -> None: # PYI041 - with fix +111 - def f3(self, arg: None | float | None | int | None = None) -> None: # PYI041 - with fix 111 + def f3(self, arg: None | float | None | None = None) -> None: # PYI041 - with fix -112 | pass | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI041_PYI041_1.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI041_PYI041_1.pyi.snap index fe68fdfd7f274..fd61863808ddb 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI041_PYI041_1.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI041_PYI041_1.pyi.snap @@ -8,10 +8,8 @@ PYI041 [*] Use `float` instead of `int | float` | ^^^^^^^^^^^ help: Remove redundant type | -20 | - - def f0(arg1: float | int) -> None: ... # PYI041 +21 - def f0(arg1: float | int) -> None: ... # PYI041 21 + def f0(arg1: float) -> None: ... # PYI041 -22 | | PYI041 [*] Use `complex` instead of `float | complex` @@ -21,10 +19,8 @@ PYI041 [*] Use `complex` instead of `float | complex` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove redundant type | -23 | - - def f1(arg1: float, *, arg2: float | list[str] | type[bool] | complex) -> None: ... # PYI041 +24 - def f1(arg1: float, *, arg2: float | list[str] | type[bool] | complex) -> None: ... # PYI041 24 + def f1(arg1: float, *, arg2: list[str] | type[bool] | complex) -> None: ... # PYI041 -25 | | PYI041 [*] Use `float` instead of `int | float` @@ -34,10 +30,8 @@ PYI041 [*] Use `float` instead of `int | float` | ^^^^^^^^^^^^^^^^^ help: Remove redundant type | -26 | - - def f2(arg1: int, /, arg2: int | int | float) -> None: ... # PYI041 +27 - def f2(arg1: int, /, arg2: int | int | float) -> None: ... # PYI041 27 + def f2(arg1: int, /, arg2: float) -> None: ... # PYI041 -28 | | PYI041 [*] Use `float` instead of `int | float` @@ -47,10 +41,8 @@ PYI041 [*] Use `float` instead of `int | float` | ^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove redundant type | -29 | - - def f3(arg1: int, *args: Union[int | int | float]) -> None: ... # PYI041 +30 - def f3(arg1: int, *args: Union[int | int | float]) -> None: ... # PYI041 30 + def f3(arg1: int, *args: float) -> None: ... # PYI041 -31 | | PYI041 [*] Use `float` instead of `int | float` @@ -63,10 +55,8 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -32 | - - async def f4(**kwargs: int | int | float) -> None: ... # PYI041 +33 - async def f4(**kwargs: int | int | float) -> None: ... # PYI041 33 + async def f4(**kwargs: float) -> None: ... # PYI041 -34 | | PYI041 [*] Use `complex` instead of `int | float | complex` @@ -82,12 +72,10 @@ PYI041 [*] Use `complex` instead of `int | float | complex` | help: Remove redundant type | -35 | def f5( - - arg: Union[ # comment - - float, # another - - complex, int] +36 - arg: Union[ # comment +37 - float, # another +38 - complex, int] 36 + arg: complex -37 | ) -> None: ... # PYI041 | note: This is an unsafe fix and may change runtime behavior @@ -105,10 +93,8 @@ PYI041 [*] Use `complex` instead of `int | float | complex` | help: Remove redundant type | -42 | arg: ( - - int | # comment - - float | # another -43 | complex +43 - int | # comment +44 - float | # another | note: This is an unsafe fix and may change runtime behavior @@ -121,10 +107,8 @@ PYI041 [*] Use `float` instead of `int | float` | ^^^^^^^^^^^^^^^^^^^^^^ help: Remove redundant type | -48 | - - def f5(arg1: int, *args: Union[int, int, float]) -> None: ... # PYI041 +49 - def f5(arg1: int, *args: Union[int, int, float]) -> None: ... # PYI041 49 + def f5(arg1: int, *args: float) -> None: ... # PYI041 -50 | | PYI041 [*] Use `float` instead of `int | float` @@ -134,10 +118,8 @@ PYI041 [*] Use `float` instead of `int | float` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove redundant type | -51 | - - def f6(arg1: int, *args: Union[Union[int, int, float]]) -> None: ... # PYI041 +52 - def f6(arg1: int, *args: Union[Union[int, int, float]]) -> None: ... # PYI041 52 + def f6(arg1: int, *args: float) -> None: ... # PYI041 -53 | | PYI041 [*] Use `float` instead of `int | float` @@ -147,10 +129,8 @@ PYI041 [*] Use `float` instead of `int | float` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove redundant type | -54 | - - def f7(arg1: int, *args: Union[Union[Union[int, int, float]]]) -> None: ... # PYI041 +55 - def f7(arg1: int, *args: Union[Union[Union[int, int, float]]]) -> None: ... # PYI041 55 + def f7(arg1: int, *args: float) -> None: ... # PYI041 -56 | | PYI041 [*] Use `float` instead of `int | float` @@ -160,10 +140,8 @@ PYI041 [*] Use `float` instead of `int | float` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove redundant type | -57 | - - def f8(arg1: int, *args: Union[Union[Union[int | int | float]]]) -> None: ... # PYI041 +58 - def f8(arg1: int, *args: Union[Union[Union[int | int | float]]]) -> None: ... # PYI041 58 + def f8(arg1: int, *args: float) -> None: ... # PYI041 -59 | | PYI041 [*] Use `complex` instead of `int | float | complex` @@ -178,10 +156,8 @@ PYI041 [*] Use `complex` instead of `int | float | complex` | help: Remove redundant type | -63 | - - def bad(self, arg: int | float | complex) -> None: ... # PYI041 +64 - def bad(self, arg: int | float | complex) -> None: ... # PYI041 64 + def bad(self, arg: complex) -> None: ... # PYI041 -65 | | PYI041 [*] Use `complex` instead of `int | float | complex` @@ -196,10 +172,8 @@ PYI041 [*] Use `complex` instead of `int | float | complex` | help: Remove redundant type | -65 | - - def bad2(self, arg: int | Union[float, complex]) -> None: ... # PYI041 +66 - def bad2(self, arg: int | Union[float, complex]) -> None: ... # PYI041 66 + def bad2(self, arg: complex) -> None: ... # PYI041 -67 | | PYI041 [*] Use `complex` instead of `int | float | complex` @@ -214,10 +188,8 @@ PYI041 [*] Use `complex` instead of `int | float | complex` | help: Remove redundant type | -67 | - - def bad3(self, arg: Union[Union[float, complex], int]) -> None: ... # PYI041 +68 - def bad3(self, arg: Union[Union[float, complex], int]) -> None: ... # PYI041 68 + def bad3(self, arg: complex) -> None: ... # PYI041 -69 | | PYI041 [*] Use `complex` instead of `int | float | complex` @@ -232,10 +204,8 @@ PYI041 [*] Use `complex` instead of `int | float | complex` | help: Remove redundant type | -69 | - - def bad4(self, arg: Union[float | complex, int]) -> None: ... # PYI041 +70 - def bad4(self, arg: Union[float | complex, int]) -> None: ... # PYI041 70 + def bad4(self, arg: complex) -> None: ... # PYI041 -71 | | PYI041 [*] Use `complex` instead of `int | float | complex` @@ -247,10 +217,8 @@ PYI041 [*] Use `complex` instead of `int | float | complex` | ^^^^^^^^^^^^^^^^^^^^^^^ help: Remove redundant type | -71 | - - def bad5(self, arg: int | (float | complex)) -> None: ... # PYI041 +72 - def bad5(self, arg: int | (float | complex)) -> None: ... # PYI041 72 + def bad5(self, arg: complex) -> None: ... # PYI041 -73 | | PYI041 [*] Use `float` instead of `int | float` @@ -265,10 +233,8 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -77 | class Issue18298: - - def f1(self, arg: None | int | None | float = None) -> None: ... # PYI041 - with fix +78 - def f1(self, arg: None | int | None | float = None) -> None: ... # PYI041 - with fix 78 + def f1(self, arg: None | None | float = None) -> None: ... # PYI041 - with fix -79 | | PYI041 [*] Use `float` instead of `int | float` @@ -280,7 +246,6 @@ PYI041 [*] Use `float` instead of `int | float` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove redundant type | -79 | - - def f3(self, arg: None | float | None | int | None = None) -> None: ... # PYI041 - with fix +80 - def f3(self, arg: None | float | None | int | None = None) -> None: ... # PYI041 - with fix 80 + def f3(self, arg: None | float | None | None = None) -> None: ... # PYI041 - with fix | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI044_PYI044.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI044_PYI044.pyi.snap index 2aeb7652a1384..3f601ede53f31 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI044_PYI044.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI044_PYI044.pyi.snap @@ -11,9 +11,7 @@ PYI044 [*] `from __future__ import annotations` has no effect in stub files, sin | help: Remove `from __future__ import annotations` | -1 | # Bad import. - - from __future__ import annotations # PYI044. -2 | from __future__ import annotations, with_statement # PYI044. +2 - from __future__ import annotations # PYI044. | PYI044 [*] `from __future__ import annotations` has no effect in stub files, since type checkers automatically treat stubs as having those semantics @@ -28,8 +26,6 @@ PYI044 [*] `from __future__ import annotations` has no effect in stub files, sin | help: Remove `from __future__ import annotations` | -2 | from __future__ import annotations # PYI044. - - from __future__ import annotations, with_statement # PYI044. +3 - from __future__ import annotations, with_statement # PYI044. 3 + from __future__ import with_statement # PYI044. -4 | | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI053_PYI053.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI053_PYI053.pyi.snap index 27ff3ec838e3e..e2914fba51939 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI053_PYI053.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI053_PYI053.pyi.snap @@ -13,10 +13,8 @@ PYI053 [*] String and bytes literals longer than 50 characters are not permitted | help: Replace with `...` | -6 | def f2( - - x: str = "51 character stringgggggggggggggggggggggggggggggggg", # Error: PYI053 +7 - x: str = "51 character stringgggggggggggggggggggggggggggggggg", # Error: PYI053 7 + x: str = ..., # Error: PYI053 -8 | ) -> None: ... | PYI053 [*] String and bytes literals longer than 50 characters are not permitted @@ -31,10 +29,8 @@ PYI053 [*] String and bytes literals longer than 50 characters are not permitted | help: Replace with `...` | -12 | def f4( - - x: str = "51 character stringggggggggggggggggggggggggggggggg\U0001f600", # Error: PYI053 +13 - x: str = "51 character stringggggggggggggggggggggggggggggggg\U0001f600", # Error: PYI053 13 + x: str = ..., # Error: PYI053 -14 | ) -> None: ... | PYI053 [*] String and bytes literals longer than 50 characters are not permitted @@ -48,10 +44,8 @@ PYI053 [*] String and bytes literals longer than 50 characters are not permitted | help: Replace with `...` | -24 | def f8( - - x: bytes = b"51 character byte stringgggggggggggggggggggggggggg\xff", # Error: PYI053 +25 - x: bytes = b"51 character byte stringgggggggggggggggggggggggggg\xff", # Error: PYI053 25 + x: bytes = ..., # Error: PYI053 -26 | ) -> None: ... | PYI053 [*] String and bytes literals longer than 50 characters are not permitted @@ -66,10 +60,8 @@ PYI053 [*] String and bytes literals longer than 50 characters are not permitted | help: Replace with `...` | -29 | - - bar: str = "51 character stringgggggggggggggggggggggggggggggggg" # Error: PYI053 +30 - bar: str = "51 character stringgggggggggggggggggggggggggggggggg" # Error: PYI053 30 + bar: str = ... # Error: PYI053 -31 | | PYI053 [*] String and bytes literals longer than 50 characters are not permitted @@ -84,10 +76,8 @@ PYI053 [*] String and bytes literals longer than 50 characters are not permitted | help: Replace with `...` | -33 | - - qux: bytes = b"51 character byte stringggggggggggggggggggggggggggg\xff" # Error: PYI053 +34 - qux: bytes = b"51 character byte stringggggggggggggggggggggggggggg\xff" # Error: PYI053 34 + qux: bytes = ... # Error: PYI053 -35 | | PYI053 [*] String and bytes literals longer than 50 characters are not permitted @@ -102,10 +92,8 @@ PYI053 [*] String and bytes literals longer than 50 characters are not permitted | help: Replace with `...` | -37 | - - fbar: str = f"51 character stringgggggggggggggggggggggggggggggggg" # Error: PYI053 +38 - fbar: str = f"51 character stringgggggggggggggggggggggggggggggggg" # Error: PYI053 38 + fbar: str = ... # Error: PYI053 -39 | | PYI053 [*] String and bytes literals longer than 50 characters are not permitted @@ -119,10 +107,8 @@ PYI053 [*] String and bytes literals longer than 50 characters are not permitted | help: Replace with `...` | -63 | @not_warnings_dot_deprecated( - - "Not warnings.deprecated, so this one *should* lead to PYI053 in a stub!" # Error: PYI053 +64 - "Not warnings.deprecated, so this one *should* lead to PYI053 in a stub!" # Error: PYI053 64 + ... # Error: PYI053 -65 | ) | PYI053 [*] String and bytes literals longer than 50 characters are not permitted @@ -137,8 +123,6 @@ PYI053 [*] String and bytes literals longer than 50 characters are not permitted | help: Replace with `...` | -67 | - - fbaz: str = f"51 character {foo} stringgggggggggggggggggggggggggg" # Error: PYI053 +68 - fbaz: str = f"51 character {foo} stringgggggggggggggggggggggggggg" # Error: PYI053 68 + fbaz: str = ... # Error: PYI053 -69 | | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI054_PYI054.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI054_PYI054.pyi.snap index 335d4c319d2bf..8c74d49dc4807 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI054_PYI054.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI054_PYI054.pyi.snap @@ -12,10 +12,8 @@ PYI054 [*] Numeric literals with a string representation longer than ten charact | help: Replace with `...` | -1 | field01: int = 0xFFFFFFFF - - field02: int = 0xFFFFFFFFF # Error: PYI054 +2 - field02: int = 0xFFFFFFFFF # Error: PYI054 2 + field02: int = ... # Error: PYI054 -3 | field03: int = -0xFFFFFFFF | PYI054 [*] Numeric literals with a string representation longer than ten characters are not permitted @@ -30,10 +28,8 @@ PYI054 [*] Numeric literals with a string representation longer than ten charact | help: Replace with `...` | -3 | field03: int = -0xFFFFFFFF - - field04: int = -0xFFFFFFFFF # Error: PYI054 +4 - field04: int = -0xFFFFFFFFF # Error: PYI054 4 + field04: int = -... # Error: PYI054 -5 | | PYI054 [*] Numeric literals with a string representation longer than ten characters are not permitted @@ -48,10 +44,8 @@ PYI054 [*] Numeric literals with a string representation longer than ten charact | help: Replace with `...` | -7 | field06: int = 12_456_890 - - field07: int = 12345678901 # Error: PYI054 +8 - field07: int = 12345678901 # Error: PYI054 8 + field07: int = ... # Error: PYI054 -9 | field08: int = -1234567801 | PYI054 [*] Numeric literals with a string representation longer than ten characters are not permitted @@ -66,10 +60,8 @@ PYI054 [*] Numeric literals with a string representation longer than ten charact | help: Replace with `...` | -9 | field08: int = -1234567801 - - field09: int = -234_567_890 # Error: PYI054 +10 - field09: int = -234_567_890 # Error: PYI054 10 + field09: int = -... # Error: PYI054 -11 | | PYI054 [*] Numeric literals with a string representation longer than ten characters are not permitted @@ -83,10 +75,8 @@ PYI054 [*] Numeric literals with a string representation longer than ten charact | help: Replace with `...` | -12 | field10: float = 123.456789 - - field11: float = 123.4567890 # Error: PYI054 +13 - field11: float = 123.4567890 # Error: PYI054 13 + field11: float = ... # Error: PYI054 -14 | field12: float = -123.456789 | PYI054 [*] Numeric literals with a string representation longer than ten characters are not permitted @@ -101,10 +91,8 @@ PYI054 [*] Numeric literals with a string representation longer than ten charact | help: Replace with `...` | -14 | field12: float = -123.456789 - - field13: float = -123.567_890 # Error: PYI054 +15 - field13: float = -123.567_890 # Error: PYI054 15 + field13: float = -... # Error: PYI054 -16 | | PYI054 [*] Numeric literals with a string representation longer than ten characters are not permitted @@ -118,10 +106,8 @@ PYI054 [*] Numeric literals with a string representation longer than ten charact | help: Replace with `...` | -17 | field14: complex = 1e1234567j - - field15: complex = 1e12345678j # Error: PYI054 +18 - field15: complex = 1e12345678j # Error: PYI054 18 + field15: complex = ... # Error: PYI054 -19 | field16: complex = -1e1234567j | PYI054 [*] Numeric literals with a string representation longer than ten characters are not permitted @@ -133,7 +119,6 @@ PYI054 [*] Numeric literals with a string representation longer than ten charact | ^^^^^^^^^^^^ help: Replace with `...` | -19 | field16: complex = -1e1234567j - - field17: complex = 1e123456789j # Error: PYI054 +20 - field17: complex = 1e123456789j # Error: PYI054 20 + field17: complex = ... # Error: PYI054 | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI055_PYI055.py.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI055_PYI055.py.snap index 38150e6db7ccc..de6f3b0c93422 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI055_PYI055.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI055_PYI055.py.snap @@ -13,10 +13,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -3 | - - s: builtins.type[int] | builtins.type[str] | builtins.type[complex] +4 - s: builtins.type[int] | builtins.type[str] | builtins.type[complex] 4 + s: type[int | str | complex] -5 | t: type[int] | type[str] | type[float] | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[int | str | float]`. @@ -30,10 +28,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -4 | s: builtins.type[int] | builtins.type[str] | builtins.type[complex] - - t: type[int] | type[str] | type[float] +5 - t: type[int] | type[str] | type[float] 5 + t: type[int | str | float] -6 | u: builtins.type[int] | type[str] | builtins.type[complex] | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[int | str | complex]`. @@ -48,10 +44,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -5 | t: type[int] | type[str] | type[float] - - u: builtins.type[int] | type[str] | builtins.type[complex] +6 - u: builtins.type[int] | type[str] | builtins.type[complex] 6 + u: type[int | str | complex] -7 | v: Union[type[float], type[complex]] | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[Union[float, complex]]`. @@ -66,10 +60,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -6 | u: builtins.type[int] | type[str] | builtins.type[complex] - - v: Union[type[float], type[complex]] +7 - v: Union[type[float], type[complex]] 7 + v: type[Union[float, complex]] -8 | w: Union[type[float | int], type[complex]] | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[Union[float | int, complex]]`. @@ -84,10 +76,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -7 | v: Union[type[float], type[complex]] - - w: Union[type[float | int], type[complex]] +8 - w: Union[type[float | int], type[complex]] 8 + w: type[Union[float | int, complex]] -9 | x: Union[Union[type[Union[float, int]], type[complex]]] | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[Union[Union[float, int], complex]]`. @@ -101,12 +91,10 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ 11 | z: Union[type[complex], Union[Union[type[Union[float, int]]]]] | help: Combine multiple `type` members - | -8 | w: Union[type[float | int], type[complex]] - - x: Union[Union[type[Union[float, int]], type[complex]]] -9 + x: type[Union[Union[float, int], complex]] -10 | y: Union[Union[Union[type[float | int], type[complex]]]] - | + | +9 - x: Union[Union[type[Union[float, int]], type[complex]]] +9 + x: type[Union[Union[float, int], complex]] + | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[Union[float | int, complex]]`. --> PYI055.py:10:4 @@ -119,10 +107,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -9 | x: Union[Union[type[Union[float, int]], type[complex]]] - - y: Union[Union[Union[type[float | int], type[complex]]]] +10 - y: Union[Union[Union[type[float | int], type[complex]]]] 10 + y: type[Union[float | int, complex]] -11 | z: Union[type[complex], Union[Union[type[Union[float, int]]]]] | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[Union[complex, Union[float, int]]]`. @@ -134,10 +120,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Combine multiple `type` members | -10 | y: Union[Union[Union[type[float | int], type[complex]]]] - - z: Union[type[complex], Union[Union[type[Union[float, int]]]]] +11 - z: Union[type[complex], Union[Union[type[Union[float, int]]]]] 11 + z: type[Union[complex, Union[float, int]]] -12 | | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[int | float]`. @@ -149,10 +133,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -13 | - - def func(arg: type[int] | str | type[float]) -> None: +14 - def func(arg: type[int] | str | type[float]) -> None: 14 + def func(arg: type[int | float] | str) -> None: -15 | ... | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[requests_mock.Mocker | httpretty]`. @@ -163,10 +145,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Combine multiple `type` members | -28 | # OK - - item: type[requests_mock.Mocker] | type[httpretty] = requests_mock.Mocker +29 - item: type[requests_mock.Mocker] | type[httpretty] = requests_mock.Mocker 29 + item: type[requests_mock.Mocker | httpretty] = requests_mock.Mocker -30 | | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[requests_mock.Mocker | httpretty | str]`. @@ -181,10 +161,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -33 | # PYI055 - - x: type[requests_mock.Mocker] | type[httpretty] | type[str] = requests_mock.Mocker +34 - x: type[requests_mock.Mocker] | type[httpretty] | type[str] = requests_mock.Mocker 34 + x: type[requests_mock.Mocker | httpretty | str] = requests_mock.Mocker -35 | y: Union[type[requests_mock.Mocker], type[httpretty], type[str]] = requests_mock.Mocker | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[Union[requests_mock.Mocker, httpretty, str]]`. @@ -199,10 +177,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -34 | x: type[requests_mock.Mocker] | type[httpretty] | type[str] = requests_mock.Mocker - - y: Union[type[requests_mock.Mocker], type[httpretty], type[str]] = requests_mock.Mocker +35 - y: Union[type[requests_mock.Mocker], type[httpretty], type[str]] = requests_mock.Mocker 35 + y: type[Union[requests_mock.Mocker, httpretty, str]] = requests_mock.Mocker -36 | z: Union[ # comment | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[Union[requests_mock.Mocker, httpretty, str]]`. @@ -217,12 +193,10 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | |___________________________________^ help: Combine multiple `type` members | -35 | y: Union[type[requests_mock.Mocker], type[httpretty], type[str]] = requests_mock.Mocker - - z: Union[ # comment - - type[requests_mock.Mocker], # another comment - - type[httpretty], type[str]] = requests_mock.Mocker +36 - z: Union[ # comment +37 - type[requests_mock.Mocker], # another comment +38 - type[httpretty], type[str]] = requests_mock.Mocker 36 + z: type[Union[requests_mock.Mocker, httpretty, str]] = requests_mock.Mocker -37 | | note: This is an unsafe fix and may change runtime behavior @@ -234,10 +208,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Combine multiple `type` members | -44 | # PYI055 - - x: Union[type[requests_mock.Mocker], type[httpretty], type[str]] = requests_mock.Mocker +45 - x: Union[type[requests_mock.Mocker], type[httpretty], type[str]] = requests_mock.Mocker 45 + x: type[Union[requests_mock.Mocker, httpretty, str]] = requests_mock.Mocker -46 | | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[_T | Converter[_T]]`. @@ -252,10 +224,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -49 | converters: tuple[ - - type[_T] | type[Converter[_T]] | Converter[_T] | Callable[[str], _T], ... # PYI055 +50 - type[_T] | type[Converter[_T]] | Converter[_T] | Callable[[str], _T], ... # PYI055 50 + type[_T | Converter[_T]] | Converter[_T] | Callable[[str], _T], ... # PYI055 -51 | ] = union.__args__ | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[_T | Converter[_T]]`. @@ -270,10 +240,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -55 | converters: tuple[ - - Union[type[_T] | type[Converter[_T]] | Converter[_T] | Callable[[str], _T]], ... # PYI055 +56 - Union[type[_T] | type[Converter[_T]] | Converter[_T] | Callable[[str], _T]], ... # PYI055 56 + type[_T | Converter[_T]] | Converter[_T] | Callable[[str], _T], ... # PYI055 -57 | ] = union.__args__ | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[_T | Converter[_T]]`. @@ -288,10 +256,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -61 | converters: tuple[ - - Union[type[_T] | type[Converter[_T]]] | Converter[_T] | Callable[[str], _T], ... # PYI055 +62 - Union[type[_T] | type[Converter[_T]]] | Converter[_T] | Callable[[str], _T], ... # PYI055 62 + type[_T | Converter[_T]] | Converter[_T] | Callable[[str], _T], ... # PYI055 -63 | ] = union.__args__ | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[_T | Converter[_T]]`. @@ -306,8 +272,6 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -67 | converters: tuple[ - - Union[type[_T] | type[Converter[_T]] | str] | Converter[_T] | Callable[[str], _T], ... # PYI055 +68 - Union[type[_T] | type[Converter[_T]] | str] | Converter[_T] | Callable[[str], _T], ... # PYI055 68 + type[_T | Converter[_T]] | str | Converter[_T] | Callable[[str], _T], ... # PYI055 -69 | ] = union.__args__ | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI055_PYI055.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI055_PYI055.pyi.snap index b5defd6f570d2..ff4369c9c2901 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI055_PYI055.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI055_PYI055.pyi.snap @@ -13,10 +13,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -3 | - - s: builtins.type[int] | builtins.type[str] | builtins.type[complex] +4 - s: builtins.type[int] | builtins.type[str] | builtins.type[complex] 4 + s: type[int | str | complex] -5 | t: type[int] | type[str] | type[float] | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[int | str | float]`. @@ -30,10 +28,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -4 | s: builtins.type[int] | builtins.type[str] | builtins.type[complex] - - t: type[int] | type[str] | type[float] +5 - t: type[int] | type[str] | type[float] 5 + t: type[int | str | float] -6 | u: builtins.type[int] | type[str] | builtins.type[complex] | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[int | str | complex]`. @@ -48,10 +44,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -5 | t: type[int] | type[str] | type[float] - - u: builtins.type[int] | type[str] | builtins.type[complex] +6 - u: builtins.type[int] | type[str] | builtins.type[complex] 6 + u: type[int | str | complex] -7 | v: Union[type[float], type[complex]] | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[Union[float, complex]]`. @@ -66,10 +60,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -6 | u: builtins.type[int] | type[str] | builtins.type[complex] - - v: Union[type[float], type[complex]] +7 - v: Union[type[float], type[complex]] 7 + v: type[Union[float, complex]] -8 | w: Union[type[Union[float, int]], type[complex]] | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[Union[Union[float, int], complex]]`. @@ -84,10 +76,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -7 | v: Union[type[float], type[complex]] - - w: Union[type[Union[float, int]], type[complex]] +8 - w: Union[type[Union[float, int]], type[complex]] 8 + w: type[Union[Union[float, int], complex]] -9 | x: Union[Union[type[Union[float, int]], type[complex]]] | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[Union[Union[float, int], complex]]`. @@ -101,12 +91,10 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ 11 | z: Union[type[complex], Union[Union[type[Union[float, int]]]]] | help: Combine multiple `type` members - | -8 | w: Union[type[Union[float, int]], type[complex]] - - x: Union[Union[type[Union[float, int]], type[complex]]] -9 + x: type[Union[Union[float, int], complex]] -10 | y: Union[Union[Union[type[Union[float, int]], type[complex]]]] - | + | +9 - x: Union[Union[type[Union[float, int]], type[complex]]] +9 + x: type[Union[Union[float, int], complex]] + | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[Union[Union[float, int], complex]]`. --> PYI055.pyi:10:4 @@ -119,10 +107,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -9 | x: Union[Union[type[Union[float, int]], type[complex]]] - - y: Union[Union[Union[type[Union[float, int]], type[complex]]]] +10 - y: Union[Union[Union[type[Union[float, int]], type[complex]]]] 10 + y: type[Union[Union[float, int], complex]] -11 | z: Union[type[complex], Union[Union[type[Union[float, int]]]]] | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[Union[complex, Union[float, int]]]`. @@ -137,10 +123,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -10 | y: Union[Union[Union[type[Union[float, int]], type[complex]]]] - - z: Union[type[complex], Union[Union[type[Union[float, int]]]]] +11 - z: Union[type[complex], Union[Union[type[Union[float, int]]]]] 11 + z: type[Union[complex, Union[float, int]]] -12 | | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[int | float]`. @@ -155,10 +139,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -12 | - - def func(arg: type[int] | str | type[float]) -> None: ... +13 - def func(arg: type[int] | str | type[float]) -> None: ... 13 + def func(arg: type[int | float] | str) -> None: ... -14 | | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[requests_mock.Mocker | httpretty]`. @@ -172,10 +154,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -22 | # PYI055 - - item: type[requests_mock.Mocker] | type[httpretty] = requests_mock.Mocker +23 - item: type[requests_mock.Mocker] | type[httpretty] = requests_mock.Mocker 23 + item: type[requests_mock.Mocker | httpretty] = requests_mock.Mocker -24 | | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[requests_mock.Mocker | httpretty | str]`. @@ -190,10 +170,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -26 | # PYI055 - - item: type[requests_mock.Mocker] | type[httpretty] | type[str] = requests_mock.Mocker +27 - item: type[requests_mock.Mocker] | type[httpretty] | type[str] = requests_mock.Mocker 27 + item: type[requests_mock.Mocker | httpretty | str] = requests_mock.Mocker -28 | item2: Union[type[requests_mock.Mocker], type[httpretty], type[str]] = requests_mock.Mocker | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[Union[requests_mock.Mocker, httpretty, str]]`. @@ -208,10 +186,8 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | help: Combine multiple `type` members | -27 | item: type[requests_mock.Mocker] | type[httpretty] | type[str] = requests_mock.Mocker - - item2: Union[type[requests_mock.Mocker], type[httpretty], type[str]] = requests_mock.Mocker +28 - item2: Union[type[requests_mock.Mocker], type[httpretty], type[str]] = requests_mock.Mocker 28 + item2: type[Union[requests_mock.Mocker, httpretty, str]] = requests_mock.Mocker -29 | item3: Union[ # comment | PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `type[Union[requests_mock.Mocker, httpretty, str]]`. @@ -226,11 +202,9 @@ PYI055 [*] Multiple `type` members in a union. Combine them into one, e.g., `typ | |___________________________________^ help: Combine multiple `type` members | -28 | item2: Union[type[requests_mock.Mocker], type[httpretty], type[str]] = requests_mock.Mocker - - item3: Union[ # comment - - type[requests_mock.Mocker], # another comment - - type[httpretty], type[str]] = requests_mock.Mocker +29 - item3: Union[ # comment +30 - type[requests_mock.Mocker], # another comment +31 - type[httpretty], type[str]] = requests_mock.Mocker 29 + item3: type[Union[requests_mock.Mocker, httpretty, str]] = requests_mock.Mocker -30 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI058_PYI058.py.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI058_PYI058.py.snap index 8f88c15597591..419a688d819a7 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI058_PYI058.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI058_PYI058.py.snap @@ -16,9 +16,7 @@ help: Convert the return annotation of your `__iter__` method to `Iterator` 3 | from collections.abc import Generator 4 | 5 | class IteratorReturningSimpleGenerator1: - - def __iter__(self) -> Generator: -6 + def __iter__(self) -> Iterator: -7 | ... # PYI058 (use `Iterator`) +6 ~ def __iter__(self) -> Iterator: | PYI058 [*] Use `Iterator` as the return value for simple `__iter__` methods @@ -31,10 +29,10 @@ PYI058 [*] Use `Iterator` as the return value for simple `__iter__` methods | help: Convert the return annotation of your `__iter__` method to `Iterator` | +10 ~ import typing +11 | 12 | class IteratorReturningSimpleGenerator2: - - def __iter__(self) -> typing.Generator: -13 + def __iter__(self) -> typing.Iterator: -14 | ... # PYI058 (use `Iterator`) +13 ~ def __iter__(self) -> typing.Iterator: | PYI058 [*] Use `Iterator` as the return value for simple `__iter__` methods @@ -47,10 +45,10 @@ PYI058 [*] Use `Iterator` as the return value for simple `__iter__` methods | help: Convert the return annotation of your `__iter__` method to `Iterator` | +18 ~ import collections.abc +19 | 20 | class IteratorReturningSimpleGenerator3: - - def __iter__(self) -> collections.abc.Generator: -21 + def __iter__(self) -> collections.abc.Iterator: -22 | ... # PYI058 (use `Iterator`) +21 ~ def __iter__(self) -> collections.abc.Iterator: | PYI058 [*] Use `Iterator` as the return value for simple `__iter__` methods @@ -63,10 +61,11 @@ PYI058 [*] Use `Iterator` as the return value for simple `__iter__` methods | help: Convert the return annotation of your `__iter__` method to `Iterator` | +26 ~ import collections.abc +27 | from typing import Any +28 | 29 | class IteratorReturningSimpleGenerator4: - - def __iter__(self, /) -> collections.abc.Generator[str, Any, None]: -30 + def __iter__(self, /) -> collections.abc.Iterator[str]: -31 | ... # PYI058 (use `Iterator`) +30 ~ def __iter__(self, /) -> collections.abc.Iterator[str]: | PYI058 [*] Use `Iterator` as the return value for simple `__iter__` methods @@ -79,10 +78,11 @@ PYI058 [*] Use `Iterator` as the return value for simple `__iter__` methods | help: Convert the return annotation of your `__iter__` method to `Iterator` | +35 ~ import collections.abc +36 | import typing +37 | 38 | class IteratorReturningSimpleGenerator5: - - def __iter__(self, /) -> collections.abc.Generator[str, None, typing.Any]: -39 + def __iter__(self, /) -> collections.abc.Iterator[str]: -40 | ... # PYI058 (use `Iterator`) +39 ~ def __iter__(self, /) -> collections.abc.Iterator[str]: | PYI058 [*] Use `Iterator` as the return value for simple `__iter__` methods @@ -95,13 +95,12 @@ PYI058 [*] Use `Iterator` as the return value for simple `__iter__` methods | help: Convert the return annotation of your `__iter__` method to `Iterator` | -1 + from collections.abc import Iterator -2 | def scope(): --------------------------------------------------------------------------------- + 1 + from collections.abc import Iterator + 2 | def scope(): + 3 | from collections.abc import Generator + … 47 | class IteratorReturningSimpleGenerator6: - - def __iter__(self, /) -> Generator[str, None, None]: -48 + def __iter__(self, /) -> Iterator[str]: -49 | ... # PYI058 (use `Iterator`) +48 ~ def __iter__(self, /) -> Iterator[str]: | PYI058 [*] Use `AsyncIterator` as the return value for simple `__aiter__` methods @@ -115,10 +114,11 @@ PYI058 [*] Use `AsyncIterator` as the return value for simple `__aiter__` method | help: Convert the return annotation of your `__aiter__` method to `AsyncIterator` | +52 ~ import typing_extensions +53 | + … 56 | self, - - ) -> typing_extensions.AsyncGenerator: -57 + ) -> typing_extensions.AsyncIterator: -58 | ... # PYI058 (Use `AsyncIterator`) +57 ~ ) -> typing_extensions.AsyncIterator: | PYI058 [*] Use `AsyncIterator` as the return value for simple `__aiter__` methods @@ -131,8 +131,8 @@ PYI058 [*] Use `AsyncIterator` as the return value for simple `__aiter__` method | help: Convert the return annotation of your `__aiter__` method to `AsyncIterator` | +70 ~ import collections.abc +71 | 72 | class AsyncIteratorReturningSimpleAsyncGenerator3: - - def __aiter__(self, /) -> collections.abc.AsyncGenerator[str, None]: -73 + def __aiter__(self, /) -> collections.abc.AsyncIterator[str]: -74 | ... # PYI058 (Use `AsyncIterator`) +73 ~ def __aiter__(self, /) -> collections.abc.AsyncIterator[str]: | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI058_PYI058.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI058_PYI058.pyi.snap index 6310605c3da02..2566d5b774b57 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI058_PYI058.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI058_PYI058.pyi.snap @@ -17,9 +17,7 @@ help: Convert the return annotation of your `__iter__` method to `Iterator` 3 | from collections.abc import Generator 4 | 5 | class IteratorReturningSimpleGenerator1: - - def __iter__(self) -> Generator: ... # PYI058 (use `Iterator`) -6 + def __iter__(self) -> Iterator: ... # PYI058 (use `Iterator`) -7 | +6 ~ def __iter__(self) -> Iterator: ... # PYI058 (use `Iterator`) | PYI058 [*] Use `Iterator` as the return value for simple `__iter__` methods @@ -33,10 +31,10 @@ PYI058 [*] Use `Iterator` as the return value for simple `__iter__` methods | help: Convert the return annotation of your `__iter__` method to `Iterator` | + 8 ~ import typing + 9 | 10 | class IteratorReturningSimpleGenerator2: - - def __iter__(self) -> typing.Generator: ... # PYI058 (use `Iterator`) -11 + def __iter__(self) -> typing.Iterator: ... # PYI058 (use `Iterator`) -12 | +11 ~ def __iter__(self) -> typing.Iterator: ... # PYI058 (use `Iterator`) | PYI058 [*] Use `Iterator` as the return value for simple `__iter__` methods @@ -50,10 +48,10 @@ PYI058 [*] Use `Iterator` as the return value for simple `__iter__` methods | help: Convert the return annotation of your `__iter__` method to `Iterator` | +14 ~ import collections.abc +15 | 16 | class IteratorReturningSimpleGenerator3: - - def __iter__(self) -> collections.abc.Generator: ... # PYI058 (use `Iterator`) -17 + def __iter__(self) -> collections.abc.Iterator: ... # PYI058 (use `Iterator`) -18 | +17 ~ def __iter__(self) -> collections.abc.Iterator: ... # PYI058 (use `Iterator`) | PYI058 [*] Use `Iterator` as the return value for simple `__iter__` methods @@ -67,10 +65,11 @@ PYI058 [*] Use `Iterator` as the return value for simple `__iter__` methods | help: Convert the return annotation of your `__iter__` method to `Iterator` | +20 ~ import collections.abc +21 | from typing import Any +22 | 23 | class IteratorReturningSimpleGenerator4: - - def __iter__(self, /) -> collections.abc.Generator[str, Any, None]: ... # PYI058 (use `Iterator`) -24 + def __iter__(self, /) -> collections.abc.Iterator[str]: ... # PYI058 (use `Iterator`) -25 | +24 ~ def __iter__(self, /) -> collections.abc.Iterator[str]: ... # PYI058 (use `Iterator`) | PYI058 [*] Use `Iterator` as the return value for simple `__iter__` methods @@ -84,10 +83,11 @@ PYI058 [*] Use `Iterator` as the return value for simple `__iter__` methods | help: Convert the return annotation of your `__iter__` method to `Iterator` | +27 ~ import collections.abc +28 | import typing +29 | 30 | class IteratorReturningSimpleGenerator5: - - def __iter__(self, /) -> collections.abc.Generator[str, None, typing.Any]: ... # PYI058 (use `Iterator`) -31 + def __iter__(self, /) -> collections.abc.Iterator[str]: ... # PYI058 (use `Iterator`) -32 | +31 ~ def __iter__(self, /) -> collections.abc.Iterator[str]: ... # PYI058 (use `Iterator`) | PYI058 [*] Use `Iterator` as the return value for simple `__iter__` methods @@ -101,13 +101,12 @@ PYI058 [*] Use `Iterator` as the return value for simple `__iter__` methods | help: Convert the return annotation of your `__iter__` method to `Iterator` | -1 + from collections.abc import Iterator -2 | def scope(): --------------------------------------------------------------------------------- + 1 + from collections.abc import Iterator + 2 | def scope(): + 3 | from collections.abc import Generator + … 37 | class IteratorReturningSimpleGenerator6: - - def __iter__(self, /) -> Generator[str, None, None]: ... # PYI058 (use `Iterator`) -38 + def __iter__(self, /) -> Iterator[str]: ... # PYI058 (use `Iterator`) -39 | +38 ~ def __iter__(self, /) -> Iterator[str]: ... # PYI058 (use `Iterator`) | PYI058 [*] Use `AsyncIterator` as the return value for simple `__aiter__` methods @@ -121,10 +120,10 @@ PYI058 [*] Use `AsyncIterator` as the return value for simple `__aiter__` method | help: Convert the return annotation of your `__aiter__` method to `AsyncIterator` | +40 ~ import typing_extensions +41 | 42 | class AsyncIteratorReturningSimpleAsyncGenerator1: - - def __aiter__(self,) -> typing_extensions.AsyncGenerator: ... # PYI058 (Use `AsyncIterator`) -43 + def __aiter__(self,) -> typing_extensions.AsyncIterator: ... # PYI058 (Use `AsyncIterator`) -44 | +43 ~ def __aiter__(self,) -> typing_extensions.AsyncIterator: ... # PYI058 (Use `AsyncIterator`) | PYI058 [*] Use `AsyncIterator` as the return value for simple `__aiter__` methods @@ -137,10 +136,10 @@ PYI058 [*] Use `AsyncIterator` as the return value for simple `__aiter__` method | help: Convert the return annotation of your `__aiter__` method to `AsyncIterator` | +46 ~ import collections.abc +47 | 48 | class AsyncIteratorReturningSimpleAsyncGenerator3: - - def __aiter__(self, /) -> collections.abc.AsyncGenerator[str, None]: -49 + def __aiter__(self, /) -> collections.abc.AsyncIterator[str]: -50 | ... # PYI058 (Use `AsyncIterator`) +49 ~ def __aiter__(self, /) -> collections.abc.AsyncIterator[str]: | PYI058 [*] Use `AsyncIterator` as the return value for simple `__aiter__` methods @@ -154,8 +153,8 @@ PYI058 [*] Use `AsyncIterator` as the return value for simple `__aiter__` method | help: Convert the return annotation of your `__aiter__` method to `AsyncIterator` | +53 ~ import collections.abc +54 | 55 | class AsyncIteratorReturningSimpleAsyncGenerator3: - - def __aiter__(self, /) -> collections.abc.AsyncGenerator[str, None]: ... # PYI058 (Use `AsyncIterator`) -56 + def __aiter__(self, /) -> collections.abc.AsyncIterator[str]: ... # PYI058 (Use `AsyncIterator`) -57 | +56 ~ def __aiter__(self, /) -> collections.abc.AsyncIterator[str]: ... # PYI058 (Use `AsyncIterator`) | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI059_PYI059.py.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI059_PYI059.py.snap index 19a7941f315b0..84f8b1770e62f 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI059_PYI059.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI059_PYI059.py.snap @@ -13,10 +13,8 @@ PYI059 [*] `Generic[]` should always be the last base class | help: Move `Generic[]` to the end | -7 | - - class LinkedList(Generic[T], Sized): # PYI059 +8 - class LinkedList(Generic[T], Sized): # PYI059 8 + class LinkedList(Sized, Generic[T]): # PYI059 -9 | def __init__(self) -> None: | note: This is an unsafe fix and may change runtime behavior @@ -36,12 +34,8 @@ PYI059 [*] `Generic[]` should always be the last base class | help: Move `Generic[]` to the end | -15 | class MyMapping( # PYI059 - - t.Generic[K, V], -16 | Iterable[Tuple[K, V]], - - Container[Tuple[K, V]], -17 + Container[Tuple[K, V]], t.Generic[K, V], -18 | ): +16 ~ Iterable[Tuple[K, V]], +17 ~ Container[Tuple[K, V]], t.Generic[K, V], | note: This is an unsafe fix and may change runtime behavior @@ -56,10 +50,8 @@ PYI059 [*] `Generic[]` should always be the last base class | help: Move `Generic[]` to the end | -25 | # the Generic's position issue persists. - - class Foo(Generic, LinkedList): # PYI059 +26 - class Foo(Generic, LinkedList): # PYI059 26 + class Foo(LinkedList, Generic): # PYI059 -27 | pass | note: This is an unsafe fix and may change runtime behavior @@ -83,16 +75,10 @@ PYI059 [*] `Generic[]` should always be the last base class | help: Move `Generic[]` to the end | -32 | # Part 2 of multiline comment 1 - - Generic[T] # comment about Generic[T] # PYI059 - - # another comment? - - , # comment about the comma? -33 + # comment about the comma? +33 ~ # comment about the comma? 34 | # part 1 of multiline comment 2 35 | # part 2 of multiline comment 2 - - int, # comment about int -36 + int, Generic[T], # comment about int -37 | # yet another comment? +36 ~ int, Generic[T], # comment about int | note: This is an unsafe fix and may change runtime behavior @@ -115,10 +101,8 @@ PYI059 [*] `Generic[]` should always be the last base class | help: Move `Generic[]` to the end | -58 | # https://github.com/astral-sh/ruff/issues/18602 - - class C1(Generic[T], str, **{"metaclass": type}): # PYI059 +59 - class C1(Generic[T], str, **{"metaclass": type}): # PYI059 59 + class C1(str, Generic[T], **{"metaclass": type}): # PYI059 -60 | ... | note: This is an unsafe fix and may change runtime behavior @@ -133,10 +117,8 @@ PYI059 [*] `Generic[]` should always be the last base class | help: Move `Generic[]` to the end | -61 | - - class C2(Generic[T], str, metaclass=type): # PYI059 +62 - class C2(Generic[T], str, metaclass=type): # PYI059 62 + class C2(str, Generic[T], metaclass=type): # PYI059 -63 | ... | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI059_PYI059.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI059_PYI059.pyi.snap index bc4a086f4c19d..c36ce35ef8c57 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI059_PYI059.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI059_PYI059.pyi.snap @@ -13,10 +13,8 @@ PYI059 [*] `Generic[]` should always be the last base class | help: Move `Generic[]` to the end | -7 | - - class LinkedList(Generic[T], Sized): # PYI059 +8 - class LinkedList(Generic[T], Sized): # PYI059 8 + class LinkedList(Sized, Generic[T]): # PYI059 -9 | def __init__(self) -> None: ... | note: This is an unsafe fix and may change runtime behavior @@ -36,12 +34,8 @@ PYI059 [*] `Generic[]` should always be the last base class | help: Move `Generic[]` to the end | -12 | class MyMapping( # PYI059 - - t.Generic[K, V], -13 | Iterable[Tuple[K, V]], - - Container[Tuple[K, V]], -14 + Container[Tuple[K, V]], t.Generic[K, V], -15 | ): +13 ~ Iterable[Tuple[K, V]], +14 ~ Container[Tuple[K, V]], t.Generic[K, V], | note: This is an unsafe fix and may change runtime behavior @@ -54,10 +48,8 @@ PYI059 [*] `Generic[]` should always be the last base class | ^^^^^^^^^^^^^^^^^^^^^ help: Move `Generic[]` to the end | -21 | # the Generic's position issue persists. - - class Foo(Generic, LinkedList): ... # PYI059 +22 - class Foo(Generic, LinkedList): ... # PYI059 22 + class Foo(LinkedList, Generic): ... # PYI059 -23 | | note: This is an unsafe fix and may change runtime behavior @@ -81,16 +73,10 @@ PYI059 [*] `Generic[]` should always be the last base class | help: Move `Generic[]` to the end | -27 | # Part 2 of multiline comment 1 - - Generic[T] # comment about Generic[T] # PYI059 - - # another comment? - - , # comment about the comma? -28 + # comment about the comma? +28 ~ # comment about the comma? 29 | # part 1 of multiline comment 2 30 | # part 2 of multiline comment 2 - - int, # comment about int -31 + int, Generic[T], # comment about int -32 | # yet another comment? +31 ~ int, Generic[T], # comment about int | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI061_PYI061.py.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI061_PYI061.py.snap index 346f1f57fbd47..3a8f4f73d82cd 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI061_PYI061.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI061_PYI061.py.snap @@ -10,10 +10,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -3 | - - def func1(arg1: Literal[None]): +4 - def func1(arg1: Literal[None]): 4 + def func1(arg1: None): -5 | ... | note: This is an unsafe fix and may change runtime behavior @@ -26,10 +24,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -7 | - - def func2(arg1: Literal[None] | int): +8 - def func2(arg1: Literal[None] | int): 8 + def func2(arg1: None | int): -9 | ... | note: This is an unsafe fix and may change runtime behavior @@ -42,10 +38,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -11 | - - def func3() -> Literal[None]: +12 - def func3() -> Literal[None]: 12 + def func3() -> None: -13 | ... | note: This is an unsafe fix and may change runtime behavior @@ -58,10 +52,8 @@ PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` | help: Replace with `Literal[...] | None` | -15 | - - def func4(arg1: Literal[int, None, float]): +16 - def func4(arg1: Literal[int, None, float]): 16 + def func4(arg1: Literal[int, float] | None): -17 | ... | note: This is an unsafe fix and may change runtime behavior @@ -74,10 +66,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -19 | - - def func5(arg1: Literal[None, None]): +20 - def func5(arg1: Literal[None, None]): 20 + def func5(arg1: None): -21 | ... | note: This is an unsafe fix and may change runtime behavior @@ -90,10 +80,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -19 | - - def func5(arg1: Literal[None, None]): +20 - def func5(arg1: Literal[None, None]): 20 + def func5(arg1: None): -21 | ... | note: This is an unsafe fix and may change runtime behavior @@ -109,14 +97,12 @@ PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` | help: Replace with `Literal[...] | None` | -23 | - - def func6(arg1: Literal[ - - "hello", - - None # Comment 1 - - , "world" - - ]): +24 - def func6(arg1: Literal[ +25 - "hello", +26 - None # Comment 1 +27 - , "world" +28 - ]): 24 + def func6(arg1: Literal["hello", "world"] | None): -25 | ... | note: This is an unsafe fix and may change runtime behavior @@ -131,12 +117,10 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -31 | - - def func7(arg1: Literal[ - - None # Comment 1 - - ]): +32 - def func7(arg1: Literal[ +33 - None # Comment 1 +34 - ]): 32 + def func7(arg1: None): -33 | ... | note: This is an unsafe fix and may change runtime behavior @@ -158,10 +142,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -41 | - - def func9(arg1: Union[Literal[None], None]): +42 - def func9(arg1: Union[Literal[None], None]): 42 + def func9(arg1: Union[None, None]): -43 | ... | note: This is an unsafe fix and may change runtime behavior @@ -175,10 +157,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -51 | # From flake8-pyi - - Literal[None] # Y061 None inside "Literal[]" expression. Replace with "None" +52 - Literal[None] # Y061 None inside "Literal[]" expression. Replace with "None" 52 + None # Y061 None inside "Literal[]" expression. Replace with "None" -53 | Literal[True, None] # Y061 None inside "Literal[]" expression. Replace with "Literal[True] | None" | note: This is an unsafe fix and may change runtime behavior @@ -194,10 +174,8 @@ PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` | help: Replace with `Literal[...] | None` | -52 | Literal[None] # Y061 None inside "Literal[]" expression. Replace with "None" - - Literal[True, None] # Y061 None inside "Literal[]" expression. Replace with "Literal[True] | None" +53 - Literal[True, None] # Y061 None inside "Literal[]" expression. Replace with "Literal[True] | None" 53 + Literal[True] | None # Y061 None inside "Literal[]" expression. Replace with "Literal[True] | None" -54 | | note: This is an unsafe fix and may change runtime behavior @@ -212,10 +190,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -61 | # only emit Y061... - - Literal[None, None] # Y061 None inside "Literal[]" expression. Replace with "None" +62 - Literal[None, None] # Y061 None inside "Literal[]" expression. Replace with "None" 62 + None # Y061 None inside "Literal[]" expression. Replace with "None" -63 | Literal[1, None, "foo", None] # Y061 None inside "Literal[]" expression. Replace with "Literal[1, 'foo'] | None" | note: This is an unsafe fix and may change runtime behavior @@ -230,10 +206,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -61 | # only emit Y061... - - Literal[None, None] # Y061 None inside "Literal[]" expression. Replace with "None" +62 - Literal[None, None] # Y061 None inside "Literal[]" expression. Replace with "None" 62 + None # Y061 None inside "Literal[]" expression. Replace with "None" -63 | Literal[1, None, "foo", None] # Y061 None inside "Literal[]" expression. Replace with "Literal[1, 'foo'] | None" | note: This is an unsafe fix and may change runtime behavior @@ -249,10 +223,8 @@ PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` | help: Replace with `Literal[...] | None` | -62 | Literal[None, None] # Y061 None inside "Literal[]" expression. Replace with "None" - - Literal[1, None, "foo", None] # Y061 None inside "Literal[]" expression. Replace with "Literal[1, 'foo'] | None" +63 - Literal[1, None, "foo", None] # Y061 None inside "Literal[]" expression. Replace with "Literal[1, 'foo'] | None" 63 + Literal[1, "foo"] | None # Y061 None inside "Literal[]" expression. Replace with "Literal[1, 'foo'] | None" -64 | | note: This is an unsafe fix and may change runtime behavior @@ -268,10 +240,8 @@ PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` | help: Replace with `Literal[...] | None` | -62 | Literal[None, None] # Y061 None inside "Literal[]" expression. Replace with "None" - - Literal[1, None, "foo", None] # Y061 None inside "Literal[]" expression. Replace with "Literal[1, 'foo'] | None" +63 - Literal[1, None, "foo", None] # Y061 None inside "Literal[]" expression. Replace with "Literal[1, 'foo'] | None" 63 + Literal[1, "foo"] | None # Y061 None inside "Literal[]" expression. Replace with "Literal[1, 'foo'] | None" -64 | | note: This is an unsafe fix and may change runtime behavior @@ -284,10 +254,8 @@ PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` | ^^^^ help: Replace with `Literal[...] | None` | -67 | # only emit Y062: - - Literal[None, True, None, True] # Y062 Duplicate "Literal[]" member "True" +68 - Literal[None, True, None, True] # Y062 Duplicate "Literal[]" member "True" 68 + Literal[True, True] | None # Y062 Duplicate "Literal[]" member "True" -69 | | note: This is an unsafe fix and may change runtime behavior @@ -300,10 +268,8 @@ PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` | ^^^^ help: Replace with `Literal[...] | None` | -67 | # only emit Y062: - - Literal[None, True, None, True] # Y062 Duplicate "Literal[]" member "True" +68 - Literal[None, True, None, True] # Y062 Duplicate "Literal[]" member "True" 68 + Literal[True, True] | None # Y062 Duplicate "Literal[]" member "True" -69 | | note: This is an unsafe fix and may change runtime behavior @@ -341,10 +307,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -73 | y: None | Literal[None] - - z: Union[Literal[None], None] +74 - z: Union[Literal[None], None] 74 + z: Union[None, None] -75 | | note: This is an unsafe fix and may change runtime behavior @@ -417,10 +381,8 @@ PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` | help: Replace with `Literal[...] | None` | -82 | # Test cases for operator precedence issue (https://github.com/astral-sh/ruff/issues/20265) - - print(Literal[1, None].__dict__) # Should become (Literal[1] | None).__dict__ +83 - print(Literal[1, None].__dict__) # Should become (Literal[1] | None).__dict__ 83 + print((Literal[1] | None).__dict__) # Should become (Literal[1] | None).__dict__ -84 | print(Literal[1, None].method()) # Should become (Literal[1] | None).method() | note: This is an unsafe fix and may change runtime behavior @@ -436,10 +398,8 @@ PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` | help: Replace with `Literal[...] | None` | -83 | print(Literal[1, None].__dict__) # Should become (Literal[1] | None).__dict__ - - print(Literal[1, None].method()) # Should become (Literal[1] | None).method() +84 - print(Literal[1, None].method()) # Should become (Literal[1] | None).method() 84 + print((Literal[1] | None).method()) # Should become (Literal[1] | None).method() -85 | print(Literal[1, None][0]) # Should become (Literal[1] | None)[0] | note: This is an unsafe fix and may change runtime behavior @@ -455,10 +415,8 @@ PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` | help: Replace with `Literal[...] | None` | -84 | print(Literal[1, None].method()) # Should become (Literal[1] | None).method() - - print(Literal[1, None][0]) # Should become (Literal[1] | None)[0] +85 - print(Literal[1, None][0]) # Should become (Literal[1] | None)[0] 85 + print((Literal[1] | None)[0]) # Should become (Literal[1] | None)[0] -86 | print(Literal[1, None] + 1) # Should become (Literal[1] | None) + 1 | note: This is an unsafe fix and may change runtime behavior @@ -474,10 +432,8 @@ PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` | help: Replace with `Literal[...] | None` | -85 | print(Literal[1, None][0]) # Should become (Literal[1] | None)[0] - - print(Literal[1, None] + 1) # Should become (Literal[1] | None) + 1 +86 - print(Literal[1, None] + 1) # Should become (Literal[1] | None) + 1 86 + print((Literal[1] | None) + 1) # Should become (Literal[1] | None) + 1 -87 | print(Literal[1, None] * 2) # Should become (Literal[1] | None) * 2 | note: This is an unsafe fix and may change runtime behavior @@ -492,10 +448,8 @@ PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` | help: Replace with `Literal[...] | None` | -86 | print(Literal[1, None] + 1) # Should become (Literal[1] | None) + 1 - - print(Literal[1, None] * 2) # Should become (Literal[1] | None) * 2 +87 - print(Literal[1, None] * 2) # Should become (Literal[1] | None) * 2 87 + print((Literal[1] | None) * 2) # Should become (Literal[1] | None) * 2 -88 | print((Literal[1, None]).__dict__) # Should become ((Literal[1] | None)).__dict__ | note: This is an unsafe fix and may change runtime behavior @@ -511,10 +465,8 @@ PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` | help: Replace with `Literal[...] | None` | -87 | print(Literal[1, None] * 2) # Should become (Literal[1] | None) * 2 - - print((Literal[1, None]).__dict__) # Should become ((Literal[1] | None)).__dict__ +88 - print((Literal[1, None]).__dict__) # Should become ((Literal[1] | None)).__dict__ 88 + print((Literal[1] | None).__dict__) # Should become ((Literal[1] | None)).__dict__ -89 | | note: This is an unsafe fix and may change runtime behavior @@ -527,8 +479,7 @@ PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` | ^^^^ help: Replace with `Literal[...] | None` | -91 | # Rewriting this changes `typing.get_args(options)` at runtime, so the fix is unsafe. - - options = Literal["foo", "bar", None] +92 - options = Literal["foo", "bar", None] 92 + options = Literal["foo", "bar"] | None | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI061_PYI061.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI061_PYI061.pyi.snap index 86a44243cce59..9ea46cde17049 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI061_PYI061.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI061_PYI061.pyi.snap @@ -8,10 +8,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | ^^^^ help: Replace with `None` | -3 | - - def func1(arg1: Literal[None]): ... +4 - def func1(arg1: Literal[None]): ... 4 + def func1(arg1: None): ... -5 | | PYI061 [*] Use `None` rather than `Literal[None]` @@ -21,10 +19,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | ^^^^ help: Replace with `None` | -6 | - - def func2(arg1: Literal[None] | int): ... +7 - def func2(arg1: Literal[None] | int): ... 7 + def func2(arg1: None | int): ... -8 | | PYI061 [*] Use `None` rather than `Literal[None]` @@ -34,10 +30,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | ^^^^ help: Replace with `None` | -9 | - - def func3() -> Literal[None]: ... +10 - def func3() -> Literal[None]: ... 10 + def func3() -> None: ... -11 | | PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` @@ -47,10 +41,8 @@ PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` | ^^^^ help: Replace with `Literal[...] | None` | -12 | - - def func4(arg1: Literal[int, None, float]): ... +13 - def func4(arg1: Literal[int, None, float]): ... 13 + def func4(arg1: Literal[int, float] | None): ... -14 | | PYI061 [*] Use `None` rather than `Literal[None]` @@ -60,10 +52,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | ^^^^ help: Replace with `None` | -15 | - - def func5(arg1: Literal[None, None]): ... +16 - def func5(arg1: Literal[None, None]): ... 16 + def func5(arg1: None): ... -17 | | PYI061 [*] Use `None` rather than `Literal[None]` @@ -73,10 +63,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | ^^^^ help: Replace with `None` | -15 | - - def func5(arg1: Literal[None, None]): ... +16 - def func5(arg1: Literal[None, None]): ... 16 + def func5(arg1: None): ... -17 | | PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` @@ -91,14 +79,12 @@ PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` | help: Replace with `Literal[...] | None` | -18 | - - def func6(arg1: Literal[ - - "hello", - - None # Comment 1 - - , "world" - - ]): ... +19 - def func6(arg1: Literal[ +20 - "hello", +21 - None # Comment 1 +22 - , "world" +23 - ]): ... 19 + def func6(arg1: Literal["hello", "world"] | None): ... -20 | | note: This is an unsafe fix and may change runtime behavior @@ -112,12 +98,10 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -25 | - - def func7(arg1: Literal[ - - None # Comment 1 - - ]): ... +26 - def func7(arg1: Literal[ +27 - None # Comment 1 +28 - ]): ... 26 + def func7(arg1: None): ... -27 | | note: This is an unsafe fix and may change runtime behavior @@ -135,10 +119,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | ^^^^ help: Replace with `None` | -33 | - - def func9(arg1: Union[Literal[None], None]): ... +34 - def func9(arg1: Union[Literal[None], None]): ... 34 + def func9(arg1: Union[None, None]): ... -35 | | PYI061 [*] Use `None` rather than `Literal[None]` @@ -151,10 +133,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -41 | # From flake8-pyi - - Literal[None] # PYI061 None inside "Literal[]" expression. Replace with "None" +42 - Literal[None] # PYI061 None inside "Literal[]" expression. Replace with "None" 42 + None # PYI061 None inside "Literal[]" expression. Replace with "None" -43 | Literal[True, None] # PYI061 None inside "Literal[]" expression. Replace with "Literal[True] | None" | PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` @@ -166,10 +146,8 @@ PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` | ^^^^ help: Replace with `Literal[...] | None` | -42 | Literal[None] # PYI061 None inside "Literal[]" expression. Replace with "None" - - Literal[True, None] # PYI061 None inside "Literal[]" expression. Replace with "Literal[True] | None" +43 - Literal[True, None] # PYI061 None inside "Literal[]" expression. Replace with "Literal[True] | None" 43 + Literal[True] | None # PYI061 None inside "Literal[]" expression. Replace with "Literal[True] | None" -44 | | PYI061 Use `None` rather than `Literal[None]` @@ -206,10 +184,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -48 | y: None | Literal[None] - - z: Union[Literal[None], None] +49 - z: Union[Literal[None], None] 49 + z: Union[None, None] -50 | | PYI061 Use `None` rather than `Literal[None]` diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI062_PYI062.py.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI062_PYI062.py.snap index 5a7f193162967..595bda1188a4c 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI062_PYI062.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI062_PYI062.py.snap @@ -13,10 +13,8 @@ PYI062 [*] Duplicate literal member `True` | help: Remove duplicates | -4 | - - x: Literal[True, False, True, False] # PYI062 twice here +5 - x: Literal[True, False, True, False] # PYI062 twice here 5 + x: Literal[True, False] # PYI062 twice here -6 | | PYI062 [*] Duplicate literal member `False` @@ -31,10 +29,8 @@ PYI062 [*] Duplicate literal member `False` | help: Remove duplicates | -4 | - - x: Literal[True, False, True, False] # PYI062 twice here +5 - x: Literal[True, False, True, False] # PYI062 twice here 5 + x: Literal[True, False] # PYI062 twice here -6 | | PYI062 [*] Duplicate literal member `1` @@ -49,10 +45,8 @@ PYI062 [*] Duplicate literal member `1` | help: Remove duplicates | -6 | - - y: Literal[1, print("hello"), 3, Literal[4, 1]] # PYI062 on the last 1 +7 - y: Literal[1, print("hello"), 3, Literal[4, 1]] # PYI062 on the last 1 7 + y: Literal[1, print("hello"), 3, 4] # PYI062 on the last 1 -8 | | PYI062 [*] Duplicate literal member `{1, 3, 5}` @@ -66,12 +60,10 @@ PYI062 [*] Duplicate literal member `{1, 3, 5}` 11 | Literal[1, Literal[1]] # once | help: Remove duplicates - | -8 | - - z: Literal[{1, 3, 5}, "foobar", {1,3,5}] # PYI062 on the set literal -9 + z: Literal[{1, 3, 5}, "foobar"] # PYI062 on the set literal -10 | - | + | +9 - z: Literal[{1, 3, 5}, "foobar", {1,3,5}] # PYI062 on the set literal +9 + z: Literal[{1, 3, 5}, "foobar"] # PYI062 on the set literal + | PYI062 [*] Duplicate literal member `1` --> PYI062.py:11:20 @@ -85,10 +77,8 @@ PYI062 [*] Duplicate literal member `1` | help: Remove duplicates | -10 | - - Literal[1, Literal[1]] # once +11 - Literal[1, Literal[1]] # once 11 + Literal[1] # once -12 | Literal[1, 2, Literal[1, 2]] # twice | PYI062 [*] Duplicate literal member `1` @@ -102,10 +92,8 @@ PYI062 [*] Duplicate literal member `1` | help: Remove duplicates | -11 | Literal[1, Literal[1]] # once - - Literal[1, 2, Literal[1, 2]] # twice +12 - Literal[1, 2, Literal[1, 2]] # twice 12 + Literal[1, 2] # twice -13 | Literal[1, Literal[1], Literal[1]] # twice | PYI062 [*] Duplicate literal member `2` @@ -119,10 +107,8 @@ PYI062 [*] Duplicate literal member `2` | help: Remove duplicates | -11 | Literal[1, Literal[1]] # once - - Literal[1, 2, Literal[1, 2]] # twice +12 - Literal[1, 2, Literal[1, 2]] # twice 12 + Literal[1, 2] # twice -13 | Literal[1, Literal[1], Literal[1]] # twice | PYI062 [*] Duplicate literal member `1` @@ -137,10 +123,8 @@ PYI062 [*] Duplicate literal member `1` | help: Remove duplicates | -12 | Literal[1, 2, Literal[1, 2]] # twice - - Literal[1, Literal[1], Literal[1]] # twice +13 - Literal[1, Literal[1], Literal[1]] # twice 13 + Literal[1] # twice -14 | Literal[1, Literal[2], Literal[2]] # once | PYI062 [*] Duplicate literal member `1` @@ -155,10 +139,8 @@ PYI062 [*] Duplicate literal member `1` | help: Remove duplicates | -12 | Literal[1, 2, Literal[1, 2]] # twice - - Literal[1, Literal[1], Literal[1]] # twice +13 - Literal[1, Literal[1], Literal[1]] # twice 13 + Literal[1] # twice -14 | Literal[1, Literal[2], Literal[2]] # once | PYI062 [*] Duplicate literal member `2` @@ -173,10 +155,8 @@ PYI062 [*] Duplicate literal member `2` | help: Remove duplicates | -13 | Literal[1, Literal[1], Literal[1]] # twice - - Literal[1, Literal[2], Literal[2]] # once +14 - Literal[1, Literal[2], Literal[2]] # once 14 + Literal[1, 2] # once -15 | t.Literal[1, t.Literal[2, t.Literal[1]]] # once | PYI062 [*] Duplicate literal member `1` @@ -191,10 +171,8 @@ PYI062 [*] Duplicate literal member `1` | help: Remove duplicates | -14 | Literal[1, Literal[2], Literal[2]] # once - - t.Literal[1, t.Literal[2, t.Literal[1]]] # once +15 - t.Literal[1, t.Literal[2, t.Literal[1]]] # once 15 + t.Literal[1, 2] # once -16 | typing_extensions.Literal[1, 1, 1] # twice | PYI062 [*] Duplicate literal member `1` @@ -209,10 +187,8 @@ PYI062 [*] Duplicate literal member `1` | help: Remove duplicates | -15 | t.Literal[1, t.Literal[2, t.Literal[1]]] # once - - typing_extensions.Literal[1, 1, 1] # twice +16 - typing_extensions.Literal[1, 1, 1] # twice 16 + typing_extensions.Literal[1] # twice -17 | Literal[ | PYI062 [*] Duplicate literal member `1` @@ -227,10 +203,8 @@ PYI062 [*] Duplicate literal member `1` | help: Remove duplicates | -15 | t.Literal[1, t.Literal[2, t.Literal[1]]] # once - - typing_extensions.Literal[1, 1, 1] # twice +16 - typing_extensions.Literal[1, 1, 1] # twice 16 + typing_extensions.Literal[1] # twice -17 | Literal[ | PYI062 [*] Duplicate literal member `1` @@ -245,15 +219,13 @@ PYI062 [*] Duplicate literal member `1` | help: Remove duplicates | -16 | typing_extensions.Literal[1, 1, 1] # twice - - Literal[ - - 1, # comment - - Literal[ # another comment - - 1 - - ] - - ] # once +17 - Literal[ +18 - 1, # comment +19 - Literal[ # another comment +20 - 1 +21 - ] +22 - ] # once 17 + Literal[1] # once -18 | | note: This is an unsafe fix and may change runtime behavior @@ -268,10 +240,8 @@ PYI062 [*] Duplicate literal member `True` | help: Remove duplicates | -24 | # Ensure issue is only raised once, even on nested literals - - MyType = Literal["foo", Literal[True, False, True], "bar"] # PYI062 +25 - MyType = Literal["foo", Literal[True, False, True], "bar"] # PYI062 25 + MyType = Literal["foo", True, False, "bar"] # PYI062 -26 | | PYI062 [*] Duplicate literal member `1` @@ -285,10 +255,8 @@ PYI062 [*] Duplicate literal member `1` | help: Remove duplicates | -31 | Literal[Literal[1]] # no duplicate - - Literal[Literal[Literal[1], Literal[1]]] # once +32 - Literal[Literal[Literal[1], Literal[1]]] # once 32 + Literal[1] # once -33 | Literal[Literal[1], Literal[Literal[Literal[1]]]] # once | PYI062 [*] Duplicate literal member `1` @@ -300,7 +268,6 @@ PYI062 [*] Duplicate literal member `1` | ^ help: Remove duplicates | -32 | Literal[Literal[Literal[1], Literal[1]]] # once - - Literal[Literal[1], Literal[Literal[Literal[1]]]] # once +33 - Literal[Literal[1], Literal[Literal[Literal[1]]]] # once 33 + Literal[1] # once | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI062_PYI062.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI062_PYI062.pyi.snap index 28c3c6aa97402..7b42268a37318 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI062_PYI062.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI062_PYI062.pyi.snap @@ -13,10 +13,8 @@ PYI062 [*] Duplicate literal member `True` | help: Remove duplicates | -4 | - - x: Literal[True, False, True, False] # PYI062 twice here +5 - x: Literal[True, False, True, False] # PYI062 twice here 5 + x: Literal[True, False] # PYI062 twice here -6 | | PYI062 [*] Duplicate literal member `False` @@ -31,10 +29,8 @@ PYI062 [*] Duplicate literal member `False` | help: Remove duplicates | -4 | - - x: Literal[True, False, True, False] # PYI062 twice here +5 - x: Literal[True, False, True, False] # PYI062 twice here 5 + x: Literal[True, False] # PYI062 twice here -6 | | PYI062 [*] Duplicate literal member `1` @@ -49,10 +45,8 @@ PYI062 [*] Duplicate literal member `1` | help: Remove duplicates | -6 | - - y: Literal[1, print("hello"), 3, Literal[4, 1]] # PYI062 on the last 1 +7 - y: Literal[1, print("hello"), 3, Literal[4, 1]] # PYI062 on the last 1 7 + y: Literal[1, print("hello"), 3, 4] # PYI062 on the last 1 -8 | | PYI062 [*] Duplicate literal member `{1, 3, 5}` @@ -66,12 +60,10 @@ PYI062 [*] Duplicate literal member `{1, 3, 5}` 11 | Literal[1, Literal[1]] # once | help: Remove duplicates - | -8 | - - z: Literal[{1, 3, 5}, "foobar", {1,3,5}] # PYI062 on the set literal -9 + z: Literal[{1, 3, 5}, "foobar"] # PYI062 on the set literal -10 | - | + | +9 - z: Literal[{1, 3, 5}, "foobar", {1,3,5}] # PYI062 on the set literal +9 + z: Literal[{1, 3, 5}, "foobar"] # PYI062 on the set literal + | PYI062 [*] Duplicate literal member `1` --> PYI062.pyi:11:20 @@ -85,10 +77,8 @@ PYI062 [*] Duplicate literal member `1` | help: Remove duplicates | -10 | - - Literal[1, Literal[1]] # once +11 - Literal[1, Literal[1]] # once 11 + Literal[1] # once -12 | Literal[1, 2, Literal[1, 2]] # twice | PYI062 [*] Duplicate literal member `1` @@ -102,10 +92,8 @@ PYI062 [*] Duplicate literal member `1` | help: Remove duplicates | -11 | Literal[1, Literal[1]] # once - - Literal[1, 2, Literal[1, 2]] # twice +12 - Literal[1, 2, Literal[1, 2]] # twice 12 + Literal[1, 2] # twice -13 | Literal[1, Literal[1], Literal[1]] # twice | PYI062 [*] Duplicate literal member `2` @@ -119,10 +107,8 @@ PYI062 [*] Duplicate literal member `2` | help: Remove duplicates | -11 | Literal[1, Literal[1]] # once - - Literal[1, 2, Literal[1, 2]] # twice +12 - Literal[1, 2, Literal[1, 2]] # twice 12 + Literal[1, 2] # twice -13 | Literal[1, Literal[1], Literal[1]] # twice | PYI062 [*] Duplicate literal member `1` @@ -137,10 +123,8 @@ PYI062 [*] Duplicate literal member `1` | help: Remove duplicates | -12 | Literal[1, 2, Literal[1, 2]] # twice - - Literal[1, Literal[1], Literal[1]] # twice +13 - Literal[1, Literal[1], Literal[1]] # twice 13 + Literal[1] # twice -14 | Literal[1, Literal[2], Literal[2]] # once | PYI062 [*] Duplicate literal member `1` @@ -155,10 +139,8 @@ PYI062 [*] Duplicate literal member `1` | help: Remove duplicates | -12 | Literal[1, 2, Literal[1, 2]] # twice - - Literal[1, Literal[1], Literal[1]] # twice +13 - Literal[1, Literal[1], Literal[1]] # twice 13 + Literal[1] # twice -14 | Literal[1, Literal[2], Literal[2]] # once | PYI062 [*] Duplicate literal member `2` @@ -173,10 +155,8 @@ PYI062 [*] Duplicate literal member `2` | help: Remove duplicates | -13 | Literal[1, Literal[1], Literal[1]] # twice - - Literal[1, Literal[2], Literal[2]] # once +14 - Literal[1, Literal[2], Literal[2]] # once 14 + Literal[1, 2] # once -15 | t.Literal[1, t.Literal[2, t.Literal[1]]] # once | PYI062 [*] Duplicate literal member `1` @@ -191,10 +171,8 @@ PYI062 [*] Duplicate literal member `1` | help: Remove duplicates | -14 | Literal[1, Literal[2], Literal[2]] # once - - t.Literal[1, t.Literal[2, t.Literal[1]]] # once +15 - t.Literal[1, t.Literal[2, t.Literal[1]]] # once 15 + t.Literal[1, 2] # once -16 | typing_extensions.Literal[1, 1, 1] # twice | PYI062 [*] Duplicate literal member `1` @@ -209,10 +187,8 @@ PYI062 [*] Duplicate literal member `1` | help: Remove duplicates | -15 | t.Literal[1, t.Literal[2, t.Literal[1]]] # once - - typing_extensions.Literal[1, 1, 1] # twice +16 - typing_extensions.Literal[1, 1, 1] # twice 16 + typing_extensions.Literal[1] # twice -17 | Literal[ | PYI062 [*] Duplicate literal member `1` @@ -227,10 +203,8 @@ PYI062 [*] Duplicate literal member `1` | help: Remove duplicates | -15 | t.Literal[1, t.Literal[2, t.Literal[1]]] # once - - typing_extensions.Literal[1, 1, 1] # twice +16 - typing_extensions.Literal[1, 1, 1] # twice 16 + typing_extensions.Literal[1] # twice -17 | Literal[ | PYI062 [*] Duplicate literal member `1` @@ -245,15 +219,13 @@ PYI062 [*] Duplicate literal member `1` | help: Remove duplicates | -16 | typing_extensions.Literal[1, 1, 1] # twice - - Literal[ - - 1, # comment - - Literal[ # another comment - - 1 - - ] - - ] # once +17 - Literal[ +18 - 1, # comment +19 - Literal[ # another comment +20 - 1 +21 - ] +22 - ] # once 17 + Literal[1] # once -18 | | note: This is an unsafe fix and may change runtime behavior @@ -268,10 +240,8 @@ PYI062 [*] Duplicate literal member `True` | help: Remove duplicates | -24 | # Ensure issue is only raised once, even on nested literals - - MyType = Literal["foo", Literal[True, False, True], "bar"] # PYI062 +25 - MyType = Literal["foo", Literal[True, False, True], "bar"] # PYI062 25 + MyType = Literal["foo", True, False, "bar"] # PYI062 -26 | | PYI062 [*] Duplicate literal member `1` @@ -285,10 +255,8 @@ PYI062 [*] Duplicate literal member `1` | help: Remove duplicates | -31 | Literal[Literal[1]] # no duplicate - - Literal[Literal[Literal[1], Literal[1]]] # once +32 - Literal[Literal[Literal[1], Literal[1]]] # once 32 + Literal[1] # once -33 | Literal[Literal[1], Literal[Literal[Literal[1]]]] # once | PYI062 [*] Duplicate literal member `1` @@ -300,7 +268,6 @@ PYI062 [*] Duplicate literal member `1` | ^ help: Remove duplicates | -32 | Literal[Literal[Literal[1], Literal[1]]] # once - - Literal[Literal[1], Literal[Literal[Literal[1]]]] # once +33 - Literal[Literal[1], Literal[Literal[Literal[1]]]] # once 33 + Literal[1] # once | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI064_PYI064.py.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI064_PYI064.py.snap index d92f7f9cd0741..a8aa90dc4fbd2 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI064_PYI064.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI064_PYI064.py.snap @@ -13,10 +13,8 @@ PYI064 [*] `Final[Literal[True]]` can be replaced with a bare `Final` | help: Replace with `Final` | -2 | - - x: Final[Literal[True]] = True # PYI064 +3 - x: Final[Literal[True]] = True # PYI064 3 + x: Final = True # PYI064 -4 | y: Final[Literal[None]] = None # PYI064 | PYI064 [*] `Final[Literal[None]]` can be replaced with a bare `Final` @@ -30,10 +28,8 @@ PYI064 [*] `Final[Literal[None]]` can be replaced with a bare `Final` | help: Replace with `Final` | -3 | x: Final[Literal[True]] = True # PYI064 - - y: Final[Literal[None]] = None # PYI064 +4 - y: Final[Literal[None]] = None # PYI064 4 + y: Final = None # PYI064 -5 | z: Final[Literal[ # PYI064 | PYI064 [*] `Final[Literal[...]]` can be replaced with a bare `Final` @@ -50,12 +46,10 @@ PYI064 [*] `Final[Literal[...]]` can be replaced with a bare `Final` | help: Replace with `Final` | -4 | y: Final[Literal[None]] = None # PYI064 - - z: Final[Literal[ # PYI064 - - "this is a really long literal, that won't be rendered in the issue text" - - ]] = "this is a really long literal, that won't be rendered in the issue text" +5 - z: Final[Literal[ # PYI064 +6 - "this is a really long literal, that won't be rendered in the issue text" +7 - ]] = "this is a really long literal, that won't be rendered in the issue text" 5 + z: Final = "this is a really long literal, that won't be rendered in the issue text" -6 | | PYI064 [*] `Final[Literal[123]]` can be replaced with a bare `Final` @@ -69,10 +63,8 @@ PYI064 [*] `Final[Literal[123]]` can be replaced with a bare `Final` | help: Replace with `Final` | -9 | # This should be fixable, and marked as safe - - w1: Final[Literal[123]] # PYI064 +10 - w1: Final[Literal[123]] # PYI064 10 + w1: Final = 123 # PYI064 -11 | | PYI064 `Final[Literal[123]]` can be replaced with a bare `Final` diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI064_PYI064.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI064_PYI064.pyi.snap index 40368d2c2ef45..90dd7ab479007 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI064_PYI064.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI064_PYI064.pyi.snap @@ -13,10 +13,8 @@ PYI064 [*] `Final[Literal[True]]` can be replaced with a bare `Final` | help: Replace with `Final` | -2 | - - x: Final[Literal[True]] # PYI064 +3 - x: Final[Literal[True]] # PYI064 3 + x: Final = True # PYI064 -4 | y: Final[Literal[None]] = None # PYI064 | PYI064 [*] `Final[Literal[None]]` can be replaced with a bare `Final` @@ -29,10 +27,8 @@ PYI064 [*] `Final[Literal[None]]` can be replaced with a bare `Final` | help: Replace with `Final` | -3 | x: Final[Literal[True]] # PYI064 - - y: Final[Literal[None]] = None # PYI064 +4 - y: Final[Literal[None]] = None # PYI064 4 + y: Final = None # PYI064 -5 | z: Final[Literal["this is a really long literal, that won't be rendered in the issue text"]] # PYI064 | PYI064 [*] `Final[Literal[...]]` can be replaced with a bare `Final` @@ -47,10 +43,8 @@ PYI064 [*] `Final[Literal[...]]` can be replaced with a bare `Final` | help: Replace with `Final` | -4 | y: Final[Literal[None]] = None # PYI064 - - z: Final[Literal["this is a really long literal, that won't be rendered in the issue text"]] # PYI064 +5 - z: Final[Literal["this is a really long literal, that won't be rendered in the issue text"]] # PYI064 5 + z: Final = "this is a really long literal, that won't be rendered in the issue text" # PYI064 -6 | | PYI064 [*] `Final[Literal[123]]` can be replaced with a bare `Final` @@ -64,10 +58,8 @@ PYI064 [*] `Final[Literal[123]]` can be replaced with a bare `Final` | help: Replace with `Final` | -7 | # This should be fixable, and marked as safe - - w1: Final[Literal[123]] # PYI064 +8 - w1: Final[Literal[123]] # PYI064 8 + w1: Final = 123 # PYI064 -9 | | PYI064 `Final[Literal[123]]` can be replaced with a bare `Final` diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__preview_PYI041_PYI041_3.py.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__preview_PYI041_PYI041_3.py.snap index 61f4a1caa0bfb..4e24913b736e7 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__preview_PYI041_PYI041_3.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__preview_PYI041_PYI041_3.py.snap @@ -19,10 +19,8 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -22 | - - def f0(arg1: "float | int") -> "None": +23 - def f0(arg1: "float | int") -> "None": 23 + def f0(arg1: "float") -> "None": -24 | ... | note: This is an unsafe fix and may change runtime behavior @@ -36,10 +34,8 @@ PYI041 [*] Use `complex` instead of `float | complex` | help: Remove redundant type | -26 | - - def f1(arg1: "float", *, arg2: "float | list[str] | type[bool] | complex") -> "None": +27 - def f1(arg1: "float", *, arg2: "float | list[str] | type[bool] | complex") -> "None": 27 + def f1(arg1: "float", *, arg2: "list[str] | type[bool] | complex") -> "None": -28 | ... | note: This is an unsafe fix and may change runtime behavior @@ -53,10 +49,8 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -30 | - - def f2(arg1: "int", /, arg2: "int | int | float") -> "None": +31 - def f2(arg1: "int", /, arg2: "int | int | float") -> "None": 31 + def f2(arg1: "int", /, arg2: "float") -> "None": -32 | ... | note: This is an unsafe fix and may change runtime behavior @@ -70,10 +64,8 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -34 | - - def f3(arg1: "int", *args: "Union[int | int | float]") -> "None": +35 - def f3(arg1: "int", *args: "Union[int | int | float]") -> "None": 35 + def f3(arg1: "int", *args: "float") -> "None": -36 | ... | note: This is an unsafe fix and may change runtime behavior @@ -87,10 +79,8 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -38 | - - async def f4(**kwargs: "int | int | float") -> "None": +39 - async def f4(**kwargs: "int | int | float") -> "None": 39 + async def f4(**kwargs: "float") -> "None": -40 | ... | note: This is an unsafe fix and may change runtime behavior @@ -104,10 +94,8 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -42 | - - def f5(arg1: "int", *args: "Union[int, int, float]") -> "None": +43 - def f5(arg1: "int", *args: "Union[int, int, float]") -> "None": 43 + def f5(arg1: "int", *args: "float") -> "None": -44 | ... | note: This is an unsafe fix and may change runtime behavior @@ -121,10 +109,8 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -46 | - - def f6(arg1: "int", *args: "Union[Union[int, int, float]]") -> "None": +47 - def f6(arg1: "int", *args: "Union[Union[int, int, float]]") -> "None": 47 + def f6(arg1: "int", *args: "float") -> "None": -48 | ... | note: This is an unsafe fix and may change runtime behavior @@ -138,10 +124,8 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -50 | - - def f7(arg1: "int", *args: "Union[Union[Union[int, int, float]]]") -> "None": +51 - def f7(arg1: "int", *args: "Union[Union[Union[int, int, float]]]") -> "None": 51 + def f7(arg1: "int", *args: "float") -> "None": -52 | ... | note: This is an unsafe fix and may change runtime behavior @@ -155,10 +139,8 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -54 | - - def f8(arg1: "int", *args: "Union[Union[Union[int | int | float]]]") -> "None": +55 - def f8(arg1: "int", *args: "Union[Union[Union[int | int | float]]]") -> "None": 55 + def f8(arg1: "int", *args: "float") -> "None": -56 | ... | note: This is an unsafe fix and may change runtime behavior @@ -177,12 +159,10 @@ PYI041 [*] Use `complex` instead of `int | float | complex` | help: Remove redundant type | -59 | def f9( - - arg: """Union[ # comment - - float, # another - - complex, int]""" +60 - arg: """Union[ # comment +61 - float, # another +62 - complex, int]""" 60 + arg: """complex""" -61 | ) -> "None": | note: This is an unsafe fix and may change runtime behavior @@ -201,10 +181,8 @@ PYI041 [*] Use `complex` instead of `int | float | complex` | help: Remove redundant type | -67 | arg: """ - - int | # comment - - float | # another -68 | complex +68 - int | # comment +69 - float | # another | note: This is an unsafe fix and may change runtime behavior @@ -220,10 +198,8 @@ PYI041 [*] Use `complex` instead of `int | float | complex` | help: Remove redundant type | -79 | - - def bad(self, arg: "int | float | complex") -> "None": +80 - def bad(self, arg: "int | float | complex") -> "None": 80 + def bad(self, arg: "complex") -> "None": -81 | ... | note: This is an unsafe fix and may change runtime behavior @@ -239,10 +215,8 @@ PYI041 [*] Use `complex` instead of `int | float | complex` | help: Remove redundant type | -82 | - - def bad2(self, arg: "int | Union[float, complex]") -> "None": +83 - def bad2(self, arg: "int | Union[float, complex]") -> "None": 83 + def bad2(self, arg: "complex") -> "None": -84 | ... | note: This is an unsafe fix and may change runtime behavior @@ -258,10 +232,8 @@ PYI041 [*] Use `complex` instead of `int | float | complex` | help: Remove redundant type | -85 | - - def bad3(self, arg: "Union[Union[float, complex], int]") -> "None": +86 - def bad3(self, arg: "Union[Union[float, complex], int]") -> "None": 86 + def bad3(self, arg: "complex") -> "None": -87 | ... | note: This is an unsafe fix and may change runtime behavior @@ -277,10 +249,8 @@ PYI041 [*] Use `complex` instead of `int | float | complex` | help: Remove redundant type | -88 | - - def bad4(self, arg: "Union[float | complex, int]") -> "None": +89 - def bad4(self, arg: "Union[float | complex, int]") -> "None": 89 + def bad4(self, arg: "complex") -> "None": -90 | ... | note: This is an unsafe fix and may change runtime behavior @@ -296,10 +266,8 @@ PYI041 [*] Use `complex` instead of `int | float | complex` | help: Remove redundant type | -91 | - - def bad5(self, arg: "int | (float | complex)") -> "None": +92 - def bad5(self, arg: "int | (float | complex)") -> "None": 92 + def bad5(self, arg: "complex") -> "None": -93 | ... | note: This is an unsafe fix and may change runtime behavior @@ -328,10 +296,8 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -103 | - - def f2(self, arg: "None | int | None | float" = None) -> "None": ... # PYI041 - with fix +104 - def f2(self, arg: "None | int | None | float" = None) -> "None": ... # PYI041 - with fix 104 + def f2(self, arg: "None | None | float" = None) -> "None": ... # PYI041 - with fix -105 | | note: This is an unsafe fix and may change runtime behavior @@ -347,10 +313,8 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | -110 | - - def f3(self, arg: "None | float | None | int | None" = None) -> "None": # PYI041 - with fix +111 - def f3(self, arg: "None | float | None | int | None" = None) -> "None": # PYI041 - with fix 111 + def f3(self, arg: "None | float | None | None" = None) -> "None": # PYI041 - with fix -112 | pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__preview_PYI041_PYI041_4.py.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__preview_PYI041_PYI041_4.py.snap index 917bc5aa77e57..0636371673b69 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__preview_PYI041_PYI041_4.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__preview_PYI041_PYI041_4.py.snap @@ -32,10 +32,11 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | +1 ~ from typing import Union as Uno +2 | +3 | 4 | def f1(a: "U" "no[int, fl" "oat, Foo]") -> "None": ... - - def f2(a: "Uno[int, float, Foo]") -> "None": ... -5 + def f2(a: "Uno[float, Foo]") -> "None": ... -6 | def f3(a: """Uno[int, float, Foo]""") -> "None": ... +5 ~ def f2(a: "Uno[float, Foo]") -> "None": ... | note: This is an unsafe fix and may change runtime behavior @@ -52,10 +53,11 @@ PYI041 [*] Use `float` instead of `int | float` | help: Remove redundant type | +1 ~ from typing import Union as Uno +2 | +… 5 | def f2(a: "Uno[int, float, Foo]") -> "None": ... - - def f3(a: """Uno[int, float, Foo]""") -> "None": ... -6 + def f3(a: """Uno[float, Foo]""") -> "None": ... -7 | def f4(a: "Uno[in\ +6 ~ def f3(a: """Uno[float, Foo]""") -> "None": ... | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__py38_PYI026_PYI026.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__py38_PYI026_PYI026.pyi.snap index 68a2ca447fa22..fb819455a6a90 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__py38_PYI026_PYI026.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__py38_PYI026_PYI026.pyi.snap @@ -13,12 +13,9 @@ PYI026 [*] Use `typing_extensions.TypeAlias` for type alias, e.g., `NewAny: Type | help: Add `TypeAlias` annotation | -1 | from typing import Literal, Any 2 + from typing_extensions import TypeAlias -3 | - - NewAny = Any -4 + NewAny: TypeAlias = Any -5 | OptionalStr = typing.Optional[str] +3 + +4 ~ NewAny: TypeAlias = Any | PYI026 [*] Use `typing_extensions.TypeAlias` for type alias, e.g., `OptionalStr: TypeAlias = typing.Optional[str]` @@ -32,13 +29,10 @@ PYI026 [*] Use `typing_extensions.TypeAlias` for type alias, e.g., `OptionalStr: | help: Add `TypeAlias` annotation | -1 | from typing import Literal, Any 2 + from typing_extensions import TypeAlias -3 | +3 + 4 | NewAny = Any - - OptionalStr = typing.Optional[str] -5 + OptionalStr: TypeAlias = typing.Optional[str] -6 | Foo = Literal["foo"] +5 ~ OptionalStr: TypeAlias = typing.Optional[str] | PYI026 [*] Use `typing_extensions.TypeAlias` for type alias, e.g., `Foo: TypeAlias = Literal["foo"]` @@ -53,14 +47,11 @@ PYI026 [*] Use `typing_extensions.TypeAlias` for type alias, e.g., `Foo: TypeAli | help: Add `TypeAlias` annotation | -1 | from typing import Literal, Any 2 + from typing_extensions import TypeAlias -3 | +3 + 4 | NewAny = Any 5 | OptionalStr = typing.Optional[str] - - Foo = Literal["foo"] -6 + Foo: TypeAlias = Literal["foo"] -7 | IntOrStr = int | str +6 ~ Foo: TypeAlias = Literal["foo"] | PYI026 [*] Use `typing_extensions.TypeAlias` for type alias, e.g., `IntOrStr: TypeAlias = int | str` @@ -74,15 +65,12 @@ PYI026 [*] Use `typing_extensions.TypeAlias` for type alias, e.g., `IntOrStr: Ty | help: Add `TypeAlias` annotation | -1 | from typing import Literal, Any 2 + from typing_extensions import TypeAlias -3 | +3 + 4 | NewAny = Any 5 | OptionalStr = typing.Optional[str] 6 | Foo = Literal["foo"] - - IntOrStr = int | str -7 + IntOrStr: TypeAlias = int | str -8 | AliasNone = None +7 ~ IntOrStr: TypeAlias = int | str | PYI026 [*] Use `typing_extensions.TypeAlias` for type alias, e.g., `AliasNone: TypeAlias = None` @@ -97,14 +85,12 @@ PYI026 [*] Use `typing_extensions.TypeAlias` for type alias, e.g., `AliasNone: T | help: Add `TypeAlias` annotation | -1 | from typing import Literal, Any 2 + from typing_extensions import TypeAlias -3 | --------------------------------------------------------------------------------- +3 + +4 | NewAny = Any +… 7 | IntOrStr = int | str - - AliasNone = None -8 + AliasNone: TypeAlias = None -9 | +8 ~ AliasNone: TypeAlias = None | PYI026 [*] Use `typing_extensions.TypeAlias` for type alias, e.g., `FLAG_THIS: TypeAlias = None` @@ -118,12 +104,10 @@ PYI026 [*] Use `typing_extensions.TypeAlias` for type alias, e.g., `FLAG_THIS: T | help: Add `TypeAlias` annotation | -1 | from typing import Literal, Any -2 + from typing_extensions import TypeAlias -3 | --------------------------------------------------------------------------------- + 2 + from typing_extensions import TypeAlias + 3 + + 4 | NewAny = Any + … 17 | class NotAnEnum: - - FLAG_THIS = None -18 + FLAG_THIS: TypeAlias = None -19 | +18 ~ FLAG_THIS: TypeAlias = None | diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__py38_PYI061_PYI061.py.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__py38_PYI061_PYI061.py.snap index add20bd27590f..f0968ac004751 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__py38_PYI061_PYI061.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__py38_PYI061_PYI061.py.snap @@ -10,10 +10,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -3 | - - def func1(arg1: Literal[None]): +4 - def func1(arg1: Literal[None]): 4 + def func1(arg1: None): -5 | ... | note: This is an unsafe fix and may change runtime behavior @@ -26,10 +24,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -7 | - - def func2(arg1: Literal[None] | int): +8 - def func2(arg1: Literal[None] | int): 8 + def func2(arg1: None | int): -9 | ... | note: This is an unsafe fix and may change runtime behavior @@ -42,10 +38,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -11 | - - def func3() -> Literal[None]: +12 - def func3() -> Literal[None]: 12 + def func3() -> None: -13 | ... | note: This is an unsafe fix and may change runtime behavior @@ -58,14 +52,11 @@ PYI061 [*] Use `Optional[Literal[...]]` rather than `Literal[None, ...]` | help: Replace with `Optional[Literal[...]]` | - - from typing import Literal, Union -1 + from typing import Literal, Union, Optional -2 | --------------------------------------------------------------------------------- + 1 ~ from typing import Literal, Union, Optional + 2 | + … 15 | - - def func4(arg1: Literal[int, None, float]): -16 + def func4(arg1: Optional[Literal[int, float]]): -17 | ... +16 ~ def func4(arg1: Optional[Literal[int, float]]): | note: This is an unsafe fix and may change runtime behavior @@ -78,10 +69,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -19 | - - def func5(arg1: Literal[None, None]): +20 - def func5(arg1: Literal[None, None]): 20 + def func5(arg1: None): -21 | ... | note: This is an unsafe fix and may change runtime behavior @@ -94,10 +83,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -19 | - - def func5(arg1: Literal[None, None]): +20 - def func5(arg1: Literal[None, None]): 20 + def func5(arg1: None): -21 | ... | note: This is an unsafe fix and may change runtime behavior @@ -113,18 +100,11 @@ PYI061 [*] Use `Optional[Literal[...]]` rather than `Literal[None, ...]` | help: Replace with `Optional[Literal[...]]` | - - from typing import Literal, Union -1 + from typing import Literal, Union, Optional -2 | --------------------------------------------------------------------------------- + 1 ~ from typing import Literal, Union, Optional + 2 | + … 23 | - - def func6(arg1: Literal[ - - "hello", - - None # Comment 1 - - , "world" - - ]): -24 + def func6(arg1: Optional[Literal["hello", "world"]]): -25 | ... +24 ~ def func6(arg1: Optional[Literal["hello", "world"]]): | note: This is an unsafe fix and may change runtime behavior @@ -139,12 +119,10 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -31 | - - def func7(arg1: Literal[ - - None # Comment 1 - - ]): +32 - def func7(arg1: Literal[ +33 - None # Comment 1 +34 - ]): 32 + def func7(arg1: None): -33 | ... | note: This is an unsafe fix and may change runtime behavior @@ -166,10 +144,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -41 | - - def func9(arg1: Union[Literal[None], None]): +42 - def func9(arg1: Union[Literal[None], None]): 42 + def func9(arg1: Union[None, None]): -43 | ... | note: This is an unsafe fix and may change runtime behavior @@ -183,10 +159,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -51 | # From flake8-pyi - - Literal[None] # Y061 None inside "Literal[]" expression. Replace with "None" +52 - Literal[None] # Y061 None inside "Literal[]" expression. Replace with "None" 52 + None # Y061 None inside "Literal[]" expression. Replace with "None" -53 | Literal[True, None] # Y061 None inside "Literal[]" expression. Replace with "Literal[True] | None" | note: This is an unsafe fix and may change runtime behavior @@ -202,14 +176,11 @@ PYI061 [*] Use `Optional[Literal[...]]` rather than `Literal[None, ...]` | help: Replace with `Optional[Literal[...]]` | - - from typing import Literal, Union -1 + from typing import Literal, Union, Optional -2 | --------------------------------------------------------------------------------- + 1 ~ from typing import Literal, Union, Optional + 2 | + … 52 | Literal[None] # Y061 None inside "Literal[]" expression. Replace with "None" - - Literal[True, None] # Y061 None inside "Literal[]" expression. Replace with "Literal[True] | None" -53 + Optional[Literal[True]] # Y061 None inside "Literal[]" expression. Replace with "Literal[True] | None" -54 | +53 ~ Optional[Literal[True]] # Y061 None inside "Literal[]" expression. Replace with "Literal[True] | None" | note: This is an unsafe fix and may change runtime behavior @@ -224,10 +195,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -61 | # only emit Y061... - - Literal[None, None] # Y061 None inside "Literal[]" expression. Replace with "None" +62 - Literal[None, None] # Y061 None inside "Literal[]" expression. Replace with "None" 62 + None # Y061 None inside "Literal[]" expression. Replace with "None" -63 | Literal[1, None, "foo", None] # Y061 None inside "Literal[]" expression. Replace with "Literal[1, 'foo'] | None" | note: This is an unsafe fix and may change runtime behavior @@ -242,10 +211,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -61 | # only emit Y061... - - Literal[None, None] # Y061 None inside "Literal[]" expression. Replace with "None" +62 - Literal[None, None] # Y061 None inside "Literal[]" expression. Replace with "None" 62 + None # Y061 None inside "Literal[]" expression. Replace with "None" -63 | Literal[1, None, "foo", None] # Y061 None inside "Literal[]" expression. Replace with "Literal[1, 'foo'] | None" | note: This is an unsafe fix and may change runtime behavior @@ -261,14 +228,11 @@ PYI061 [*] Use `Optional[Literal[...]]` rather than `Literal[None, ...]` | help: Replace with `Optional[Literal[...]]` | - - from typing import Literal, Union -1 + from typing import Literal, Union, Optional -2 | --------------------------------------------------------------------------------- + 1 ~ from typing import Literal, Union, Optional + 2 | + … 62 | Literal[None, None] # Y061 None inside "Literal[]" expression. Replace with "None" - - Literal[1, None, "foo", None] # Y061 None inside "Literal[]" expression. Replace with "Literal[1, 'foo'] | None" -63 + Optional[Literal[1, "foo"]] # Y061 None inside "Literal[]" expression. Replace with "Literal[1, 'foo'] | None" -64 | +63 ~ Optional[Literal[1, "foo"]] # Y061 None inside "Literal[]" expression. Replace with "Literal[1, 'foo'] | None" | note: This is an unsafe fix and may change runtime behavior @@ -284,14 +248,11 @@ PYI061 [*] Use `Optional[Literal[...]]` rather than `Literal[None, ...]` | help: Replace with `Optional[Literal[...]]` | - - from typing import Literal, Union -1 + from typing import Literal, Union, Optional -2 | --------------------------------------------------------------------------------- + 1 ~ from typing import Literal, Union, Optional + 2 | + … 62 | Literal[None, None] # Y061 None inside "Literal[]" expression. Replace with "None" - - Literal[1, None, "foo", None] # Y061 None inside "Literal[]" expression. Replace with "Literal[1, 'foo'] | None" -63 + Optional[Literal[1, "foo"]] # Y061 None inside "Literal[]" expression. Replace with "Literal[1, 'foo'] | None" -64 | +63 ~ Optional[Literal[1, "foo"]] # Y061 None inside "Literal[]" expression. Replace with "Literal[1, 'foo'] | None" | note: This is an unsafe fix and may change runtime behavior @@ -304,14 +265,11 @@ PYI061 [*] Use `Optional[Literal[...]]` rather than `Literal[None, ...]` | ^^^^ help: Replace with `Optional[Literal[...]]` | - - from typing import Literal, Union -1 + from typing import Literal, Union, Optional -2 | --------------------------------------------------------------------------------- + 1 ~ from typing import Literal, Union, Optional + 2 | + … 67 | # only emit Y062: - - Literal[None, True, None, True] # Y062 Duplicate "Literal[]" member "True" -68 + Optional[Literal[True, True]] # Y062 Duplicate "Literal[]" member "True" -69 | +68 ~ Optional[Literal[True, True]] # Y062 Duplicate "Literal[]" member "True" | note: This is an unsafe fix and may change runtime behavior @@ -324,14 +282,11 @@ PYI061 [*] Use `Optional[Literal[...]]` rather than `Literal[None, ...]` | ^^^^ help: Replace with `Optional[Literal[...]]` | - - from typing import Literal, Union -1 + from typing import Literal, Union, Optional -2 | --------------------------------------------------------------------------------- + 1 ~ from typing import Literal, Union, Optional + 2 | + … 67 | # only emit Y062: - - Literal[None, True, None, True] # Y062 Duplicate "Literal[]" member "True" -68 + Optional[Literal[True, True]] # Y062 Duplicate "Literal[]" member "True" -69 | +68 ~ Optional[Literal[True, True]] # Y062 Duplicate "Literal[]" member "True" | note: This is an unsafe fix and may change runtime behavior @@ -369,10 +324,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -73 | y: None | Literal[None] - - z: Union[Literal[None], None] +74 - z: Union[Literal[None], None] 74 + z: Union[None, None] -75 | | note: This is an unsafe fix and may change runtime behavior @@ -445,14 +398,11 @@ PYI061 [*] Use `Optional[Literal[...]]` rather than `Literal[None, ...]` | help: Replace with `Optional[Literal[...]]` | - - from typing import Literal, Union -1 + from typing import Literal, Union, Optional -2 | --------------------------------------------------------------------------------- + 1 ~ from typing import Literal, Union, Optional + 2 | + … 82 | # Test cases for operator precedence issue (https://github.com/astral-sh/ruff/issues/20265) - - print(Literal[1, None].__dict__) # Should become (Literal[1] | None).__dict__ -83 + print(Optional[Literal[1]].__dict__) # Should become (Literal[1] | None).__dict__ -84 | print(Literal[1, None].method()) # Should become (Literal[1] | None).method() +83 ~ print(Optional[Literal[1]].__dict__) # Should become (Literal[1] | None).__dict__ | note: This is an unsafe fix and may change runtime behavior @@ -468,14 +418,11 @@ PYI061 [*] Use `Optional[Literal[...]]` rather than `Literal[None, ...]` | help: Replace with `Optional[Literal[...]]` | - - from typing import Literal, Union -1 + from typing import Literal, Union, Optional -2 | --------------------------------------------------------------------------------- + 1 ~ from typing import Literal, Union, Optional + 2 | + … 83 | print(Literal[1, None].__dict__) # Should become (Literal[1] | None).__dict__ - - print(Literal[1, None].method()) # Should become (Literal[1] | None).method() -84 + print(Optional[Literal[1]].method()) # Should become (Literal[1] | None).method() -85 | print(Literal[1, None][0]) # Should become (Literal[1] | None)[0] +84 ~ print(Optional[Literal[1]].method()) # Should become (Literal[1] | None).method() | note: This is an unsafe fix and may change runtime behavior @@ -491,14 +438,11 @@ PYI061 [*] Use `Optional[Literal[...]]` rather than `Literal[None, ...]` | help: Replace with `Optional[Literal[...]]` | - - from typing import Literal, Union -1 + from typing import Literal, Union, Optional -2 | --------------------------------------------------------------------------------- + 1 ~ from typing import Literal, Union, Optional + 2 | + … 84 | print(Literal[1, None].method()) # Should become (Literal[1] | None).method() - - print(Literal[1, None][0]) # Should become (Literal[1] | None)[0] -85 + print(Optional[Literal[1]][0]) # Should become (Literal[1] | None)[0] -86 | print(Literal[1, None] + 1) # Should become (Literal[1] | None) + 1 +85 ~ print(Optional[Literal[1]][0]) # Should become (Literal[1] | None)[0] | note: This is an unsafe fix and may change runtime behavior @@ -514,14 +458,11 @@ PYI061 [*] Use `Optional[Literal[...]]` rather than `Literal[None, ...]` | help: Replace with `Optional[Literal[...]]` | - - from typing import Literal, Union -1 + from typing import Literal, Union, Optional -2 | --------------------------------------------------------------------------------- + 1 ~ from typing import Literal, Union, Optional + 2 | + … 85 | print(Literal[1, None][0]) # Should become (Literal[1] | None)[0] - - print(Literal[1, None] + 1) # Should become (Literal[1] | None) + 1 -86 + print(Optional[Literal[1]] + 1) # Should become (Literal[1] | None) + 1 -87 | print(Literal[1, None] * 2) # Should become (Literal[1] | None) * 2 +86 ~ print(Optional[Literal[1]] + 1) # Should become (Literal[1] | None) + 1 | note: This is an unsafe fix and may change runtime behavior @@ -536,14 +477,11 @@ PYI061 [*] Use `Optional[Literal[...]]` rather than `Literal[None, ...]` | help: Replace with `Optional[Literal[...]]` | - - from typing import Literal, Union -1 + from typing import Literal, Union, Optional -2 | --------------------------------------------------------------------------------- + 1 ~ from typing import Literal, Union, Optional + 2 | + … 86 | print(Literal[1, None] + 1) # Should become (Literal[1] | None) + 1 - - print(Literal[1, None] * 2) # Should become (Literal[1] | None) * 2 -87 + print(Optional[Literal[1]] * 2) # Should become (Literal[1] | None) * 2 -88 | print((Literal[1, None]).__dict__) # Should become ((Literal[1] | None)).__dict__ +87 ~ print(Optional[Literal[1]] * 2) # Should become (Literal[1] | None) * 2 | note: This is an unsafe fix and may change runtime behavior @@ -559,14 +497,11 @@ PYI061 [*] Use `Optional[Literal[...]]` rather than `Literal[None, ...]` | help: Replace with `Optional[Literal[...]]` | - - from typing import Literal, Union -1 + from typing import Literal, Union, Optional -2 | --------------------------------------------------------------------------------- + 1 ~ from typing import Literal, Union, Optional + 2 | + … 87 | print(Literal[1, None] * 2) # Should become (Literal[1] | None) * 2 - - print((Literal[1, None]).__dict__) # Should become ((Literal[1] | None)).__dict__ -88 + print((Optional[Literal[1]]).__dict__) # Should become ((Literal[1] | None)).__dict__ -89 | +88 ~ print((Optional[Literal[1]]).__dict__) # Should become ((Literal[1] | None)).__dict__ | note: This is an unsafe fix and may change runtime behavior @@ -579,12 +514,10 @@ PYI061 [*] Use `Optional[Literal[...]]` rather than `Literal[None, ...]` | ^^^^ help: Replace with `Optional[Literal[...]]` | - - from typing import Literal, Union -1 + from typing import Literal, Union, Optional -2 | --------------------------------------------------------------------------------- + 1 ~ from typing import Literal, Union, Optional + 2 | + … 91 | # Rewriting this changes `typing.get_args(options)` at runtime, so the fix is unsafe. - - options = Literal["foo", "bar", None] -92 + options = Optional[Literal["foo", "bar"]] +92 ~ options = Optional[Literal["foo", "bar"]] | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__py38_PYI061_PYI061.pyi.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__py38_PYI061_PYI061.pyi.snap index 86a44243cce59..9ea46cde17049 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__py38_PYI061_PYI061.pyi.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__py38_PYI061_PYI061.pyi.snap @@ -8,10 +8,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | ^^^^ help: Replace with `None` | -3 | - - def func1(arg1: Literal[None]): ... +4 - def func1(arg1: Literal[None]): ... 4 + def func1(arg1: None): ... -5 | | PYI061 [*] Use `None` rather than `Literal[None]` @@ -21,10 +19,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | ^^^^ help: Replace with `None` | -6 | - - def func2(arg1: Literal[None] | int): ... +7 - def func2(arg1: Literal[None] | int): ... 7 + def func2(arg1: None | int): ... -8 | | PYI061 [*] Use `None` rather than `Literal[None]` @@ -34,10 +30,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | ^^^^ help: Replace with `None` | -9 | - - def func3() -> Literal[None]: ... +10 - def func3() -> Literal[None]: ... 10 + def func3() -> None: ... -11 | | PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` @@ -47,10 +41,8 @@ PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` | ^^^^ help: Replace with `Literal[...] | None` | -12 | - - def func4(arg1: Literal[int, None, float]): ... +13 - def func4(arg1: Literal[int, None, float]): ... 13 + def func4(arg1: Literal[int, float] | None): ... -14 | | PYI061 [*] Use `None` rather than `Literal[None]` @@ -60,10 +52,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | ^^^^ help: Replace with `None` | -15 | - - def func5(arg1: Literal[None, None]): ... +16 - def func5(arg1: Literal[None, None]): ... 16 + def func5(arg1: None): ... -17 | | PYI061 [*] Use `None` rather than `Literal[None]` @@ -73,10 +63,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | ^^^^ help: Replace with `None` | -15 | - - def func5(arg1: Literal[None, None]): ... +16 - def func5(arg1: Literal[None, None]): ... 16 + def func5(arg1: None): ... -17 | | PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` @@ -91,14 +79,12 @@ PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` | help: Replace with `Literal[...] | None` | -18 | - - def func6(arg1: Literal[ - - "hello", - - None # Comment 1 - - , "world" - - ]): ... +19 - def func6(arg1: Literal[ +20 - "hello", +21 - None # Comment 1 +22 - , "world" +23 - ]): ... 19 + def func6(arg1: Literal["hello", "world"] | None): ... -20 | | note: This is an unsafe fix and may change runtime behavior @@ -112,12 +98,10 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -25 | - - def func7(arg1: Literal[ - - None # Comment 1 - - ]): ... +26 - def func7(arg1: Literal[ +27 - None # Comment 1 +28 - ]): ... 26 + def func7(arg1: None): ... -27 | | note: This is an unsafe fix and may change runtime behavior @@ -135,10 +119,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | ^^^^ help: Replace with `None` | -33 | - - def func9(arg1: Union[Literal[None], None]): ... +34 - def func9(arg1: Union[Literal[None], None]): ... 34 + def func9(arg1: Union[None, None]): ... -35 | | PYI061 [*] Use `None` rather than `Literal[None]` @@ -151,10 +133,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -41 | # From flake8-pyi - - Literal[None] # PYI061 None inside "Literal[]" expression. Replace with "None" +42 - Literal[None] # PYI061 None inside "Literal[]" expression. Replace with "None" 42 + None # PYI061 None inside "Literal[]" expression. Replace with "None" -43 | Literal[True, None] # PYI061 None inside "Literal[]" expression. Replace with "Literal[True] | None" | PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` @@ -166,10 +146,8 @@ PYI061 [*] Use `Literal[...] | None` rather than `Literal[None, ...]` | ^^^^ help: Replace with `Literal[...] | None` | -42 | Literal[None] # PYI061 None inside "Literal[]" expression. Replace with "None" - - Literal[True, None] # PYI061 None inside "Literal[]" expression. Replace with "Literal[True] | None" +43 - Literal[True, None] # PYI061 None inside "Literal[]" expression. Replace with "Literal[True] | None" 43 + Literal[True] | None # PYI061 None inside "Literal[]" expression. Replace with "Literal[True] | None" -44 | | PYI061 Use `None` rather than `Literal[None]` @@ -206,10 +184,8 @@ PYI061 [*] Use `None` rather than `Literal[None]` | help: Replace with `None` | -48 | y: None | Literal[None] - - z: Union[Literal[None], None] +49 - z: Union[Literal[None], None] 49 + z: Union[None, None] -50 | | PYI061 Use `None` rather than `Literal[None]` diff --git a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__pyi021_pie790_isolation_check.snap b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__pyi021_pie790_isolation_check.snap index 620f48aa6e6b3..1f26bd0d3ef4a 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__pyi021_pie790_isolation_check.snap +++ b/crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__pyi021_pie790_isolation_check.snap @@ -11,10 +11,8 @@ PYI021 [*] Docstrings should not be included in stubs | help: Remove docstring | -4 | def check_isolation_level(mode: int) -> None: - - """Will report both, but only fix the first.""" # ERROR PYI021 +5 - """Will report both, but only fix the first.""" # ERROR PYI021 5 + # ERROR PYI021 -6 | ... # ERROR PIE790 | note: This is an unsafe fix and may change runtime behavior @@ -27,8 +25,6 @@ PIE790 [*] Unnecessary `...` literal | ^^^ help: Remove unnecessary `...` | -5 | """Will report both, but only fix the first.""" # ERROR PYI021 - - ... # ERROR PIE790 +6 - ... # ERROR PIE790 6 + # ERROR PIE790 -7 | | diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT001_default.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT001_default.snap index 77299708d08fa..7208e80e3bf20 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT001_default.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT001_default.snap @@ -11,10 +11,8 @@ PT001 [*] Use `@pytest.fixture` over `@pytest.fixture()` | help: Remove parentheses | -13 | - - @pytest.fixture() +14 - @pytest.fixture() 14 + @pytest.fixture -15 | def parentheses_no_params(): | PT001 [*] Use `@pytest.fixture` over `@pytest.fixture()` @@ -29,12 +27,10 @@ PT001 [*] Use `@pytest.fixture` over `@pytest.fixture()` | help: Remove parentheses | -23 | - - @pytest.fixture( - - - - ) +24 - @pytest.fixture( +25 - +26 - ) 24 + @pytest.fixture -25 | def parentheses_no_params_multiline(): | PT001 [*] Use `@pytest.fixture` over `@pytest.fixture()` @@ -47,10 +43,8 @@ PT001 [*] Use `@pytest.fixture` over `@pytest.fixture()` | help: Remove parentheses | -38 | - - @fixture() +39 - @fixture() 39 + @fixture -40 | def imported_from_parentheses_no_params(): | PT001 [*] Use `@pytest.fixture` over `@pytest.fixture()` @@ -65,12 +59,10 @@ PT001 [*] Use `@pytest.fixture` over `@pytest.fixture()` | help: Remove parentheses | -48 | - - @fixture( - - - - ) +49 - @fixture( +50 - +51 - ) 49 + @fixture -50 | def imported_from_parentheses_no_params_multiline(): | PT001 [*] Use `@pytest.fixture` over `@pytest.fixture()` @@ -83,10 +75,8 @@ PT001 [*] Use `@pytest.fixture` over `@pytest.fixture()` | help: Remove parentheses | -63 | - - @aliased() +64 - @aliased() 64 + @aliased -65 | def aliased_parentheses_no_params(): | PT001 [*] Use `@pytest.fixture` over `@pytest.fixture()` @@ -101,12 +91,10 @@ PT001 [*] Use `@pytest.fixture` over `@pytest.fixture()` | help: Remove parentheses | -73 | - - @aliased( - - - - ) +74 - @aliased( +75 - +76 - ) 74 + @aliased -75 | def aliased_parentheses_no_params_multiline(): | PT001 [*] Use `@pytest.fixture` over `@pytest.fixture()` @@ -122,13 +110,11 @@ PT001 [*] Use `@pytest.fixture` over `@pytest.fixture()` | help: Remove parentheses | -80 | # https://github.com/astral-sh/ruff/issues/18770 - - @pytest.fixture( - - # TODO: use module scope - - # scope="module" - - ) +81 - @pytest.fixture( +82 - # TODO: use module scope +83 - # scope="module" +84 - ) 81 + @pytest.fixture -82 | def my_fixture(): ... | note: This is an unsafe fix and may change runtime behavior @@ -142,10 +128,8 @@ PT001 [*] Use `@pytest.fixture` over `@pytest.fixture()` | help: Remove parentheses | -87 | - - @(pytest.fixture()) +88 - @(pytest.fixture()) 88 + @(pytest.fixture) -89 | def outer_paren_fixture_no_params(): | PT001 [*] Use `@pytest.fixture` over `@pytest.fixture()` @@ -158,8 +142,6 @@ PT001 [*] Use `@pytest.fixture` over `@pytest.fixture()` | help: Remove parentheses | -92 | - - @(fixture()) +93 - @(fixture()) 93 + @(fixture) -94 | def outer_paren_imported_fixture_no_params(): | diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT001_parentheses.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT001_parentheses.snap index 1701279233bca..a6e2596dd734f 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT001_parentheses.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT001_parentheses.snap @@ -10,12 +10,9 @@ PT001 [*] Use `@pytest.fixture()` over `@pytest.fixture` 11 | return 42 | help: Add parentheses - | -8 | - - @pytest.fixture -9 + @pytest.fixture() -10 | def no_parentheses(): - | + | +9 | @pytest.fixture() + | ++ PT001 [*] Use `@pytest.fixture()` over `@pytest.fixture` --> PT001.py:34:1 @@ -27,11 +24,8 @@ PT001 [*] Use `@pytest.fixture()` over `@pytest.fixture` | help: Add parentheses | -33 | - - @fixture -34 + @fixture() -35 | def imported_from_no_parentheses(): - | +34 | @fixture() + | ++ PT001 [*] Use `@pytest.fixture()` over `@pytest.fixture` --> PT001.py:59:1 @@ -43,8 +37,5 @@ PT001 [*] Use `@pytest.fixture()` over `@pytest.fixture` | help: Add parentheses | -58 | - - @aliased -59 + @aliased() -60 | def aliased_no_parentheses(): - | +59 | @aliased() + | ++ diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT003.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT003.snap index d7e9899903bd4..3e44c500ff60c 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT003.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT003.snap @@ -11,10 +11,8 @@ PT003 [*] `scope='function'` is implied in `@pytest.fixture()` | help: Remove implied `scope` argument | -13 | - - @pytest.fixture(scope="function") +14 - @pytest.fixture(scope="function") 14 + @pytest.fixture() -15 | def error(): | note: This is an unsafe fix and may change runtime behavior @@ -28,10 +26,8 @@ PT003 [*] `scope='function'` is implied in `@pytest.fixture()` | help: Remove implied `scope` argument | -18 | - - @pytest.fixture(scope="function", name="my_fixture") +19 - @pytest.fixture(scope="function", name="my_fixture") 19 + @pytest.fixture(name="my_fixture") -20 | def error_multiple_args(): | note: This is an unsafe fix and may change runtime behavior @@ -45,10 +41,8 @@ PT003 [*] `scope='function'` is implied in `@pytest.fixture()` | help: Remove implied `scope` argument | -23 | - - @pytest.fixture(name="my_fixture", scope="function") +24 - @pytest.fixture(name="my_fixture", scope="function") 24 + @pytest.fixture(name="my_fixture") -25 | def error_multiple_args(): | note: This is an unsafe fix and may change runtime behavior @@ -62,10 +56,8 @@ PT003 [*] `scope='function'` is implied in `@pytest.fixture()` | help: Remove implied `scope` argument | -28 | - - @pytest.fixture(name="my_fixture", scope="function", **kwargs) +29 - @pytest.fixture(name="my_fixture", scope="function", **kwargs) 29 + @pytest.fixture(name="my_fixture", **kwargs) -30 | def error_second_arg(): | note: This is an unsafe fix and may change runtime behavior @@ -81,10 +73,8 @@ PT003 [*] `scope='function'` is implied in `@pytest.fixture()` | help: Remove implied `scope` argument | -36 | # work for all cases. - - @pytest.fixture("my_fixture", scope="function") +37 - @pytest.fixture("my_fixture", scope="function") 37 + @pytest.fixture("my_fixture") -38 | def error_arg(): | note: This is an unsafe fix and may change runtime behavior @@ -99,9 +89,7 @@ PT003 [*] `scope='function'` is implied in `@pytest.fixture()` | help: Remove implied `scope` argument | -42 | @pytest.fixture( - - scope="function", -43 | name="my_fixture", +43 - scope="function", | note: This is an unsafe fix and may change runtime behavior @@ -117,9 +105,9 @@ PT003 [*] `scope='function'` is implied in `@pytest.fixture()` | help: Remove implied `scope` argument | -51 | name="my_fixture", - - scope="function", -52 | ) +51 - name="my_fixture", +52 - scope="function", +51 + name="my_fixture", | note: This is an unsafe fix and may change runtime behavior @@ -135,11 +123,9 @@ PT003 [*] `scope='function'` is implied in `@pytest.fixture()` | help: Remove implied `scope` argument | -65 | - - scope=\ - - "function" # some comment ), - - , - - -66 | name2=name, name3="my_fixture", **kwargs +66 - scope=\ +67 - "function" # some comment ), +68 - , +69 - | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT006_and_PT007.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT006_and_PT007.snap index 46b43091c1052..22b8b9f4c2ceb 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT006_and_PT007.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT006_and_PT007.snap @@ -13,10 +13,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -2 | - - @pytest.mark.parametrize(("param",), [[1], [2]]) +3 - @pytest.mark.parametrize(("param",), [[1], [2]]) 3 + @pytest.mark.parametrize("param", [1, 2]) -4 | def test_PT006_and_PT007_do_not_conflict(param): | PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` of `tuple` @@ -31,10 +29,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` of `tup | help: Use `list` of `tuple` for parameter values | -2 | - - @pytest.mark.parametrize(("param",), [[1], [2]]) +3 - @pytest.mark.parametrize(("param",), [[1], [2]]) 3 + @pytest.mark.parametrize(("param",), [(1,), [2]]) -4 | def test_PT006_and_PT007_do_not_conflict(param): | note: This is an unsafe fix and may change runtime behavior @@ -50,9 +46,7 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` of `tup | help: Use `list` of `tuple` for parameter values | -2 | - - @pytest.mark.parametrize(("param",), [[1], [2]]) +3 - @pytest.mark.parametrize(("param",), [[1], [2]]) 3 + @pytest.mark.parametrize(("param",), [[1], (2,)]) -4 | def test_PT006_and_PT007_do_not_conflict(param): | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT006_csv.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT006_csv.snap index 53a1724be2621..37cc639d2897c 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT006_csv.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT006_csv.snap @@ -11,10 +11,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string of comma-separated values for the first argument | -23 | - - @pytest.mark.parametrize(("param1", "param2"), [(1, 2), (3, 4)]) +24 - @pytest.mark.parametrize(("param1", "param2"), [(1, 2), (3, 4)]) 24 + @pytest.mark.parametrize("param1, param2", [(1, 2), (3, 4)]) -25 | def test_tuple(param1, param2): | note: This is an unsafe fix and may change runtime behavior @@ -38,10 +36,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string of comma-separated values for the first argument | -33 | - - @pytest.mark.parametrize(["param1", "param2"], [(1, 2), (3, 4)]) +34 - @pytest.mark.parametrize(["param1", "param2"], [(1, 2), (3, 4)]) 34 + @pytest.mark.parametrize("param1, param2", [(1, 2), (3, 4)]) -35 | def test_list(param1, param2): | note: This is an unsafe fix and may change runtime behavior @@ -85,10 +81,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -85 | - - @pytest.mark.parametrize(("param",), [(1,), (2,)]) +86 - @pytest.mark.parametrize(("param",), [(1,), (2,)]) 86 + @pytest.mark.parametrize("param", [1, 2]) -87 | def test_single_element_tuple(param): | PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` @@ -101,10 +95,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -90 | - - @pytest.mark.parametrize(("param",), [[1], [2]]) +91 - @pytest.mark.parametrize(("param",), [[1], [2]]) 91 + @pytest.mark.parametrize("param", [1, 2]) -92 | def test_single_element_list(param): | PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` @@ -117,10 +109,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -95 | - - @pytest.mark.parametrize(("param",), [[1], [2]]) +96 - @pytest.mark.parametrize(("param",), [[1], [2]]) 96 + @pytest.mark.parametrize("param", [1, 2]) -97 | def test_single_element_list(param): | PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` @@ -138,15 +128,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -102 | @pytest.mark.parametrize( - - ( - - # comment - - "param", - - ), - - [[1], [2]], -103 + "param", -104 + [1, 2], -105 | ) +103 ~ "param", +104 ~ [1, 2], | note: This is an unsafe fix and may change runtime behavior @@ -162,18 +145,10 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -113 | @pytest.mark.parametrize( - - ("param",), -114 + "param", +114 ~ "param", 115 | [ - - ( - - # comment - - 1, - - ), - - (2,), -116 + 1, -117 + 2, -118 | ], +116 ~ 1, +117 ~ 2, | note: This is an unsafe fix and may change runtime behavior @@ -189,16 +164,11 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -128 | @pytest.mark.parametrize( - - ("param",), -129 + "param", +129 ~ "param", 130 | [ - - (1,), -131 + 1, +131 ~ 1, 132 | # comment - - (2,), -133 + 2, -134 | ], +133 ~ 2, | PT006 Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` @@ -225,15 +195,10 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -163 | @pytest.mark.parametrize( - - ["param"], -164 + "param", +164 ~ "param", 165 | [ - - ((),), - - ((1,),), -166 + (), -167 + (1,), -168 | ], +166 ~ (), +167 ~ (1,), | PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` @@ -247,15 +212,10 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -174 | @pytest.mark.parametrize( - - ["param"], -175 + "param", +175 ~ "param", 176 | [ - - ((1, 2),), - - ((3, 4),), -177 + (1, 2), -178 + (3, 4), -179 | ], +177 ~ (1, 2), +178 ~ (3, 4), | PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` @@ -269,13 +229,9 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -185 | @pytest.mark.parametrize( - - ["param"], -186 + "param", +186 ~ "param", 187 | [ - - (((1,),),), -188 + ((1,),), -189 | ], +188 ~ ((1,),), | PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` @@ -289,11 +245,7 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -195 | @pytest.mark.parametrize( - - ["param"], -196 + "param", +196 ~ "param", 197 | [ - - (((1,)),), -198 + (1,), -199 | ], +198 ~ (1,), | diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT006_default.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT006_default.snap index dd434ca5ea212..91f7dcd1ca82c 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT006_default.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT006_default.snap @@ -10,12 +10,10 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe 11 | ... | help: Use a `tuple` for the first argument - | -8 | - - @pytest.mark.parametrize("param1,param2", [(1, 2), (3, 4)]) -9 + @pytest.mark.parametrize(("param1", "param2"), [(1, 2), (3, 4)]) -10 | def test_csv(param1, param2): - | + | +9 - @pytest.mark.parametrize("param1,param2", [(1, 2), (3, 4)]) +9 + @pytest.mark.parametrize(("param1", "param2"), [(1, 2), (3, 4)]) + | note: This is an unsafe fix and may change runtime behavior PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expected `tuple` @@ -28,10 +26,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a `tuple` for the first argument | -13 | - - @pytest.mark.parametrize(" param1, , param2 , ", [(1, 2), (3, 4)]) +14 - @pytest.mark.parametrize(" param1, , param2 , ", [(1, 2), (3, 4)]) 14 + @pytest.mark.parametrize(("param1", "param2"), [(1, 2), (3, 4)]) -15 | def test_csv_with_whitespace(param1, param2): | note: This is an unsafe fix and may change runtime behavior @@ -45,10 +41,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a `tuple` for the first argument | -18 | - - @pytest.mark.parametrize("param1,param2", [(1, 2), (3, 4)]) +19 - @pytest.mark.parametrize("param1,param2", [(1, 2), (3, 4)]) 19 + @pytest.mark.parametrize(("param1", "param2"), [(1, 2), (3, 4)]) -20 | def test_csv_bad_quotes(param1, param2): | note: This is an unsafe fix and may change runtime behavior @@ -72,10 +66,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a `tuple` for the first argument | -33 | - - @pytest.mark.parametrize(["param1", "param2"], [(1, 2), (3, 4)]) +34 - @pytest.mark.parametrize(["param1", "param2"], [(1, 2), (3, 4)]) 34 + @pytest.mark.parametrize(("param1", "param2"), [(1, 2), (3, 4)]) -35 | def test_list(param1, param2): | note: This is an unsafe fix and may change runtime behavior @@ -99,10 +91,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a `tuple` for the first argument | -43 | - - @pytest.mark.parametrize([some_expr, another_expr], [1, 2, 3]) +44 - @pytest.mark.parametrize([some_expr, another_expr], [1, 2, 3]) 44 + @pytest.mark.parametrize((some_expr, another_expr), [1, 2, 3]) -45 | def test_list_expressions(param1, param2): | note: This is an unsafe fix and may change runtime behavior @@ -116,10 +106,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a `tuple` for the first argument | -48 | - - @pytest.mark.parametrize([some_expr, "param2"], [1, 2, 3]) +49 - @pytest.mark.parametrize([some_expr, "param2"], [1, 2, 3]) 49 + @pytest.mark.parametrize((some_expr, "param2"), [1, 2, 3]) -50 | def test_list_mixed_expr_literal(param1, param2): | note: This is an unsafe fix and may change runtime behavior @@ -133,10 +121,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a `tuple` for the first argument | -53 | - - @pytest.mark.parametrize(("param1, " "param2, " "param3"), [(1, 2, 3), (4, 5, 6)]) +54 - @pytest.mark.parametrize(("param1, " "param2, " "param3"), [(1, 2, 3), (4, 5, 6)]) 54 + @pytest.mark.parametrize(("param1", "param2", "param3"), [(1, 2, 3), (4, 5, 6)]) -55 | def test_implicit_str_concat_with_parens(param1, param2, param3): | note: This is an unsafe fix and may change runtime behavior @@ -150,10 +136,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a `tuple` for the first argument | -58 | - - @pytest.mark.parametrize("param1, " "param2, " "param3", [(1, 2, 3), (4, 5, 6)]) +59 - @pytest.mark.parametrize("param1, " "param2, " "param3", [(1, 2, 3), (4, 5, 6)]) 59 + @pytest.mark.parametrize(("param1", "param2", "param3"), [(1, 2, 3), (4, 5, 6)]) -60 | def test_implicit_str_concat_no_parens(param1, param2, param3): | note: This is an unsafe fix and may change runtime behavior @@ -167,10 +151,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a `tuple` for the first argument | -63 | - - @pytest.mark.parametrize((("param1, " "param2, " "param3")), [(1, 2, 3), (4, 5, 6)]) +64 - @pytest.mark.parametrize((("param1, " "param2, " "param3")), [(1, 2, 3), (4, 5, 6)]) 64 + @pytest.mark.parametrize(("param1", "param2", "param3"), [(1, 2, 3), (4, 5, 6)]) -65 | def test_implicit_str_concat_with_multi_parens(param1, param2, param3): | note: This is an unsafe fix and may change runtime behavior @@ -184,10 +166,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a `tuple` for the first argument | -68 | - - @pytest.mark.parametrize(("param1,param2"), [(1, 2), (3, 4)]) +69 - @pytest.mark.parametrize(("param1,param2"), [(1, 2), (3, 4)]) 69 + @pytest.mark.parametrize(("param1", "param2"), [(1, 2), (3, 4)]) -70 | def test_csv_with_parens(param1, param2): | note: This is an unsafe fix and may change runtime behavior @@ -201,10 +181,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a `tuple` for the first argument | -73 | - - parametrize = pytest.mark.parametrize(("param1,param2"), [(1, 2), (3, 4)]) +74 - parametrize = pytest.mark.parametrize(("param1,param2"), [(1, 2), (3, 4)]) 74 + parametrize = pytest.mark.parametrize(("param1", "param2"), [(1, 2), (3, 4)]) -75 | | note: This is an unsafe fix and may change runtime behavior @@ -218,10 +196,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a `tuple` for the first argument | -80 | - - @pytest.mark.parametrize(argnames=("param1,param2"), argvalues=[(1, 2), (3, 4)]) +81 - @pytest.mark.parametrize(argnames=("param1,param2"), argvalues=[(1, 2), (3, 4)]) 81 + @pytest.mark.parametrize(argnames=("param1", "param2"), argvalues=[(1, 2), (3, 4)]) -82 | def test_keyword_arguments(param1, param2): | note: This is an unsafe fix and may change runtime behavior @@ -235,10 +211,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -85 | - - @pytest.mark.parametrize(("param",), [(1,), (2,)]) +86 - @pytest.mark.parametrize(("param",), [(1,), (2,)]) 86 + @pytest.mark.parametrize("param", [1, 2]) -87 | def test_single_element_tuple(param): | PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` @@ -251,10 +225,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -90 | - - @pytest.mark.parametrize(("param",), [[1], [2]]) +91 - @pytest.mark.parametrize(("param",), [[1], [2]]) 91 + @pytest.mark.parametrize("param", [1, 2]) -92 | def test_single_element_list(param): | PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` @@ -267,10 +239,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -95 | - - @pytest.mark.parametrize(("param",), [[1], [2]]) +96 - @pytest.mark.parametrize(("param",), [[1], [2]]) 96 + @pytest.mark.parametrize("param", [1, 2]) -97 | def test_single_element_list(param): | PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` @@ -288,15 +258,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -102 | @pytest.mark.parametrize( - - ( - - # comment - - "param", - - ), - - [[1], [2]], -103 + "param", -104 + [1, 2], -105 | ) +103 ~ "param", +104 ~ [1, 2], | note: This is an unsafe fix and may change runtime behavior @@ -312,18 +275,10 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -113 | @pytest.mark.parametrize( - - ("param",), -114 + "param", +114 ~ "param", 115 | [ - - ( - - # comment - - 1, - - ), - - (2,), -116 + 1, -117 + 2, -118 | ], +116 ~ 1, +117 ~ 2, | note: This is an unsafe fix and may change runtime behavior @@ -339,16 +294,11 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -128 | @pytest.mark.parametrize( - - ("param",), -129 + "param", +129 ~ "param", 130 | [ - - (1,), -131 + 1, +131 ~ 1, 132 | # comment - - (2,), -133 + 2, -134 | ], +133 ~ 2, | PT006 Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` @@ -375,15 +325,10 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -163 | @pytest.mark.parametrize( - - ["param"], -164 + "param", +164 ~ "param", 165 | [ - - ((),), - - ((1,),), -166 + (), -167 + (1,), -168 | ], +166 ~ (), +167 ~ (1,), | PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` @@ -397,15 +342,10 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -174 | @pytest.mark.parametrize( - - ["param"], -175 + "param", +175 ~ "param", 176 | [ - - ((1, 2),), - - ((3, 4),), -177 + (1, 2), -178 + (3, 4), -179 | ], +177 ~ (1, 2), +178 ~ (3, 4), | PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` @@ -419,13 +359,9 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -185 | @pytest.mark.parametrize( - - ["param"], -186 + "param", +186 ~ "param", 187 | [ - - (((1,),),), -188 + ((1,),), -189 | ], +188 ~ ((1,),), | PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` @@ -439,11 +375,7 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -195 | @pytest.mark.parametrize( - - ["param"], -196 + "param", +196 ~ "param", 197 | [ - - (((1,)),), -198 + (1,), -199 | ], +198 ~ (1,), | diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT006_list.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT006_list.snap index 3533b8c50a3d2..a67e201a191ce 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT006_list.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT006_list.snap @@ -10,12 +10,10 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe 11 | ... | help: Use a `list` for the first argument - | -8 | - - @pytest.mark.parametrize("param1,param2", [(1, 2), (3, 4)]) -9 + @pytest.mark.parametrize(["param1", "param2"], [(1, 2), (3, 4)]) -10 | def test_csv(param1, param2): - | + | +9 - @pytest.mark.parametrize("param1,param2", [(1, 2), (3, 4)]) +9 + @pytest.mark.parametrize(["param1", "param2"], [(1, 2), (3, 4)]) + | note: This is an unsafe fix and may change runtime behavior PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expected `list` @@ -28,10 +26,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a `list` for the first argument | -13 | - - @pytest.mark.parametrize(" param1, , param2 , ", [(1, 2), (3, 4)]) +14 - @pytest.mark.parametrize(" param1, , param2 , ", [(1, 2), (3, 4)]) 14 + @pytest.mark.parametrize(["param1", "param2"], [(1, 2), (3, 4)]) -15 | def test_csv_with_whitespace(param1, param2): | note: This is an unsafe fix and may change runtime behavior @@ -45,10 +41,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a `list` for the first argument | -18 | - - @pytest.mark.parametrize("param1,param2", [(1, 2), (3, 4)]) +19 - @pytest.mark.parametrize("param1,param2", [(1, 2), (3, 4)]) 19 + @pytest.mark.parametrize(["param1", "param2"], [(1, 2), (3, 4)]) -20 | def test_csv_bad_quotes(param1, param2): | note: This is an unsafe fix and may change runtime behavior @@ -62,10 +56,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a `list` for the first argument | -23 | - - @pytest.mark.parametrize(("param1", "param2"), [(1, 2), (3, 4)]) +24 - @pytest.mark.parametrize(("param1", "param2"), [(1, 2), (3, 4)]) 24 + @pytest.mark.parametrize(["param1", "param2"], [(1, 2), (3, 4)]) -25 | def test_tuple(param1, param2): | note: This is an unsafe fix and may change runtime behavior @@ -99,10 +91,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a `list` for the first argument | -53 | - - @pytest.mark.parametrize(("param1, " "param2, " "param3"), [(1, 2, 3), (4, 5, 6)]) +54 - @pytest.mark.parametrize(("param1, " "param2, " "param3"), [(1, 2, 3), (4, 5, 6)]) 54 + @pytest.mark.parametrize(["param1", "param2", "param3"], [(1, 2, 3), (4, 5, 6)]) -55 | def test_implicit_str_concat_with_parens(param1, param2, param3): | note: This is an unsafe fix and may change runtime behavior @@ -116,10 +106,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a `list` for the first argument | -58 | - - @pytest.mark.parametrize("param1, " "param2, " "param3", [(1, 2, 3), (4, 5, 6)]) +59 - @pytest.mark.parametrize("param1, " "param2, " "param3", [(1, 2, 3), (4, 5, 6)]) 59 + @pytest.mark.parametrize(["param1", "param2", "param3"], [(1, 2, 3), (4, 5, 6)]) -60 | def test_implicit_str_concat_no_parens(param1, param2, param3): | note: This is an unsafe fix and may change runtime behavior @@ -133,10 +121,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a `list` for the first argument | -63 | - - @pytest.mark.parametrize((("param1, " "param2, " "param3")), [(1, 2, 3), (4, 5, 6)]) +64 - @pytest.mark.parametrize((("param1, " "param2, " "param3")), [(1, 2, 3), (4, 5, 6)]) 64 + @pytest.mark.parametrize(["param1", "param2", "param3"], [(1, 2, 3), (4, 5, 6)]) -65 | def test_implicit_str_concat_with_multi_parens(param1, param2, param3): | note: This is an unsafe fix and may change runtime behavior @@ -150,10 +136,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a `list` for the first argument | -68 | - - @pytest.mark.parametrize(("param1,param2"), [(1, 2), (3, 4)]) +69 - @pytest.mark.parametrize(("param1,param2"), [(1, 2), (3, 4)]) 69 + @pytest.mark.parametrize(["param1", "param2"], [(1, 2), (3, 4)]) -70 | def test_csv_with_parens(param1, param2): | note: This is an unsafe fix and may change runtime behavior @@ -167,10 +151,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a `list` for the first argument | -73 | - - parametrize = pytest.mark.parametrize(("param1,param2"), [(1, 2), (3, 4)]) +74 - parametrize = pytest.mark.parametrize(("param1,param2"), [(1, 2), (3, 4)]) 74 + parametrize = pytest.mark.parametrize(["param1", "param2"], [(1, 2), (3, 4)]) -75 | | note: This is an unsafe fix and may change runtime behavior @@ -184,10 +166,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a `list` for the first argument | -80 | - - @pytest.mark.parametrize(argnames=("param1,param2"), argvalues=[(1, 2), (3, 4)]) +81 - @pytest.mark.parametrize(argnames=("param1,param2"), argvalues=[(1, 2), (3, 4)]) 81 + @pytest.mark.parametrize(argnames=["param1", "param2"], argvalues=[(1, 2), (3, 4)]) -82 | def test_keyword_arguments(param1, param2): | note: This is an unsafe fix and may change runtime behavior @@ -201,10 +181,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -85 | - - @pytest.mark.parametrize(("param",), [(1,), (2,)]) +86 - @pytest.mark.parametrize(("param",), [(1,), (2,)]) 86 + @pytest.mark.parametrize("param", [1, 2]) -87 | def test_single_element_tuple(param): | PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` @@ -217,10 +195,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -90 | - - @pytest.mark.parametrize(("param",), [[1], [2]]) +91 - @pytest.mark.parametrize(("param",), [[1], [2]]) 91 + @pytest.mark.parametrize("param", [1, 2]) -92 | def test_single_element_list(param): | PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` @@ -233,10 +209,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -95 | - - @pytest.mark.parametrize(("param",), [[1], [2]]) +96 - @pytest.mark.parametrize(("param",), [[1], [2]]) 96 + @pytest.mark.parametrize("param", [1, 2]) -97 | def test_single_element_list(param): | PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` @@ -254,15 +228,8 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -102 | @pytest.mark.parametrize( - - ( - - # comment - - "param", - - ), - - [[1], [2]], -103 + "param", -104 + [1, 2], -105 | ) +103 ~ "param", +104 ~ [1, 2], | note: This is an unsafe fix and may change runtime behavior @@ -278,18 +245,10 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -113 | @pytest.mark.parametrize( - - ("param",), -114 + "param", +114 ~ "param", 115 | [ - - ( - - # comment - - 1, - - ), - - (2,), -116 + 1, -117 + 2, -118 | ], +116 ~ 1, +117 ~ 2, | note: This is an unsafe fix and may change runtime behavior @@ -305,16 +264,11 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -128 | @pytest.mark.parametrize( - - ("param",), -129 + "param", +129 ~ "param", 130 | [ - - (1,), -131 + 1, +131 ~ 1, 132 | # comment - - (2,), -133 + 2, -134 | ], +133 ~ 2, | PT006 Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` @@ -341,15 +295,10 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -163 | @pytest.mark.parametrize( - - ["param"], -164 + "param", +164 ~ "param", 165 | [ - - ((),), - - ((1,),), -166 + (), -167 + (1,), -168 | ], +166 ~ (), +167 ~ (1,), | PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` @@ -363,15 +312,10 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -174 | @pytest.mark.parametrize( - - ["param"], -175 + "param", +175 ~ "param", 176 | [ - - ((1, 2),), - - ((3, 4),), -177 + (1, 2), -178 + (3, 4), -179 | ], +177 ~ (1, 2), +178 ~ (3, 4), | PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` @@ -385,13 +329,9 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -185 | @pytest.mark.parametrize( - - ["param"], -186 + "param", +186 ~ "param", 187 | [ - - (((1,),),), -188 + ((1,),), -189 | ], +188 ~ ((1,),), | PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` @@ -405,11 +345,7 @@ PT006 [*] Wrong type passed to first argument of `pytest.mark.parametrize`; expe | help: Use a string for the first argument | -195 | @pytest.mark.parametrize( - - ["param"], -196 + "param", +196 ~ "param", 197 | [ - - (((1,)),), -198 + (1,), -199 | ], +198 ~ (1,), | diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT007_list_of_lists.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT007_list_of_lists.snap index 4d5ecdc7118f3..40594344f2ec0 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT007_list_of_lists.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT007_list_of_lists.snap @@ -11,10 +11,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` | help: Use `list` for parameter values | -3 | - - @pytest.mark.parametrize("param", (1, 2)) +4 - @pytest.mark.parametrize("param", (1, 2)) 4 + @pytest.mark.parametrize("param", [1, 2]) -5 | def test_tuple(param): | note: This is an unsafe fix and may change runtime behavior @@ -33,14 +31,10 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` of `lis | help: Use `list` of `list` for parameter values | -10 | ("param1", "param2"), - - ( -11 + [ +11 ~ [ 12 | (1, 2), 13 | (3, 4), - - ), -14 + ], -15 | ) +14 ~ ], | note: This is an unsafe fix and may change runtime behavior @@ -56,10 +50,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` of `lis | help: Use `list` of `list` for parameter values | -11 | ( - - (1, 2), +12 - (1, 2), 12 + [1, 2], -13 | (3, 4), | note: This is an unsafe fix and may change runtime behavior @@ -75,10 +67,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` of `lis | help: Use `list` of `list` for parameter values | -12 | (1, 2), - - (3, 4), +13 - (3, 4), 13 + [3, 4], -14 | ), | note: This is an unsafe fix and may change runtime behavior @@ -97,14 +87,10 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` of `lis | help: Use `list` of `list` for parameter values | -21 | ("param1", "param2"), - - ( -22 + [ +22 ~ [ 23 | [1, 2], 24 | [3, 4], - - ), -25 + ], -26 | ) +25 ~ ], | note: This is an unsafe fix and may change runtime behavior @@ -120,10 +106,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` of `lis | help: Use `list` of `list` for parameter values | -38 | [ - - (1, 2), +39 - (1, 2), 39 + [1, 2], -40 | (3, 4), | note: This is an unsafe fix and may change runtime behavior @@ -139,10 +123,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` of `lis | help: Use `list` of `list` for parameter values | -39 | (1, 2), - - (3, 4), +40 - (3, 4), 40 + [3, 4], -41 | ], | note: This is an unsafe fix and may change runtime behavior @@ -157,10 +139,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` of `lis | help: Use `list` of `list` for parameter values | -80 | @pytest.mark.parametrize("a", [1, 2]) - - @pytest.mark.parametrize(("b", "c"), ((3, 4), (5, 6))) +81 - @pytest.mark.parametrize(("b", "c"), ((3, 4), (5, 6))) 81 + @pytest.mark.parametrize(("b", "c"), [(3, 4), (5, 6)]) -82 | @pytest.mark.parametrize("d", [3,]) | note: This is an unsafe fix and may change runtime behavior @@ -175,10 +155,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` of `lis | help: Use `list` of `list` for parameter values | -80 | @pytest.mark.parametrize("a", [1, 2]) - - @pytest.mark.parametrize(("b", "c"), ((3, 4), (5, 6))) +81 - @pytest.mark.parametrize(("b", "c"), ((3, 4), (5, 6))) 81 + @pytest.mark.parametrize(("b", "c"), ([3, 4], (5, 6))) -82 | @pytest.mark.parametrize("d", [3,]) | note: This is an unsafe fix and may change runtime behavior @@ -193,9 +171,7 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` of `lis | help: Use `list` of `list` for parameter values | -80 | @pytest.mark.parametrize("a", [1, 2]) - - @pytest.mark.parametrize(("b", "c"), ((3, 4), (5, 6))) +81 - @pytest.mark.parametrize(("b", "c"), ((3, 4), (5, 6))) 81 + @pytest.mark.parametrize(("b", "c"), ((3, 4), [5, 6])) -82 | @pytest.mark.parametrize("d", [3,]) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT007_list_of_tuples.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT007_list_of_tuples.snap index a7d8df20a7f44..eabccabe0988a 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT007_list_of_tuples.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT007_list_of_tuples.snap @@ -11,10 +11,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` | help: Use `list` for parameter values | -3 | - - @pytest.mark.parametrize("param", (1, 2)) +4 - @pytest.mark.parametrize("param", (1, 2)) 4 + @pytest.mark.parametrize("param", [1, 2]) -5 | def test_tuple(param): | note: This is an unsafe fix and may change runtime behavior @@ -33,14 +31,10 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` of `tup | help: Use `list` of `tuple` for parameter values | -10 | ("param1", "param2"), - - ( -11 + [ +11 ~ [ 12 | (1, 2), 13 | (3, 4), - - ), -14 + ], -15 | ) +14 ~ ], | note: This is an unsafe fix and may change runtime behavior @@ -59,14 +53,10 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` of `tup | help: Use `list` of `tuple` for parameter values | -21 | ("param1", "param2"), - - ( -22 + [ +22 ~ [ 23 | [1, 2], 24 | [3, 4], - - ), -25 + ], -26 | ) +25 ~ ], | note: This is an unsafe fix and may change runtime behavior @@ -82,10 +72,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` of `tup | help: Use `list` of `tuple` for parameter values | -22 | ( - - [1, 2], +23 - [1, 2], 23 + (1, 2), -24 | [3, 4], | note: This is an unsafe fix and may change runtime behavior @@ -101,10 +89,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` of `tup | help: Use `list` of `tuple` for parameter values | -23 | [1, 2], - - [3, 4], +24 - [3, 4], 24 + (3, 4), -25 | ), | note: This is an unsafe fix and may change runtime behavior @@ -120,10 +106,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` of `tup | help: Use `list` of `tuple` for parameter values | -49 | [ - - [1, 2], +50 - [1, 2], 50 + (1, 2), -51 | [3, 4], | note: This is an unsafe fix and may change runtime behavior @@ -139,10 +123,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` of `tup | help: Use `list` of `tuple` for parameter values | -50 | [1, 2], - - [3, 4], +51 - [3, 4], 51 + (3, 4), -52 | ], | note: This is an unsafe fix and may change runtime behavior @@ -158,10 +140,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` of `tup | help: Use `list` of `tuple` for parameter values | -60 | [ - - [1, 2], +61 - [1, 2], 61 + (1, 2), -62 | [3, 4], | note: This is an unsafe fix and may change runtime behavior @@ -177,10 +157,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` of `tup | help: Use `list` of `tuple` for parameter values | -61 | [1, 2], - - [3, 4], +62 - [3, 4], 62 + (3, 4), -63 | ], | note: This is an unsafe fix and may change runtime behavior @@ -195,9 +173,7 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `list` of `tup | help: Use `list` of `tuple` for parameter values | -80 | @pytest.mark.parametrize("a", [1, 2]) - - @pytest.mark.parametrize(("b", "c"), ((3, 4), (5, 6))) +81 - @pytest.mark.parametrize(("b", "c"), ((3, 4), (5, 6))) 81 + @pytest.mark.parametrize(("b", "c"), [(3, 4), (5, 6)]) -82 | @pytest.mark.parametrize("d", [3,]) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT007_tuple_of_lists.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT007_tuple_of_lists.snap index fa9a34f0fb512..c305d9a2155df 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT007_tuple_of_lists.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT007_tuple_of_lists.snap @@ -13,10 +13,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` of `li | help: Use `tuple` of `list` for parameter values | -11 | ( - - (1, 2), +12 - (1, 2), 12 + [1, 2], -13 | (3, 4), | note: This is an unsafe fix and may change runtime behavior @@ -32,10 +30,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` of `li | help: Use `tuple` of `list` for parameter values | -12 | (1, 2), - - (3, 4), +13 - (3, 4), 13 + [3, 4], -14 | ), | note: This is an unsafe fix and may change runtime behavior @@ -49,10 +45,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` | help: Use `tuple` for parameter values | -30 | - - @pytest.mark.parametrize("param", [1, 2]) +31 - @pytest.mark.parametrize("param", [1, 2]) 31 + @pytest.mark.parametrize("param", (1, 2)) -32 | def test_list(param): | note: This is an unsafe fix and may change runtime behavior @@ -71,14 +65,10 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` of `li | help: Use `tuple` of `list` for parameter values | -37 | ("param1", "param2"), - - [ -38 + ( +38 ~ ( 39 | (1, 2), 40 | (3, 4), - - ], -41 + ), -42 | ) +41 ~ ), | note: This is an unsafe fix and may change runtime behavior @@ -94,10 +84,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` of `li | help: Use `tuple` of `list` for parameter values | -38 | [ - - (1, 2), +39 - (1, 2), 39 + [1, 2], -40 | (3, 4), | note: This is an unsafe fix and may change runtime behavior @@ -113,10 +101,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` of `li | help: Use `tuple` of `list` for parameter values | -39 | (1, 2), - - (3, 4), +40 - (3, 4), 40 + [3, 4], -41 | ], | note: This is an unsafe fix and may change runtime behavior @@ -135,14 +121,10 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` of `li | help: Use `tuple` of `list` for parameter values | -48 | ("param1", "param2"), - - [ -49 + ( +49 ~ ( 50 | [1, 2], 51 | [3, 4], - - ], -52 + ), -53 | ) +52 ~ ), | note: This is an unsafe fix and may change runtime behavior @@ -161,14 +143,10 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` of `li | help: Use `tuple` of `list` for parameter values | -59 | "param1,param2", - - [ -60 + ( +60 ~ ( 61 | [1, 2], 62 | [3, 4], - - ], -63 + ), -64 | ) +63 ~ ), | note: This is an unsafe fix and may change runtime behavior @@ -187,14 +165,10 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` | help: Use `tuple` for parameter values | -70 | "param", - - [ -71 + ( +71 ~ ( 72 | [1, 2], 73 | [3, 4], - - ], -74 + ), -75 | ) +74 ~ ), | note: This is an unsafe fix and may change runtime behavior @@ -208,10 +182,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` | help: Use `tuple` for parameter values | -79 | - - @pytest.mark.parametrize("a", [1, 2]) +80 - @pytest.mark.parametrize("a", [1, 2]) 80 + @pytest.mark.parametrize("a", (1, 2)) -81 | @pytest.mark.parametrize(("b", "c"), ((3, 4), (5, 6))) | note: This is an unsafe fix and may change runtime behavior @@ -226,10 +198,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` of `li | help: Use `tuple` of `list` for parameter values | -80 | @pytest.mark.parametrize("a", [1, 2]) - - @pytest.mark.parametrize(("b", "c"), ((3, 4), (5, 6))) +81 - @pytest.mark.parametrize(("b", "c"), ((3, 4), (5, 6))) 81 + @pytest.mark.parametrize(("b", "c"), ([3, 4], (5, 6))) -82 | @pytest.mark.parametrize("d", [3,]) | note: This is an unsafe fix and may change runtime behavior @@ -244,10 +214,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` of `li | help: Use `tuple` of `list` for parameter values | -80 | @pytest.mark.parametrize("a", [1, 2]) - - @pytest.mark.parametrize(("b", "c"), ((3, 4), (5, 6))) +81 - @pytest.mark.parametrize(("b", "c"), ((3, 4), (5, 6))) 81 + @pytest.mark.parametrize(("b", "c"), ((3, 4), [5, 6])) -82 | @pytest.mark.parametrize("d", [3,]) | note: This is an unsafe fix and may change runtime behavior @@ -263,10 +231,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` | help: Use `tuple` for parameter values | -81 | @pytest.mark.parametrize(("b", "c"), ((3, 4), (5, 6))) - - @pytest.mark.parametrize("d", [3,]) +82 - @pytest.mark.parametrize("d", [3,]) 82 + @pytest.mark.parametrize("d", (3,)) -83 | @pytest.mark.parametrize( | note: This is an unsafe fix and may change runtime behavior @@ -282,10 +248,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` | help: Use `tuple` for parameter values | -84 | "d", - - [("3", "4")], +85 - [("3", "4")], 85 + (("3", "4"),), -86 | ) | note: This is an unsafe fix and may change runtime behavior @@ -301,9 +265,7 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` | help: Use `tuple` for parameter values | -88 | "e", - - [("3", "4"),], +89 - [("3", "4"),], 89 + (("3", "4"),), -90 | ) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT007_tuple_of_tuples.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT007_tuple_of_tuples.snap index daf70cba374b3..771c19241bcd6 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT007_tuple_of_tuples.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT007_tuple_of_tuples.snap @@ -13,10 +13,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` of `tu | help: Use `tuple` of `tuple` for parameter values | -22 | ( - - [1, 2], +23 - [1, 2], 23 + (1, 2), -24 | [3, 4], | note: This is an unsafe fix and may change runtime behavior @@ -32,10 +30,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` of `tu | help: Use `tuple` of `tuple` for parameter values | -23 | [1, 2], - - [3, 4], +24 - [3, 4], 24 + (3, 4), -25 | ), | note: This is an unsafe fix and may change runtime behavior @@ -49,10 +45,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` | help: Use `tuple` for parameter values | -30 | - - @pytest.mark.parametrize("param", [1, 2]) +31 - @pytest.mark.parametrize("param", [1, 2]) 31 + @pytest.mark.parametrize("param", (1, 2)) -32 | def test_list(param): | note: This is an unsafe fix and may change runtime behavior @@ -71,14 +65,10 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` of `tu | help: Use `tuple` of `tuple` for parameter values | -37 | ("param1", "param2"), - - [ -38 + ( +38 ~ ( 39 | (1, 2), 40 | (3, 4), - - ], -41 + ), -42 | ) +41 ~ ), | note: This is an unsafe fix and may change runtime behavior @@ -97,14 +87,10 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` of `tu | help: Use `tuple` of `tuple` for parameter values | -48 | ("param1", "param2"), - - [ -49 + ( +49 ~ ( 50 | [1, 2], 51 | [3, 4], - - ], -52 + ), -53 | ) +52 ~ ), | note: This is an unsafe fix and may change runtime behavior @@ -120,10 +106,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` of `tu | help: Use `tuple` of `tuple` for parameter values | -49 | [ - - [1, 2], +50 - [1, 2], 50 + (1, 2), -51 | [3, 4], | note: This is an unsafe fix and may change runtime behavior @@ -139,10 +123,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` of `tu | help: Use `tuple` of `tuple` for parameter values | -50 | [1, 2], - - [3, 4], +51 - [3, 4], 51 + (3, 4), -52 | ], | note: This is an unsafe fix and may change runtime behavior @@ -161,14 +143,10 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` of `tu | help: Use `tuple` of `tuple` for parameter values | -59 | "param1,param2", - - [ -60 + ( +60 ~ ( 61 | [1, 2], 62 | [3, 4], - - ], -63 + ), -64 | ) +63 ~ ), | note: This is an unsafe fix and may change runtime behavior @@ -184,10 +162,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` of `tu | help: Use `tuple` of `tuple` for parameter values | -60 | [ - - [1, 2], +61 - [1, 2], 61 + (1, 2), -62 | [3, 4], | note: This is an unsafe fix and may change runtime behavior @@ -203,10 +179,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` of `tu | help: Use `tuple` of `tuple` for parameter values | -61 | [1, 2], - - [3, 4], +62 - [3, 4], 62 + (3, 4), -63 | ], | note: This is an unsafe fix and may change runtime behavior @@ -225,14 +199,10 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` | help: Use `tuple` for parameter values | -70 | "param", - - [ -71 + ( +71 ~ ( 72 | [1, 2], 73 | [3, 4], - - ], -74 + ), -75 | ) +74 ~ ), | note: This is an unsafe fix and may change runtime behavior @@ -246,10 +216,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` | help: Use `tuple` for parameter values | -79 | - - @pytest.mark.parametrize("a", [1, 2]) +80 - @pytest.mark.parametrize("a", [1, 2]) 80 + @pytest.mark.parametrize("a", (1, 2)) -81 | @pytest.mark.parametrize(("b", "c"), ((3, 4), (5, 6))) | note: This is an unsafe fix and may change runtime behavior @@ -265,10 +233,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` | help: Use `tuple` for parameter values | -81 | @pytest.mark.parametrize(("b", "c"), ((3, 4), (5, 6))) - - @pytest.mark.parametrize("d", [3,]) +82 - @pytest.mark.parametrize("d", [3,]) 82 + @pytest.mark.parametrize("d", (3,)) -83 | @pytest.mark.parametrize( | note: This is an unsafe fix and may change runtime behavior @@ -284,10 +250,8 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` | help: Use `tuple` for parameter values | -84 | "d", - - [("3", "4")], +85 - [("3", "4")], 85 + (("3", "4"),), -86 | ) | note: This is an unsafe fix and may change runtime behavior @@ -303,9 +267,7 @@ PT007 [*] Wrong values type in `pytest.mark.parametrize` expected `tuple` | help: Use `tuple` for parameter values | -88 | "e", - - [("3", "4"),], +89 - [("3", "4"),], 89 + (("3", "4"),), -90 | ) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT009.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT009.snap index abf2f69567858..94be0465c6c25 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT009.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT009.snap @@ -13,10 +13,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertTrue` | help: Replace `assertTrue(...)` with `assert ...` | -10 | msg = "Must be True" - - self.assertTrue(expr) # Error +11 - self.assertTrue(expr) # Error 11 + assert expr # Error -12 | self.assertTrue(expr=expr) # Error | note: This is an unsafe fix and may change runtime behavior @@ -32,10 +30,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertTrue` | help: Replace `assertTrue(...)` with `assert ...` | -11 | self.assertTrue(expr) # Error - - self.assertTrue(expr=expr) # Error +12 - self.assertTrue(expr=expr) # Error 12 + assert expr # Error -13 | self.assertTrue(expr, msg) # Error | note: This is an unsafe fix and may change runtime behavior @@ -51,10 +47,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertTrue` | help: Replace `assertTrue(...)` with `assert ...` | -12 | self.assertTrue(expr=expr) # Error - - self.assertTrue(expr, msg) # Error +13 - self.assertTrue(expr, msg) # Error 13 + assert expr, msg # Error -14 | self.assertTrue(expr=expr, msg=msg) # Error | note: This is an unsafe fix and may change runtime behavior @@ -70,10 +64,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertTrue` | help: Replace `assertTrue(...)` with `assert ...` | -13 | self.assertTrue(expr, msg) # Error - - self.assertTrue(expr=expr, msg=msg) # Error +14 - self.assertTrue(expr=expr, msg=msg) # Error 14 + assert expr, msg # Error -15 | self.assertTrue(msg=msg, expr=expr) # Error | note: This is an unsafe fix and may change runtime behavior @@ -89,10 +81,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertTrue` | help: Replace `assertTrue(...)` with `assert ...` | -14 | self.assertTrue(expr=expr, msg=msg) # Error - - self.assertTrue(msg=msg, expr=expr) # Error +15 - self.assertTrue(msg=msg, expr=expr) # Error 15 + assert expr, msg # Error -16 | self.assertTrue(*(expr, msg)) # Error, unfixable | note: This is an unsafe fix and may change runtime behavior @@ -191,10 +181,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertFalse` | help: Replace `assertFalse(...)` with `assert ...` | -27 | def test_assert_false(self): - - self.assertFalse(True) # Error +28 - self.assertFalse(True) # Error 28 + assert not True # Error -29 | | note: This is an unsafe fix and may change runtime behavior @@ -209,10 +197,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertEqual` | help: Replace `assertEqual(...)` with `assert ...` | -30 | def test_assert_equal(self): - - self.assertEqual(1, 2) # Error +31 - self.assertEqual(1, 2) # Error 31 + assert 1 == 2 # Error -32 | | note: This is an unsafe fix and may change runtime behavior @@ -227,10 +213,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertNotEqual` | help: Replace `assertNotEqual(...)` with `assert ...` | -33 | def test_assert_not_equal(self): - - self.assertNotEqual(1, 1) # Error +34 - self.assertNotEqual(1, 1) # Error 34 + assert 1 != 1 # Error -35 | | note: This is an unsafe fix and may change runtime behavior @@ -245,10 +229,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertGreater` | help: Replace `assertGreater(...)` with `assert ...` | -36 | def test_assert_greater(self): - - self.assertGreater(1, 2) # Error +37 - self.assertGreater(1, 2) # Error 37 + assert 1 > 2 # Error -38 | | note: This is an unsafe fix and may change runtime behavior @@ -263,10 +245,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertGreaterEqual` | help: Replace `assertGreaterEqual(...)` with `assert ...` | -39 | def test_assert_greater_equal(self): - - self.assertGreaterEqual(1, 2) # Error +40 - self.assertGreaterEqual(1, 2) # Error 40 + assert 1 >= 2 # Error -41 | | note: This is an unsafe fix and may change runtime behavior @@ -281,10 +261,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertLess` | help: Replace `assertLess(...)` with `assert ...` | -42 | def test_assert_less(self): - - self.assertLess(2, 1) # Error +43 - self.assertLess(2, 1) # Error 43 + assert 2 < 1 # Error -44 | | note: This is an unsafe fix and may change runtime behavior @@ -299,10 +277,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertLessEqual` | help: Replace `assertLessEqual(...)` with `assert ...` | -45 | def test_assert_less_equal(self): - - self.assertLessEqual(1, 2) # Error +46 - self.assertLessEqual(1, 2) # Error 46 + assert 1 <= 2 # Error -47 | | note: This is an unsafe fix and may change runtime behavior @@ -317,10 +293,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertIn` | help: Replace `assertIn(...)` with `assert ...` | -48 | def test_assert_in(self): - - self.assertIn(1, [2, 3]) # Error +49 - self.assertIn(1, [2, 3]) # Error 49 + assert 1 in [2, 3] # Error -50 | | note: This is an unsafe fix and may change runtime behavior @@ -335,10 +309,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertNotIn` | help: Replace `assertNotIn(...)` with `assert ...` | -51 | def test_assert_not_in(self): - - self.assertNotIn(2, [2, 3]) # Error +52 - self.assertNotIn(2, [2, 3]) # Error 52 + assert 2 not in [2, 3] # Error -53 | | note: This is an unsafe fix and may change runtime behavior @@ -353,10 +325,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertIsNone` | help: Replace `assertIsNone(...)` with `assert ...` | -54 | def test_assert_is_none(self): - - self.assertIsNone(0) # Error +55 - self.assertIsNone(0) # Error 55 + assert 0 is None # Error -56 | | note: This is an unsafe fix and may change runtime behavior @@ -371,10 +341,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertIsNotNone` | help: Replace `assertIsNotNone(...)` with `assert ...` | -57 | def test_assert_is_not_none(self): - - self.assertIsNotNone(0) # Error +58 - self.assertIsNotNone(0) # Error 58 + assert 0 is not None # Error -59 | | note: This is an unsafe fix and may change runtime behavior @@ -389,10 +357,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertIs` | help: Replace `assertIs(...)` with `assert ...` | -60 | def test_assert_is(self): - - self.assertIs([], []) # Error +61 - self.assertIs([], []) # Error 61 + assert [] is [] # Error -62 | | note: This is an unsafe fix and may change runtime behavior @@ -407,10 +373,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertIsNot` | help: Replace `assertIsNot(...)` with `assert ...` | -63 | def test_assert_is_not(self): - - self.assertIsNot(1, 1) # Error +64 - self.assertIsNot(1, 1) # Error 64 + assert 1 is not 1 # Error -65 | | note: This is an unsafe fix and may change runtime behavior @@ -425,10 +389,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertIsInstance` | help: Replace `assertIsInstance(...)` with `assert ...` | -66 | def test_assert_is_instance(self): - - self.assertIsInstance(1, str) # Error +67 - self.assertIsInstance(1, str) # Error 67 + assert isinstance(1, str) # Error -68 | | note: This is an unsafe fix and may change runtime behavior @@ -443,10 +405,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertNotIsInstance` | help: Replace `assertNotIsInstance(...)` with `assert ...` | -69 | def test_assert_is_not_instance(self): - - self.assertNotIsInstance(1, int) # Error +70 - self.assertNotIsInstance(1, int) # Error 70 + assert not isinstance(1, int) # Error -71 | | note: This is an unsafe fix and may change runtime behavior @@ -461,10 +421,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertRegex` | help: Replace `assertRegex(...)` with `assert ...` | -72 | def test_assert_regex(self): - - self.assertRegex("abc", r"def") # Error +73 - self.assertRegex("abc", r"def") # Error 73 + assert re.search(r"def", "abc") # Error -74 | | note: This is an unsafe fix and may change runtime behavior @@ -479,10 +437,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertNotRegex` | help: Replace `assertNotRegex(...)` with `assert ...` | -75 | def test_assert_not_regex(self): - - self.assertNotRegex("abc", r"abc") # Error +76 - self.assertNotRegex("abc", r"abc") # Error 76 + assert not re.search(r"abc", "abc") # Error -77 | | note: This is an unsafe fix and may change runtime behavior @@ -497,10 +453,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertRegexpMatches` | help: Replace `assertRegexpMatches(...)` with `assert ...` | -78 | def test_assert_regexp_matches(self): - - self.assertRegexpMatches("abc", r"def") # Error +79 - self.assertRegexpMatches("abc", r"def") # Error 79 + assert re.search(r"def", "abc") # Error -80 | | note: This is an unsafe fix and may change runtime behavior @@ -515,10 +469,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertNotRegex` | help: Replace `assertNotRegex(...)` with `assert ...` | -81 | def test_assert_not_regexp_matches(self): - - self.assertNotRegex("abc", r"abc") # Error +82 - self.assertNotRegex("abc", r"abc") # Error 82 + assert not re.search(r"abc", "abc") # Error -83 | | note: This is an unsafe fix and may change runtime behavior @@ -533,10 +485,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `failIf` | help: Replace `failIf(...)` with `assert ...` | -84 | def test_fail_if(self): - - self.failIf("abc") # Error +85 - self.failIf("abc") # Error 85 + assert not "abc" # Error -86 | | note: This is an unsafe fix and may change runtime behavior @@ -551,10 +501,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `failUnless` | help: Replace `failUnless(...)` with `assert ...` | -87 | def test_fail_unless(self): - - self.failUnless("abc") # Error +88 - self.failUnless("abc") # Error 88 + assert "abc" # Error -89 | | note: This is an unsafe fix and may change runtime behavior @@ -569,10 +517,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `failUnlessEqual` | help: Replace `failUnlessEqual(...)` with `assert ...` | -90 | def test_fail_unless_equal(self): - - self.failUnlessEqual(1, 2) # Error +91 - self.failUnlessEqual(1, 2) # Error 91 + assert 1 == 2 # Error -92 | | note: This is an unsafe fix and may change runtime behavior @@ -584,10 +530,8 @@ PT009 [*] Use a regular `assert` instead of unittest-style `failIfEqual` | ^^^^^^^^^^^^^^^^ help: Replace `failIfEqual(...)` with `assert ...` | -93 | def test_fail_if_equal(self): - - self.failIfEqual(1, 2) # Error +94 - self.failIfEqual(1, 2) # Error 94 + assert 1 != 2 # Error -95 | | note: This is an unsafe fix and may change runtime behavior @@ -601,11 +545,10 @@ PT009 [*] Use a regular `assert` instead of unittest-style `assertTrue` 100 | self.model.piAx_piAy_beta[r][x][y]))) | help: Replace `assertTrue(...)` with `assert ...` - | -97 | # Regression test for: https://github.com/astral-sh/ruff/issues/7455#issuecomment-1722459517 - - (self.assertTrue( - - "piAx_piAy_beta[r][x][y] = {17}".format( - - self.model.piAx_piAy_beta[r][x][y]))) -98 + assert "piAx_piAy_beta[r][x][y] = {17}".format(self.model.piAx_piAy_beta[r][x][y]) - | + | + 98 - (self.assertTrue( + 99 - "piAx_piAy_beta[r][x][y] = {17}".format( +100 - self.model.piAx_piAy_beta[r][x][y]))) + 98 + assert "piAx_piAy_beta[r][x][y] = {17}".format(self.model.piAx_piAy_beta[r][x][y]) + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT014.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT014.snap index 63dd2b8e8cf72..c4df18772758d 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT014.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT014.snap @@ -11,10 +11,8 @@ PT014 [*] Duplicate of test case at index 0 in `pytest.mark.parametrize` | help: Remove duplicate test case | -3 | - - @pytest.mark.parametrize("x", [1, 1, 2]) +4 - @pytest.mark.parametrize("x", [1, 1, 2]) 4 + @pytest.mark.parametrize("x", [1, 2]) -5 | def test_error_literal(x): | note: This is an unsafe fix and may change runtime behavior @@ -28,10 +26,8 @@ PT014 [*] Duplicate of test case at index 0 in `pytest.mark.parametrize` | help: Remove duplicate test case | -13 | - - @pytest.mark.parametrize("x", [a, a, b, b, b, c]) +14 - @pytest.mark.parametrize("x", [a, a, b, b, b, c]) 14 + @pytest.mark.parametrize("x", [a, b, b, b, c]) -15 | def test_error_expr_simple(x): | note: This is an unsafe fix and may change runtime behavior @@ -45,10 +41,8 @@ PT014 [*] Duplicate of test case at index 2 in `pytest.mark.parametrize` | help: Remove duplicate test case | -13 | - - @pytest.mark.parametrize("x", [a, a, b, b, b, c]) +14 - @pytest.mark.parametrize("x", [a, a, b, b, b, c]) 14 + @pytest.mark.parametrize("x", [a, a, b, b, c]) -15 | def test_error_expr_simple(x): | note: This is an unsafe fix and may change runtime behavior @@ -62,10 +56,8 @@ PT014 [*] Duplicate of test case at index 2 in `pytest.mark.parametrize` | help: Remove duplicate test case | -13 | - - @pytest.mark.parametrize("x", [a, a, b, b, b, c]) +14 - @pytest.mark.parametrize("x", [a, a, b, b, b, c]) 14 + @pytest.mark.parametrize("x", [a, a, b, b, c]) -15 | def test_error_expr_simple(x): | note: This is an unsafe fix and may change runtime behavior @@ -91,10 +83,8 @@ PT014 [*] Duplicate of test case at index 0 in `pytest.mark.parametrize` | help: Remove duplicate test case | -31 | - - @pytest.mark.parametrize("x", [a, b, (a), c, ((a))]) +32 - @pytest.mark.parametrize("x", [a, b, (a), c, ((a))]) 32 + @pytest.mark.parametrize("x", [a, b, c, ((a))]) -33 | def test_error_parentheses(x): | note: This is an unsafe fix and may change runtime behavior @@ -108,10 +98,8 @@ PT014 [*] Duplicate of test case at index 0 in `pytest.mark.parametrize` | help: Remove duplicate test case | -31 | - - @pytest.mark.parametrize("x", [a, b, (a), c, ((a))]) +32 - @pytest.mark.parametrize("x", [a, b, (a), c, ((a))]) 32 + @pytest.mark.parametrize("x", [a, b, (a), c]) -33 | def test_error_parentheses(x): | note: This is an unsafe fix and may change runtime behavior @@ -127,9 +115,9 @@ PT014 [*] Duplicate of test case at index 0 in `pytest.mark.parametrize` | help: Remove duplicate test case | -41 | b, - - (a), -42 | c, +41 - b, +42 - (a), +41 + b, | note: This is an unsafe fix and may change runtime behavior @@ -145,9 +133,9 @@ PT014 [*] Duplicate of test case at index 0 in `pytest.mark.parametrize` | help: Remove duplicate test case | -43 | c, - - ((a)), -44 | ], +43 - c, +44 - ((a)), +43 + c, | note: This is an unsafe fix and may change runtime behavior @@ -161,9 +149,7 @@ PT014 [*] Duplicate of test case at index 0 in `pytest.mark.parametrize` | help: Remove duplicate test case | -55 | - - @pytest.mark.parametrize('data, spec', [(1.0, 1.0), (1.0, 1.0)]) +56 - @pytest.mark.parametrize('data, spec', [(1.0, 1.0), (1.0, 1.0)]) 56 + @pytest.mark.parametrize('data, spec', [(1.0, 1.0)]) -57 | def test_numbers(data, spec): | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT018.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT018.snap index 15b8ed2c4a9a7..d361021f45e4a 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT018.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT018.snap @@ -1,6 +1,5 @@ --- source: crates/ruff_linter/src/rules/flake8_pytest_style/mod.rs -assertion_line: 358 --- PT018 [*] Assertion should be broken down into multiple parts --> PT018.py:14:5 @@ -13,11 +12,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -13 | def test_error(): - - assert something and something_else 14 + assert something 15 + assert something_else -16 | assert something and something_else and something_third | note: This is an unsafe fix and may change runtime behavior @@ -33,11 +29,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -14 | assert something and something_else - - assert something and something_else and something_third 15 + assert something and something_else 16 + assert something_third -17 | assert something and not something_else | note: This is an unsafe fix and may change runtime behavior @@ -53,11 +46,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -15 | assert something and something_else and something_third - - assert something and not something_else 16 + assert something 17 + assert not something_else -18 | assert something and (something_else or something_third) | note: This is an unsafe fix and may change runtime behavior @@ -73,11 +63,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -16 | assert something and not something_else - - assert something and (something_else or something_third) 17 + assert something 18 + assert (something_else or something_third) -19 | assert not something and something_else | note: This is an unsafe fix and may change runtime behavior @@ -93,11 +80,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -17 | assert something and (something_else or something_third) - - assert not something and something_else 18 + assert not something 19 + assert something_else -20 | assert not (something or something_else) | note: This is an unsafe fix and may change runtime behavior @@ -113,11 +97,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -18 | assert not something and something_else - - assert not (something or something_else) 19 + assert not something 20 + assert not something_else -21 | assert not (something or something_else or something_third) | note: This is an unsafe fix and may change runtime behavior @@ -133,11 +114,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -19 | assert not (something or something_else) - - assert not (something or something_else or something_third) 20 + assert not (something or something_else) 21 + assert not something_third -22 | assert something and something_else == """error | note: This is an unsafe fix and may change runtime behavior @@ -155,11 +133,10 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -20 | assert not (something or something_else or something_third) - - assert something and something_else == """error 21 + assert something 22 + assert something_else == """error -23 | message +23 + message +24 + """ | note: This is an unsafe fix and may change runtime behavior @@ -181,13 +158,13 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -23 | """ 24 + assert something -25 | assert ( - - something - - and something_else +25 + assert ( 26 + something_else -27 | == """error +27 + == """error +28 + message +29 + """ +30 + ) | note: This is an unsafe fix and may change runtime behavior @@ -201,11 +178,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -32 | # recursive case - - assert not (a or not (b or c)) 33 + assert not a 34 + assert (b or c) -35 | assert not (a or not (b and c)) | note: This is an unsafe fix and may change runtime behavior @@ -221,11 +195,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -33 | assert not (a or not (b or c)) - - assert not (a or not (b and c)) 34 + assert not a 35 + assert (b and c) -36 | | note: This is an unsafe fix and may change runtime behavior @@ -271,11 +242,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -43 | assert something # OK - - assert something and something_else # Error 44 + assert something 45 + assert something_else -46 | assert something and something_else and something_third # Error | note: This is an unsafe fix and may change runtime behavior @@ -288,11 +256,8 @@ PT018 [*] Assertion should be broken down into multiple parts | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Break down assertion into multiple parts | -44 | assert something and something_else # Error - - assert something and something_else and something_third # Error 45 + assert something and something_else 46 + assert something_third -47 | | note: This is an unsafe fix and may change runtime behavior @@ -343,13 +308,13 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -61 | or self.find_graph_input(node.input[0]) - - or self.find_graph_output(node.input[0]) -62 | ) +59 + assert not ( +60 + self.find_graph_output(node.output[0]) +61 + or self.find_graph_input(node.input[0]) +62 + ) 63 + assert not ( 64 + self.find_graph_output(node.input[0]) 65 + ) -66 | | note: This is an unsafe fix and may change runtime behavior @@ -369,18 +334,13 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -64 | - - assert (not ( 65 + assert not ( -66 | self.find_graph_output(node.output[0]) -67 | or self.find_graph_input(node.input[0]) - - or self.find_graph_output(node.input[0]) - - )) +66 + self.find_graph_output(node.output[0]) +67 + or self.find_graph_input(node.input[0]) 68 + ) 69 + assert not ( 70 + self.find_graph_output(node.input[0]) 71 + ) -72 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT022.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT022.snap index b460eb6e9ea09..1e9252cd81c20 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT022.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT022.snap @@ -10,10 +10,8 @@ PT022 [*] No teardown in fixture `error`, use `return` instead of `yield` | ^^^^^^^^^^^^^^ help: Replace `yield` with `return` | -16 | resource = acquire_resource() - - yield resource +17 - yield resource 17 + return resource -18 | | note: This is an unsafe fix and may change runtime behavior @@ -26,13 +24,9 @@ PT022 [*] No teardown in fixture `error`, use `return` instead of `yield` | ^^^^^^^^^^^^^^ help: Replace `yield` with `return` | -34 | @pytest.fixture() - - def error() -> typing.Generator[typing.Any, None, None]: -35 + def error() -> typing.Any: +35 ~ def error() -> typing.Any: 36 | resource = acquire_resource() - - yield resource -37 + return resource -38 | +37 ~ return resource | note: This is an unsafe fix and may change runtime behavior @@ -45,11 +39,8 @@ PT022 [*] No teardown in fixture `error`, use `return` instead of `yield` | ^^^^^^^^^^^^^^ help: Replace `yield` with `return` | -40 | @pytest.fixture() - - def error() -> Generator[Resource, None, None]: -41 + def error() -> Resource: +41 ~ def error() -> Resource: 42 | resource = acquire_resource() - - yield resource -43 + return resource +43 ~ return resource | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT023_default.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT023_default.snap index e6aacd6bdd3d4..18a47745aeca9 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT023_default.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT023_default.snap @@ -11,10 +11,8 @@ PT023 [*] Use `@pytest.mark.foo` over `@pytest.mark.foo()` | help: Remove parentheses | -50 | - - @pytest.mark.foo() +51 - @pytest.mark.foo() 51 + @pytest.mark.foo -52 | def test_something(): | PT023 [*] Use `@pytest.mark.foo` over `@pytest.mark.foo()` @@ -27,10 +25,8 @@ PT023 [*] Use `@pytest.mark.foo` over `@pytest.mark.foo()` | help: Remove parentheses | -55 | - - @pytest.mark.foo() +56 - @pytest.mark.foo() 56 + @pytest.mark.foo -57 | class TestClass: | PT023 [*] Use `@pytest.mark.foo` over `@pytest.mark.foo()` @@ -44,10 +40,8 @@ PT023 [*] Use `@pytest.mark.foo` over `@pytest.mark.foo()` | help: Remove parentheses | -62 | class TestClass: - - @pytest.mark.foo() +63 - @pytest.mark.foo() 63 + @pytest.mark.foo -64 | def test_something(): | PT023 [*] Use `@pytest.mark.foo` over `@pytest.mark.foo()` @@ -61,10 +55,8 @@ PT023 [*] Use `@pytest.mark.foo` over `@pytest.mark.foo()` | help: Remove parentheses | -68 | class TestClass: - - @pytest.mark.foo() +69 - @pytest.mark.foo() 69 + @pytest.mark.foo -70 | class TestNestedClass: | PT023 [*] Use `@pytest.mark.foo` over `@pytest.mark.foo()` @@ -79,10 +71,8 @@ PT023 [*] Use `@pytest.mark.foo` over `@pytest.mark.foo()` | help: Remove parentheses | -76 | class TestNestedClass: - - @pytest.mark.foo() +77 - @pytest.mark.foo() 77 + @pytest.mark.foo -78 | def test_something(): | PT023 [*] Use `@pytest.mark.parametrize` over `@pytest.mark.parametrize()` @@ -102,17 +92,15 @@ PT023 [*] Use `@pytest.mark.parametrize` over `@pytest.mark.parametrize()` | help: Remove parentheses | -81 | # https://github.com/astral-sh/ruff/issues/18770 - - @pytest.mark.parametrize( - - # TODO: fix later - - # ("param1", "param2"), - - # ( - - # (1, 2), - - # (3, 4), - - # ), - - ) +82 - @pytest.mark.parametrize( +83 - # TODO: fix later +84 - # ("param1", "param2"), +85 - # ( +86 - # (1, 2), +87 - # (3, 4), +88 - # ), +89 - ) 82 + @pytest.mark.parametrize -83 | def test_bar(param1, param2): ... | note: This is an unsafe fix and may change runtime behavior @@ -126,10 +114,8 @@ PT023 [*] Use `@pytest.mark.foo` over `@pytest.mark.foo()` | help: Remove parentheses | -92 | - - @(pytest.mark.foo()) +93 - @(pytest.mark.foo()) 93 + @(pytest.mark.foo) -94 | def test_outer_paren_mark_function(): | PT023 [*] Use `@pytest.mark.foo` over `@pytest.mark.foo()` @@ -142,9 +128,7 @@ PT023 [*] Use `@pytest.mark.foo` over `@pytest.mark.foo()` 101 | pass | help: Remove parentheses - | -98 | class TestClass: - - @(pytest.mark.foo()) -99 + @(pytest.mark.foo) -100 | def test_method_outer_paren(): - | + | +99 - @(pytest.mark.foo()) +99 + @(pytest.mark.foo) + | diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT023_parentheses.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT023_parentheses.snap index a7b3a051d0875..b8ddd9712c640 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT023_parentheses.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT023_parentheses.snap @@ -11,11 +11,8 @@ PT023 [*] Use `@pytest.mark.foo()` over `@pytest.mark.foo` | help: Add parentheses | -16 | - - @pytest.mark.foo -17 + @pytest.mark.foo() -18 | def test_something(): - | +17 | @pytest.mark.foo() + | ++ PT023 [*] Use `@pytest.mark.foo()` over `@pytest.mark.foo` --> PT023.py:22:1 @@ -27,11 +24,8 @@ PT023 [*] Use `@pytest.mark.foo()` over `@pytest.mark.foo` | help: Add parentheses | -21 | - - @pytest.mark.foo -22 + @pytest.mark.foo() -23 | class TestClass: - | +22 | @pytest.mark.foo() + | ++ PT023 [*] Use `@pytest.mark.foo()` over `@pytest.mark.foo` --> PT023.py:29:5 @@ -44,11 +38,8 @@ PT023 [*] Use `@pytest.mark.foo()` over `@pytest.mark.foo` | help: Add parentheses | -28 | class TestClass: - - @pytest.mark.foo -29 + @pytest.mark.foo() -30 | def test_something(): - | +29 | @pytest.mark.foo() + | ++ PT023 [*] Use `@pytest.mark.foo()` over `@pytest.mark.foo` --> PT023.py:35:5 @@ -61,11 +52,8 @@ PT023 [*] Use `@pytest.mark.foo()` over `@pytest.mark.foo` | help: Add parentheses | -34 | class TestClass: - - @pytest.mark.foo -35 + @pytest.mark.foo() -36 | class TestNestedClass: - | +35 | @pytest.mark.foo() + | ++ PT023 [*] Use `@pytest.mark.foo()` over `@pytest.mark.foo` --> PT023.py:43:9 @@ -79,8 +67,5 @@ PT023 [*] Use `@pytest.mark.foo()` over `@pytest.mark.foo` | help: Add parentheses | -42 | class TestNestedClass: - - @pytest.mark.foo -43 + @pytest.mark.foo() -44 | def test_something(): - | +43 | @pytest.mark.foo() + | ++ diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT024.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT024.snap index d72b115a53c8a..96256af6ebf80 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT024.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT024.snap @@ -11,9 +11,7 @@ PT024 [*] `pytest.mark.asyncio` is unnecessary for fixtures | help: Remove `pytest.mark.asyncio` | -13 | - - @pytest.mark.asyncio() -14 | @pytest.fixture() +14 - @pytest.mark.asyncio() | PT024 [*] `pytest.mark.asyncio` is unnecessary for fixtures @@ -26,9 +24,7 @@ PT024 [*] `pytest.mark.asyncio` is unnecessary for fixtures | help: Remove `pytest.mark.asyncio` | -19 | - - @pytest.mark.asyncio -20 | @pytest.fixture() +20 - @pytest.mark.asyncio | PT024 [*] `pytest.mark.asyncio` is unnecessary for fixtures @@ -42,9 +38,7 @@ PT024 [*] `pytest.mark.asyncio` is unnecessary for fixtures | help: Remove `pytest.mark.asyncio` | -26 | @pytest.fixture() - - @pytest.mark.asyncio() -27 | async def my_fixture(): # Error after +27 - @pytest.mark.asyncio() | PT024 [*] `pytest.mark.asyncio` is unnecessary for fixtures @@ -58,7 +52,5 @@ PT024 [*] `pytest.mark.asyncio` is unnecessary for fixtures | help: Remove `pytest.mark.asyncio` | -32 | @pytest.fixture() - - @pytest.mark.asyncio -33 | async def my_fixture(): # Error after no parens +33 - @pytest.mark.asyncio | diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT025.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT025.snap index 52d660139a272..b1a93982e358a 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT025.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT025.snap @@ -10,11 +10,9 @@ PT025 [*] `pytest.mark.usefixtures` has no effect on fixtures 11 | def my_fixture(): # Error before | help: Remove `pytest.mark.usefixtures` - | -8 | - - @pytest.mark.usefixtures("a") -9 | @pytest.fixture() - | + | + 9 - @pytest.mark.usefixtures("a") + | PT025 [*] `pytest.mark.usefixtures` has no effect on fixtures --> PT025.py:16:1 @@ -27,7 +25,5 @@ PT025 [*] `pytest.mark.usefixtures` has no effect on fixtures | help: Remove `pytest.mark.usefixtures` | -15 | @pytest.fixture() - - @pytest.mark.usefixtures("a") -16 | def my_fixture(): # Error after +16 - @pytest.mark.usefixtures("a") | diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT026.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT026.snap index 2bc1f72ad95d7..881e957d4828e 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT026.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT026.snap @@ -11,10 +11,7 @@ PT026 [*] Useless `pytest.mark.usefixtures` without parameters | help: Remove `usefixtures` decorator or pass parameters | -18 | - - @pytest.mark.usefixtures() -19 + -20 | def test_error_with_parens(): +19 - @pytest.mark.usefixtures() | note: This is an unsafe fix and may change runtime behavior @@ -28,9 +25,6 @@ PT026 [*] Useless `pytest.mark.usefixtures` without parameters | help: Remove `usefixtures` decorator or pass parameters | -23 | - - @pytest.mark.usefixtures -24 + -25 | def test_error_no_parens(): +24 - @pytest.mark.usefixtures | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT027_0.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT027_0.snap index 8432288af2799..07076907cd4f6 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT027_0.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT027_0.snap @@ -13,15 +13,12 @@ PT027 [*] Use `pytest.raises` instead of unittest-style `assertRaises` | help: Replace `assertRaises` with `pytest.raises` | -1 | import unittest 2 + import pytest -3 | +3 + 4 | 5 | class Test(unittest.TestCase): 6 | def test_errors(self): - - with self.assertRaises(ValueError): -7 + with pytest.raises(ValueError): -8 | raise ValueError +7 ~ with pytest.raises(ValueError): | note: This is an unsafe fix and may change runtime behavior @@ -35,16 +32,14 @@ PT027 [*] Use `pytest.raises` instead of unittest-style `assertRaises` 9 | raise ValueError | help: Replace `assertRaises` with `pytest.raises` - | -1 | import unittest -2 + import pytest -3 | --------------------------------------------------------------------------------- -8 | raise ValueError - - with self.assertRaises(expected_exception=ValueError): -9 + with pytest.raises(ValueError): -10 | raise ValueError - | + | +2 + import pytest +3 + +4 | +… +8 | raise ValueError +9 ~ with pytest.raises(ValueError): + | note: This is an unsafe fix and may change runtime behavior PT027 [*] Use `pytest.raises` instead of unittest-style `failUnlessRaises` @@ -58,14 +53,12 @@ PT027 [*] Use `pytest.raises` instead of unittest-style `failUnlessRaises` | help: Replace `failUnlessRaises` with `pytest.raises` | -1 | import unittest -2 + import pytest -3 | --------------------------------------------------------------------------------- + 2 + import pytest + 3 + + 4 | + … 11 | - - with self.failUnlessRaises(ValueError): -12 + with pytest.raises(ValueError): -13 | raise ValueError +12 ~ with pytest.raises(ValueError): | note: This is an unsafe fix and may change runtime behavior @@ -80,14 +73,12 @@ PT027 [*] Use `pytest.raises` instead of unittest-style `assertRaisesRegex` | help: Replace `assertRaisesRegex` with `pytest.raises` | -1 | import unittest -2 + import pytest -3 | --------------------------------------------------------------------------------- + 2 + import pytest + 3 + + 4 | + … 14 | - - with self.assertRaisesRegex(ValueError, "test"): -15 + with pytest.raises(ValueError, match="test"): -16 | raise ValueError("test") +15 ~ with pytest.raises(ValueError, match="test"): | note: This is an unsafe fix and may change runtime behavior @@ -102,14 +93,12 @@ PT027 [*] Use `pytest.raises` instead of unittest-style `assertRaisesRegex` | help: Replace `assertRaisesRegex` with `pytest.raises` | -1 | import unittest -2 + import pytest -3 | --------------------------------------------------------------------------------- + 2 + import pytest + 3 + + 4 | + … 17 | - - with self.assertRaisesRegex(ValueError, expected_regex="test"): -18 + with pytest.raises(ValueError, match="test"): -19 | raise ValueError("test") +18 ~ with pytest.raises(ValueError, match="test"): | note: This is an unsafe fix and may change runtime behavior @@ -125,16 +114,12 @@ PT027 [*] Use `pytest.raises` instead of unittest-style `assertRaisesRegex` | help: Replace `assertRaisesRegex` with `pytest.raises` | -1 | import unittest -2 + import pytest -3 | --------------------------------------------------------------------------------- + 2 + import pytest + 3 + + 4 | + … 20 | - - with self.assertRaisesRegex( - - expected_exception=ValueError, expected_regex="test" - - ): -21 + with pytest.raises(ValueError, match="test"): -22 | raise ValueError("test") +21 ~ with pytest.raises(ValueError, match="test"): | note: This is an unsafe fix and may change runtime behavior @@ -150,16 +135,12 @@ PT027 [*] Use `pytest.raises` instead of unittest-style `assertRaisesRegex` | help: Replace `assertRaisesRegex` with `pytest.raises` | -1 | import unittest -2 + import pytest -3 | --------------------------------------------------------------------------------- + 2 + import pytest + 3 + + 4 | + … 25 | - - with self.assertRaisesRegex( - - expected_regex="test", expected_exception=ValueError - - ): -26 + with pytest.raises(ValueError, match="test"): -27 | raise ValueError("test") +26 ~ with pytest.raises(ValueError, match="test"): | note: This is an unsafe fix and may change runtime behavior @@ -174,14 +155,12 @@ PT027 [*] Use `pytest.raises` instead of unittest-style `assertRaisesRegexp` | help: Replace `assertRaisesRegexp` with `pytest.raises` | -1 | import unittest -2 + import pytest -3 | --------------------------------------------------------------------------------- + 2 + import pytest + 3 + + 4 | + … 30 | - - with self.assertRaisesRegexp(ValueError, "test"): -31 + with pytest.raises(ValueError, match="test"): -32 | raise ValueError("test") +31 ~ with pytest.raises(ValueError, match="test"): | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT027_1.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT027_1.snap index e0da998271e09..622e65ecc1e44 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT027_1.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT027_1.snap @@ -11,10 +11,11 @@ PT027 [*] Use `pytest.raises` instead of unittest-style `assertRaises` | help: Replace `assertRaises` with `pytest.raises` | + 2 ~ import pytest + 3 | + … 10 | def test_errors(self): - - with self.assertRaises(ValueError): -11 + with pytest.raises(ValueError): -12 | raise ValueError +11 ~ with pytest.raises(ValueError): | note: This is an unsafe fix and may change runtime behavior @@ -28,15 +29,15 @@ PT027 [*] Use `pytest.raises` instead of unittest-style `assertRaises` | help: Replace `assertRaises` with `pytest.raises` | + 2 ~ import pytest + 3 | + … 14 | def test_rewrite_references(self): - - with self.assertRaises(ValueError) as e: -15 + with pytest.raises(ValueError) as e: +15 ~ with pytest.raises(ValueError) as e: 16 | raise ValueError 17 | 18 | print(e.foo) - - print(e.exception) -19 + print(e.value) -20 | +19 ~ print(e.value) | note: This is an unsafe fix and may change runtime behavior @@ -51,16 +52,15 @@ PT027 [*] Use `pytest.raises` instead of unittest-style `assertRaises` | help: Replace `assertRaises` with `pytest.raises` | + 2 ~ import pytest + 3 | + … 21 | def test_rewrite_references_multiple_items(self): - - with self.assertRaises(ValueError) as e1, \ -22 + with pytest.raises(ValueError) as e1, \ +22 ~ with pytest.raises(ValueError) as e1, \ 23 | self.assertRaises(ValueError) as e2: -24 | raise ValueError -25 | + … 26 | print(e1.foo) - - print(e1.exception) -27 + print(e1.value) -28 | +27 ~ print(e1.value) | note: This is an unsafe fix and may change runtime behavior @@ -75,15 +75,15 @@ PT027 [*] Use `pytest.raises` instead of unittest-style `assertRaises` | help: Replace `assertRaises` with `pytest.raises` | + 2 ~ import pytest + 3 | + … 22 | with self.assertRaises(ValueError) as e1, \ - - self.assertRaises(ValueError) as e2: -23 + pytest.raises(ValueError) as e2: +23 ~ pytest.raises(ValueError) as e2: 24 | raise ValueError --------------------------------------------------------------------------------- + … 29 | print(e2.foo) - - print(e2.exception) -30 + print(e2.value) -31 | +30 ~ print(e2.value) | note: This is an unsafe fix and may change runtime behavior @@ -98,16 +98,15 @@ PT027 [*] Use `pytest.raises` instead of unittest-style `assertRaises` | help: Replace `assertRaises` with `pytest.raises` | + 2 ~ import pytest + 3 | + … 32 | def test_rewrite_references_multiple_items_nested(self): - - with self.assertRaises(ValueError) as e1, \ -33 + with pytest.raises(ValueError) as e1, \ +33 ~ with pytest.raises(ValueError) as e1, \ 34 | foo(self.assertRaises(ValueError)) as e2: -35 | raise ValueError -36 | + … 37 | print(e1.foo) - - print(e1.exception) -38 + print(e1.value) -39 | +38 ~ print(e1.value) | note: This is an unsafe fix and may change runtime behavior @@ -122,9 +121,10 @@ PT027 [*] Use `pytest.raises` instead of unittest-style `assertRaises` | help: Replace `assertRaises` with `pytest.raises` | + 2 ~ import pytest + 3 | + … 33 | with self.assertRaises(ValueError) as e1, \ - - foo(self.assertRaises(ValueError)) as e2: -34 + foo(pytest.raises(ValueError)) as e2: -35 | raise ValueError +34 ~ foo(pytest.raises(ValueError)) as e2: | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT028.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT028.snap index 0d4024d9bd2ee..c4577908bac07 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT028.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__PT028.snap @@ -13,10 +13,8 @@ PT028 [*] Test function parameter `a` has default argument | help: Remove default argument | -2 | - - def test_foo(a=1): ... +3 - def test_foo(a=1): ... 3 + def test_foo(a): ... -4 | def test_foo(a = 1): ... | note: This is a display-only fix and is likely to be incorrect @@ -31,10 +29,8 @@ PT028 [*] Test function parameter `a` has default argument | help: Remove default argument | -3 | def test_foo(a=1): ... - - def test_foo(a = 1): ... +4 - def test_foo(a = 1): ... 4 + def test_foo(a): ... -5 | def test_foo(a = (1)): ... | note: This is a display-only fix and is likely to be incorrect @@ -50,10 +46,8 @@ PT028 [*] Test function parameter `a` has default argument | help: Remove default argument | -4 | def test_foo(a = 1): ... - - def test_foo(a = (1)): ... +5 - def test_foo(a = (1)): ... 5 + def test_foo(a): ... -6 | def test_foo(a: int=1): ... | note: This is a display-only fix and is likely to be incorrect @@ -69,10 +63,8 @@ PT028 [*] Test function parameter `a` has default argument | help: Remove default argument | -5 | def test_foo(a = (1)): ... - - def test_foo(a: int=1): ... +6 - def test_foo(a: int=1): ... 6 + def test_foo(a: int): ... -7 | def test_foo(a: int = 1): ... | note: This is a display-only fix and is likely to be incorrect @@ -88,10 +80,8 @@ PT028 [*] Test function parameter `a` has default argument | help: Remove default argument | -6 | def test_foo(a: int=1): ... - - def test_foo(a: int = 1): ... +7 - def test_foo(a: int = 1): ... 7 + def test_foo(a: int): ... -8 | def test_foo(a: (int) = 1): ... | note: This is a display-only fix and is likely to be incorrect @@ -107,10 +97,8 @@ PT028 [*] Test function parameter `a` has default argument | help: Remove default argument | -7 | def test_foo(a: int = 1): ... - - def test_foo(a: (int) = 1): ... +8 - def test_foo(a: (int) = 1): ... 8 + def test_foo(a: (int)): ... -9 | def test_foo(a: int = (1)): ... | note: This is a display-only fix and is likely to be incorrect @@ -125,12 +113,10 @@ PT028 [*] Test function parameter `a` has default argument 11 | def test_foo(a=1, /, b=2, *, c=3): ... | help: Remove default argument - | -8 | def test_foo(a: (int) = 1): ... - - def test_foo(a: int = (1)): ... -9 + def test_foo(a: int): ... -10 | def test_foo(a: (int) = (1)): ... - | + | +9 - def test_foo(a: int = (1)): ... +9 + def test_foo(a: int): ... + | note: This is a display-only fix and is likely to be incorrect PT028 [*] Test function parameter `a` has default argument @@ -144,10 +130,8 @@ PT028 [*] Test function parameter `a` has default argument | help: Remove default argument | -9 | def test_foo(a: int = (1)): ... - - def test_foo(a: (int) = (1)): ... +10 - def test_foo(a: (int) = (1)): ... 10 + def test_foo(a: (int)): ... -11 | def test_foo(a=1, /, b=2, *, c=3): ... | note: This is a display-only fix and is likely to be incorrect @@ -160,10 +144,8 @@ PT028 [*] Test function parameter `a` has default argument | ^ help: Remove default argument | -10 | def test_foo(a: (int) = (1)): ... - - def test_foo(a=1, /, b=2, *, c=3): ... +11 - def test_foo(a=1, /, b=2, *, c=3): ... 11 + def test_foo(a, /, b=2, *, c=3): ... -12 | | note: This is a display-only fix and is likely to be incorrect @@ -176,10 +158,8 @@ PT028 [*] Test function parameter `b` has default argument | ^ help: Remove default argument | -10 | def test_foo(a: (int) = (1)): ... - - def test_foo(a=1, /, b=2, *, c=3): ... +11 - def test_foo(a=1, /, b=2, *, c=3): ... 11 + def test_foo(a=1, /, b, *, c=3): ... -12 | | note: This is a display-only fix and is likely to be incorrect @@ -192,9 +172,7 @@ PT028 [*] Test function parameter `c` has default argument | ^ help: Remove default argument | -10 | def test_foo(a: (int) = (1)): ... - - def test_foo(a=1, /, b=2, *, c=3): ... +11 - def test_foo(a=1, /, b=2, *, c=3): ... 11 + def test_foo(a=1, /, b=2, *, c): ... -12 | | note: This is a display-only fix and is likely to be incorrect diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__is_pytest_test.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__is_pytest_test.snap index c3597dcf9d8e1..3da681e6fa012 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__is_pytest_test.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__is_pytest_test.snap @@ -12,10 +12,8 @@ PT028 [*] Test function parameter `a` has default argument | help: Remove default argument | -2 | - - def test_this_is_a_test(a=1): ... +3 - def test_this_is_a_test(a=1): ... 3 + def test_this_is_a_test(a): ... -4 | def testThisIsAlsoATest(a=1): ... | note: This is a display-only fix and is likely to be incorrect @@ -30,10 +28,8 @@ PT028 [*] Test function parameter `a` has default argument | help: Remove default argument | -3 | def test_this_is_a_test(a=1): ... - - def testThisIsAlsoATest(a=1): ... +4 - def testThisIsAlsoATest(a=1): ... 4 + def testThisIsAlsoATest(a): ... -5 | | note: This is a display-only fix and is likely to be incorrect @@ -47,10 +43,8 @@ PT028 [*] Test function parameter `a` has default argument | help: Remove default argument | -6 | class TestClass: - - def test_this_too_is_a_test(self, a=1): ... +7 - def test_this_too_is_a_test(self, a=1): ... 7 + def test_this_too_is_a_test(self, a): ... -8 | def testAndOfCourseThis(self, a=1): ... | note: This is a display-only fix and is likely to be incorrect @@ -63,9 +57,7 @@ PT028 [*] Test function parameter `a` has default argument | ^ help: Remove default argument | -7 | def test_this_too_is_a_test(self, a=1): ... - - def testAndOfCourseThis(self, a=1): ... +8 - def testAndOfCourseThis(self, a=1): ... 8 + def testAndOfCourseThis(self, a): ... -9 | | note: This is a display-only fix and is likely to be incorrect diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__preview__PT003_PT003.py.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__preview__PT003_PT003.py.snap index f818addc81ac5..1701e3a248219 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__preview__PT003_PT003.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__preview__PT003_PT003.py.snap @@ -22,9 +22,7 @@ PT003 [*] `scope='function'` is implied in `@pytest.fixture()` | help: Remove implied `scope` argument | -74 | - - @pytest_asyncio.fixture(scope="function") +75 - @pytest_asyncio.fixture(scope="function") 75 + @pytest_asyncio.fixture() -76 | async def asyncio_error(): | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__preview__PT018_PT018.py.snap b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__preview__PT018_PT018.py.snap index 1a299ba99a1b2..143041647610c 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__preview__PT018_PT018.py.snap +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/snapshots/ruff_linter__rules__flake8_pytest_style__tests__preview__PT018_PT018.py.snap @@ -1,6 +1,5 @@ --- source: crates/ruff_linter/src/rules/flake8_pytest_style/mod.rs -assertion_line: 389 --- --- Linter settings --- -linter.preview = disabled @@ -22,11 +21,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -13 | def test_error(): - - assert something and something_else 14 + assert something 15 + assert something_else -16 | assert something and something_else and something_third | note: This is an unsafe fix and may change runtime behavior @@ -43,11 +39,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -14 | assert something and something_else - - assert something and something_else and something_third 15 + assert something and something_else 16 + assert something_third -17 | assert something and not something_else | note: This is an unsafe fix and may change runtime behavior @@ -64,11 +57,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -15 | assert something and something_else and something_third - - assert something and not something_else 16 + assert something 17 + assert not something_else -18 | assert something and (something_else or something_third) | note: This is an unsafe fix and may change runtime behavior @@ -85,11 +75,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -16 | assert something and not something_else - - assert something and (something_else or something_third) 17 + assert something 18 + assert (something_else or something_third) -19 | assert not something and something_else | note: This is an unsafe fix and may change runtime behavior @@ -106,11 +93,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -17 | assert something and (something_else or something_third) - - assert not something and something_else 18 + assert not something 19 + assert something_else -20 | assert not (something or something_else) | note: This is an unsafe fix and may change runtime behavior @@ -127,11 +111,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -18 | assert not something and something_else - - assert not (something or something_else) 19 + assert not something 20 + assert not something_else -21 | assert not (something or something_else or something_third) | note: This is an unsafe fix and may change runtime behavior @@ -148,11 +129,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -19 | assert not (something or something_else) - - assert not (something or something_else or something_third) 20 + assert not (something or something_else) 21 + assert not something_third -22 | assert something and something_else == """error | note: This is an unsafe fix and may change runtime behavior @@ -171,11 +149,10 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -20 | assert not (something or something_else or something_third) - - assert something and something_else == """error 21 + assert something 22 + assert something_else == """error -23 | message +23 + message +24 + """ | note: This is an unsafe fix and may change runtime behavior @@ -198,13 +175,13 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -23 | """ 24 + assert something -25 | assert ( - - something - - and something_else +25 + assert ( 26 + something_else -27 | == """error +27 + == """error +28 + message +29 + """ +30 + ) | note: This is an unsafe fix and may change runtime behavior @@ -219,11 +196,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -32 | # recursive case - - assert not (a or not (b or c)) 33 + assert not a 34 + assert (b or c) -35 | assert not (a or not (b and c)) | note: This is an unsafe fix and may change runtime behavior @@ -240,11 +214,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -33 | assert not (a or not (b or c)) - - assert not (a or not (b and c)) 34 + assert not a 35 + assert (b and c) -36 | | note: This is an unsafe fix and may change runtime behavior @@ -265,13 +236,13 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -61 | or self.find_graph_input(node.input[0]) - - or self.find_graph_output(node.input[0]) -62 | ) +59 + assert not ( +60 + self.find_graph_output(node.output[0]) +61 + or self.find_graph_input(node.input[0]) +62 + ) 63 + assert not ( 64 + self.find_graph_output(node.input[0]) 65 + ) -66 | | note: This is an unsafe fix and may change runtime behavior @@ -292,18 +263,13 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -64 | - - assert (not ( 65 + assert not ( -66 | self.find_graph_output(node.output[0]) -67 | or self.find_graph_input(node.input[0]) - - or self.find_graph_output(node.input[0]) - - )) +66 + self.find_graph_output(node.output[0]) +67 + or self.find_graph_input(node.input[0]) 68 + ) 69 + assert not ( 70 + self.find_graph_output(node.input[0]) 71 + ) -72 | | note: This is an unsafe fix and may change runtime behavior @@ -333,11 +299,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -13 | def test_error(): - - assert something and something_else 14 + assert something 15 + assert something_else -16 | assert something and something_else and something_third | @@ -353,11 +316,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -14 | assert something and something_else - - assert something and something_else and something_third 15 + assert something and something_else 16 + assert something_third -17 | assert something and not something_else | @@ -373,11 +333,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -15 | assert something and something_else and something_third - - assert something and not something_else 16 + assert something 17 + assert not something_else -18 | assert something and (something_else or something_third) | @@ -393,11 +350,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -16 | assert something and not something_else - - assert something and (something_else or something_third) 17 + assert something 18 + assert (something_else or something_third) -19 | assert not something and something_else | @@ -413,11 +367,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -17 | assert something and (something_else or something_third) - - assert not something and something_else 18 + assert not something 19 + assert something_else -20 | assert not (something or something_else) | @@ -433,11 +384,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -18 | assert not something and something_else - - assert not (something or something_else) 19 + assert not something 20 + assert not something_else -21 | assert not (something or something_else or something_third) | @@ -453,11 +401,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -19 | assert not (something or something_else) - - assert not (something or something_else or something_third) 20 + assert not (something or something_else) 21 + assert not something_third -22 | assert something and something_else == """error | @@ -475,11 +420,10 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -20 | assert not (something or something_else or something_third) - - assert something and something_else == """error 21 + assert something 22 + assert something_else == """error -23 | message +23 + message +24 + """ | @@ -501,13 +445,13 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -23 | """ 24 + assert something -25 | assert ( - - something - - and something_else +25 + assert ( 26 + something_else -27 | == """error +27 + == """error +28 + message +29 + """ +30 + ) | @@ -521,11 +465,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -32 | # recursive case - - assert not (a or not (b or c)) 33 + assert not a 34 + assert (b or c) -35 | assert not (a or not (b and c)) | @@ -541,11 +482,8 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -33 | assert not (a or not (b or c)) - - assert not (a or not (b and c)) 34 + assert not a 35 + assert (b and c) -36 | | @@ -565,13 +503,13 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -61 | or self.find_graph_input(node.input[0]) - - or self.find_graph_output(node.input[0]) -62 | ) +59 + assert not ( +60 + self.find_graph_output(node.output[0]) +61 + or self.find_graph_input(node.input[0]) +62 + ) 63 + assert not ( 64 + self.find_graph_output(node.input[0]) 65 + ) -66 | | @@ -591,18 +529,13 @@ PT018 [*] Assertion should be broken down into multiple parts | help: Break down assertion into multiple parts | -64 | - - assert (not ( 65 + assert not ( -66 | self.find_graph_output(node.output[0]) -67 | or self.find_graph_input(node.input[0]) - - or self.find_graph_output(node.input[0]) - - )) +66 + self.find_graph_output(node.output[0]) +67 + or self.find_graph_input(node.input[0]) 68 + ) 69 + assert not ( 70 + self.find_graph_output(node.input[0]) 71 + ) -72 | | @@ -617,11 +550,6 @@ PT018 [*] Assertion should be broken down into multiple parts | |_____^ help: Break down assertion into multiple parts | -75 | def test_comments(): - - assert ( - - # comment - - something and something_else - - ) 76 + assert something 77 + assert something_else | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__only_docstring_doubles_all.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__only_docstring_doubles_all.py.snap index f00f7b6288d03..5734ebcaa2ca9 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__only_docstring_doubles_all.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__only_docstring_doubles_all.py.snap @@ -11,7 +11,6 @@ Q002 [*] Double quote docstring found but single quotes preferred | help: Replace double quotes docstring with single quotes | - - """This is a docstring.""" +1 - """This is a docstring.""" 1 + '''This is a docstring.''' -2 | | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__only_inline_doubles_all.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__only_inline_doubles_all.py.snap index 44d309415cd82..aa295fe2e9157 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__only_inline_doubles_all.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__only_inline_doubles_all.py.snap @@ -13,8 +13,6 @@ Q000 [*] Double quotes found but single quotes preferred | help: Replace double quotes with single quotes | -2 | - - this_is_an_inline_string = "double quote string" +3 - this_is_an_inline_string = "double quote string" 3 + this_is_an_inline_string = 'double quote string' -4 | | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__only_multiline_doubles_all.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__only_multiline_doubles_all.py.snap index e2b969aedb150..27d1495bf4434 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__only_multiline_doubles_all.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__only_multiline_doubles_all.py.snap @@ -13,10 +13,7 @@ Q001 [*] Double quote multiline found but single quotes preferred | |___^ help: Replace double multiline quotes with single quotes | -4 | - - this_is_a_multiline_string = """ -5 + this_is_a_multiline_string = ''' -6 | double quote string - - """ +5 ~ this_is_a_multiline_string = ''' +6 + double quote string 7 + ''' | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_doubles.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_doubles.py.snap index 5fd8ee23c8152..14ebc1f795858 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_doubles.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_doubles.py.snap @@ -15,13 +15,9 @@ Q001 [*] Double quote multiline found but single quotes preferred | help: Replace double multiline quotes with single quotes | -4 | - - """ 5 + ''' -6 | this is not a docstring - - """ +6 + this is not a docstring 7 + ''' -8 | | Q001 [*] Double quote multiline found but single quotes preferred @@ -38,13 +34,9 @@ Q001 [*] Double quote multiline found but single quotes preferred | help: Replace double multiline quotes with single quotes | -15 | - - """ -16 + ''' -17 | this is not a docstring - - """ +16 ~ ''' +17 + this is not a docstring 18 + ''' -19 | | Q001 [*] Double quote multiline found but single quotes preferred @@ -60,12 +52,8 @@ Q001 [*] Double quote multiline found but single quotes preferred | help: Replace double multiline quotes with single quotes | -20 | # The colon in the list indexing below is an edge case for the docstring scanner - - def f(self, bar=""" - - definitely not a docstring""", -21 + def f(self, bar=''' -22 + definitely not a docstring''', -23 | val=l[Cls():3]): +21 ~ def f(self, bar=''' +22 ~ definitely not a docstring''', | Q001 [*] Double quote multiline found but single quotes preferred @@ -82,13 +70,9 @@ Q001 [*] Double quote multiline found but single quotes preferred | help: Replace double multiline quotes with single quotes | -29 | - - """ -30 + ''' -31 | this is not a docstring - - """ +30 ~ ''' +31 + this is not a docstring 32 + ''' -33 | | Q001 [*] Double quote multiline found but single quotes preferred @@ -103,11 +87,7 @@ Q001 [*] Double quote multiline found but single quotes preferred | help: Replace double multiline quotes with single quotes | -34 | if l: - - """ -35 + ''' -36 | Looks like a docstring, but in reality it isn't - only modules, classes and functions - - """ +35 ~ ''' +36 + Looks like a docstring, but in reality it isn't - only modules, classes and functions 37 + ''' -38 | pass | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_doubles_class.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_doubles_class.py.snap index 57aeea32b4403..ad70d10d3272c 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_doubles_class.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_doubles_class.py.snap @@ -13,10 +13,8 @@ Q001 [*] Double quote multiline found but single quotes preferred | help: Replace double multiline quotes with single quotes | -2 | """ Double quotes single line class docstring """ - - """ Not a docstring """ +3 - """ Not a docstring """ 3 + ''' Not a docstring ''' -4 | | Q001 [*] Double quote multiline found but single quotes preferred @@ -31,8 +29,6 @@ Q001 [*] Double quote multiline found but single quotes preferred | help: Replace double multiline quotes with single quotes | -4 | - - def foo(self, bar="""not a docstring"""): +5 - def foo(self, bar="""not a docstring"""): 5 + def foo(self, bar='''not a docstring'''): -6 | """ Double quotes single line method docstring""" | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_doubles_function.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_doubles_function.py.snap index 91cce82790b93..46a79ff706ac4 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_doubles_function.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_doubles_function.py.snap @@ -12,10 +12,8 @@ Q001 [*] Double quote multiline found but single quotes preferred | help: Replace double multiline quotes with single quotes | -2 | """function without params, single line docstring""" - - """ not a docstring""" +3 - """ not a docstring""" 3 + ''' not a docstring''' -4 | return | Q001 [*] Double quote multiline found but single quotes preferred @@ -29,10 +27,8 @@ Q001 [*] Double quote multiline found but single quotes preferred | help: Replace double multiline quotes with single quotes | -10 | """ - - """ not a docstring""" +11 - """ not a docstring""" 11 + ''' not a docstring''' -12 | return | Q001 [*] Double quote multiline found but single quotes preferred @@ -47,13 +43,9 @@ Q001 [*] Double quote multiline found but single quotes preferred | help: Replace double multiline quotes with single quotes | -14 | - - def fun_with_params_no_docstring(a, b=""" -15 + def fun_with_params_no_docstring(a, b=''' -16 | not a - - """ """docstring"""): -17 + ''' """docstring"""): -18 | pass +15 ~ def fun_with_params_no_docstring(a, b=''' +16 + not a +17 ~ ''' """docstring"""): | Q001 [*] Double quote multiline found but single quotes preferred @@ -67,10 +59,8 @@ Q001 [*] Double quote multiline found but single quotes preferred | help: Replace double multiline quotes with single quotes | -16 | not a - - """ """docstring"""): +17 - """ """docstring"""): 17 + """ '''docstring'''): -18 | pass | Q001 [*] Double quote multiline found but single quotes preferred @@ -83,8 +73,6 @@ Q001 [*] Double quote multiline found but single quotes preferred | help: Replace double multiline quotes with single quotes | -21 | def fun_with_params_no_docstring2(a, b=c[foo():], c=\ - - """ not a docstring """): +22 - """ not a docstring """): 22 + ''' not a docstring '''): -23 | pass | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_doubles_module_multiline.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_doubles_module_multiline.py.snap index 7935bd5f49a31..7362f00fd6898 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_doubles_module_multiline.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_doubles_module_multiline.py.snap @@ -15,13 +15,9 @@ Q001 [*] Double quote multiline found but single quotes preferred | help: Replace double multiline quotes with single quotes | -3 | """ - - """ 4 + ''' -5 | this is not a docstring - - """ +5 + this is not a docstring 6 + ''' -7 | def foo(): | Q001 [*] Double quote multiline found but single quotes preferred @@ -35,10 +31,7 @@ Q001 [*] Double quote multiline found but single quotes preferred | |___^ help: Replace double multiline quotes with single quotes | -8 | pass - - """ -9 + ''' -10 | this is not a docstring - - """ + 9 + ''' +10 + this is not a docstring 11 + ''' | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_doubles_module_singleline.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_doubles_module_singleline.py.snap index 9520a1fc21856..2c7b861a56a17 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_doubles_module_singleline.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_doubles_module_singleline.py.snap @@ -12,10 +12,8 @@ Q001 [*] Double quote multiline found but single quotes preferred | help: Replace double multiline quotes with single quotes | -1 | """ Double quotes singleline module docstring """ - - """ this is not a docstring """ +2 - """ this is not a docstring """ 2 + ''' this is not a docstring ''' -3 | | Q001 [*] Double quote multiline found but single quotes preferred @@ -27,7 +25,6 @@ Q001 [*] Double quote multiline found but single quotes preferred | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace double multiline quotes with single quotes | -5 | pass - - """ this is not a docstring """ +6 - """ this is not a docstring """ 6 + ''' this is not a docstring ''' | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles.py.snap index 162b96964b012..7f50d2d124047 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles.py.snap @@ -13,12 +13,9 @@ Q002 [*] Single quote docstring found but double quotes preferred | help: Replace single quotes docstring with double quotes | - - ''' 1 + """ -2 | Single quotes multiline module docstring - - ''' +2 + Single quotes multiline module docstring 3 + """ -4 | | Q002 [*] Single quote docstring found but double quotes preferred @@ -35,13 +32,9 @@ Q002 [*] Single quote docstring found but double quotes preferred | help: Replace single quotes docstring with double quotes | -13 | ''')): - - ''' -14 + """ -15 | Single quotes multiline class docstring - - ''' +14 ~ """ +15 + Single quotes multiline class docstring 16 + """ -17 | | Q002 [*] Single quote docstring found but double quotes preferred @@ -58,11 +51,7 @@ Q002 [*] Single quote docstring found but double quotes preferred | help: Replace single quotes docstring with double quotes | -25 | val=l[Cls():3]): - - ''' -26 + """ -27 | Single quotes multiline function docstring - - ''' +26 ~ """ +27 + Single quotes multiline function docstring 28 + """ -29 | | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_class.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_class.py.snap index 4d53a37f63ede..29828ef01b2e7 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_class.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_class.py.snap @@ -11,10 +11,8 @@ Q002 [*] Single quote docstring found but double quotes preferred | help: Replace single quotes docstring with double quotes | -1 | class SingleLineDocstrings(): - - ''' Double quotes single line class docstring ''' +2 - ''' Double quotes single line class docstring ''' 2 + """ Double quotes single line class docstring """ -3 | ''' Not a docstring ''' | Q002 [*] Single quote docstring found but double quotes preferred @@ -27,10 +25,8 @@ Q002 [*] Single quote docstring found but double quotes preferred | help: Replace single quotes docstring with double quotes | -5 | def foo(self, bar='''not a docstring'''): - - ''' Double quotes single line method docstring''' +6 - ''' Double quotes single line method docstring''' 6 + """ Double quotes single line method docstring""" -7 | pass | Q002 [*] Single quote docstring found but double quotes preferred @@ -42,7 +38,6 @@ Q002 [*] Single quote docstring found but double quotes preferred | ^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace single quotes docstring with double quotes | -8 | - - class Nested(foo()[:]): ''' inline docstring '''; pass +9 - class Nested(foo()[:]): ''' inline docstring '''; pass 9 + class Nested(foo()[:]): """ inline docstring """; pass | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_function.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_function.py.snap index a797388c0792f..a33d05eea8c94 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_function.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_function.py.snap @@ -12,10 +12,8 @@ Q002 [*] Single quote docstring found but double quotes preferred | help: Replace single quotes docstring with double quotes | -1 | def foo(): - - '''function without params, single line docstring''' +2 - '''function without params, single line docstring''' 2 + """function without params, single line docstring""" -3 | ''' not a docstring''' | Q002 [*] Single quote docstring found but double quotes preferred @@ -31,13 +29,9 @@ Q002 [*] Single quote docstring found but double quotes preferred | help: Replace single quotes docstring with double quotes | -7 | def foo2(): - - ''' -8 + """ -9 | function without params, multiline docstring - - ''' + 8 ~ """ + 9 + function without params, multiline docstring 10 + """ -11 | ''' not a docstring''' | Q002 [*] Single quote docstring found but double quotes preferred @@ -48,8 +42,6 @@ Q002 [*] Single quote docstring found but double quotes preferred | ^^^^^^^^^^^^^^^^^^^^^^^ help: Replace single quotes docstring with double quotes | -26 | def function_with_single_docstring(a): - - 'Single line docstring' +27 - 'Single line docstring' 27 + "Single line docstring" -28 | | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_mixed_quotes_class_var_1.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_mixed_quotes_class_var_1.py.snap index aafe221fec038..a29c2b76cd820 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_mixed_quotes_class_var_1.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_mixed_quotes_class_var_1.py.snap @@ -21,10 +21,8 @@ Q002 [*] Single quote docstring found but double quotes preferred | help: Replace single quotes docstring with double quotes | -1 | class SingleLineDocstrings(): - - ''"Start with empty string" ' and lint docstring safely' +2 - ''"Start with empty string" ' and lint docstring safely' 2 + ''"Start with empty string" " and lint docstring safely" -3 | ''' Not a docstring ''' | Q002 Single quote docstring found but double quotes preferred @@ -47,10 +45,8 @@ Q002 [*] Single quote docstring found but double quotes preferred | help: Replace single quotes docstring with double quotes | -5 | def foo(self, bar='''not a docstring'''): - - ''"Start with empty string" ' and lint docstring safely' +6 - ''"Start with empty string" ' and lint docstring safely' 6 + ''"Start with empty string" " and lint docstring safely" -7 | pass | Q002 Single quote docstring found but double quotes preferred @@ -71,7 +67,6 @@ Q002 [*] Single quote docstring found but double quotes preferred | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace single quotes docstring with double quotes | -8 | - - class Nested(foo()[:]): ''"Start with empty string" ' and lint docstring safely'; pass +9 - class Nested(foo()[:]): ''"Start with empty string" ' and lint docstring safely'; pass 9 + class Nested(foo()[:]): ''"Start with empty string" " and lint docstring safely"; pass | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_mixed_quotes_class_var_2.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_mixed_quotes_class_var_2.py.snap index 61253ebe23966..9fbda3a8c1d39 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_mixed_quotes_class_var_2.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_mixed_quotes_class_var_2.py.snap @@ -11,10 +11,8 @@ Q002 [*] Single quote docstring found but double quotes preferred | help: Replace single quotes docstring with double quotes | -1 | class SingleLineDocstrings(): - - 'Do not'" start with empty string" ' and lint docstring safely' +2 - 'Do not'" start with empty string" ' and lint docstring safely' 2 + "Do not"" start with empty string" ' and lint docstring safely' -3 | ''' Not a docstring ''' | Q002 [*] Single quote docstring found but double quotes preferred @@ -27,10 +25,8 @@ Q002 [*] Single quote docstring found but double quotes preferred | help: Replace single quotes docstring with double quotes | -1 | class SingleLineDocstrings(): - - 'Do not'" start with empty string" ' and lint docstring safely' +2 - 'Do not'" start with empty string" ' and lint docstring safely' 2 + 'Do not'" start with empty string" " and lint docstring safely" -3 | ''' Not a docstring ''' | Q002 [*] Single quote docstring found but double quotes preferred @@ -43,10 +39,8 @@ Q002 [*] Single quote docstring found but double quotes preferred | help: Replace single quotes docstring with double quotes | -5 | def foo(self, bar='''not a docstring'''): - - 'Do not'" start with empty string" ' and lint docstring safely' +6 - 'Do not'" start with empty string" ' and lint docstring safely' 6 + "Do not"" start with empty string" ' and lint docstring safely' -7 | pass | Q002 [*] Single quote docstring found but double quotes preferred @@ -59,10 +53,8 @@ Q002 [*] Single quote docstring found but double quotes preferred | help: Replace single quotes docstring with double quotes | -5 | def foo(self, bar='''not a docstring'''): - - 'Do not'" start with empty string" ' and lint docstring safely' +6 - 'Do not'" start with empty string" ' and lint docstring safely' 6 + 'Do not'" start with empty string" " and lint docstring safely" -7 | pass | Q002 [*] Single quote docstring found but double quotes preferred @@ -74,8 +66,7 @@ Q002 [*] Single quote docstring found but double quotes preferred | ^^^^^^^^ help: Replace single quotes docstring with double quotes | -8 | - - class Nested(foo()[:]): 'Do not'" start with empty string" ' and lint docstring safely'; pass +9 - class Nested(foo()[:]): 'Do not'" start with empty string" ' and lint docstring safely'; pass 9 + class Nested(foo()[:]): "Do not"" start with empty string" ' and lint docstring safely'; pass | @@ -88,7 +79,6 @@ Q002 [*] Single quote docstring found but double quotes preferred | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace single quotes docstring with double quotes | -8 | - - class Nested(foo()[:]): 'Do not'" start with empty string" ' and lint docstring safely'; pass +9 - class Nested(foo()[:]): 'Do not'" start with empty string" ' and lint docstring safely'; pass 9 + class Nested(foo()[:]): 'Do not'" start with empty string" " and lint docstring safely"; pass | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_mixed_quotes_module_singleline_var_1.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_mixed_quotes_module_singleline_var_1.py.snap index dbbf6c1b35bd5..7af1d10779f94 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_mixed_quotes_module_singleline_var_1.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_mixed_quotes_module_singleline_var_1.py.snap @@ -21,9 +21,8 @@ Q002 [*] Single quote docstring found but double quotes preferred | help: Replace single quotes docstring with double quotes | - - ''"Start with empty string" ' and lint docstring safely' +1 - ''"Start with empty string" ' and lint docstring safely' 1 + ''"Start with empty string" " and lint docstring safely" -2 | | Q001 [*] Double quote multiline found but single quotes preferred @@ -35,7 +34,6 @@ Q001 [*] Double quote multiline found but single quotes preferred | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace double multiline quotes with single quotes | -4 | pass - - """ this is not a docstring """ +5 - """ this is not a docstring """ 5 + ''' this is not a docstring ''' | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_mixed_quotes_module_singleline_var_2.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_mixed_quotes_module_singleline_var_2.py.snap index 48503a33b2bbb..bf708498c66f5 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_mixed_quotes_module_singleline_var_2.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_mixed_quotes_module_singleline_var_2.py.snap @@ -11,9 +11,8 @@ Q002 [*] Single quote docstring found but double quotes preferred | help: Replace single quotes docstring with double quotes | - - 'Do not'" start with empty string" ' and lint docstring safely' +1 - 'Do not'" start with empty string" ' and lint docstring safely' 1 + "Do not"" start with empty string" ' and lint docstring safely' -2 | | Q002 [*] Single quote docstring found but double quotes preferred @@ -26,9 +25,8 @@ Q002 [*] Single quote docstring found but double quotes preferred | help: Replace single quotes docstring with double quotes | - - 'Do not'" start with empty string" ' and lint docstring safely' +1 - 'Do not'" start with empty string" ' and lint docstring safely' 1 + 'Do not'" start with empty string" " and lint docstring safely" -2 | | Q001 [*] Double quote multiline found but single quotes preferred @@ -40,7 +38,6 @@ Q001 [*] Double quote multiline found but single quotes preferred | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace double multiline quotes with single quotes | -4 | pass - - """ this is not a docstring """ +5 - """ this is not a docstring """ 5 + ''' this is not a docstring ''' | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_module_multiline.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_module_multiline.py.snap index 0f1c105709f2b..3f99c765eaa66 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_module_multiline.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_module_multiline.py.snap @@ -13,10 +13,7 @@ Q002 [*] Single quote docstring found but double quotes preferred | help: Replace single quotes docstring with double quotes | - - ''' 1 + """ -2 | Double quotes multiline module docstring - - ''' +2 + Double quotes multiline module docstring 3 + """ -4 | ''' | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_module_singleline.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_module_singleline.py.snap index 73396b895390d..60fc0f4402130 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_module_singleline.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_doubles_over_docstring_singles_module_singleline.py.snap @@ -10,7 +10,6 @@ Q002 [*] Single quote docstring found but double quotes preferred | help: Replace single quotes docstring with double quotes | - - ''' Double quotes singleline module docstring ''' +1 - ''' Double quotes singleline module docstring ''' 1 + """ Double quotes singleline module docstring """ -2 | ''' this is not a docstring ''' | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles.py.snap index 77332968e3e71..4b3f58d4add45 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles.py.snap @@ -13,12 +13,9 @@ Q002 [*] Double quote docstring found but single quotes preferred | help: Replace double quotes docstring with single quotes | - - """ 1 + ''' -2 | Double quotes multiline module docstring - - """ +2 + Double quotes multiline module docstring 3 + ''' -4 | | Q002 [*] Double quote docstring found but single quotes preferred @@ -34,13 +31,9 @@ Q002 [*] Double quote docstring found but single quotes preferred | help: Replace double quotes docstring with single quotes | -11 | class Cls: - - """ -12 + ''' -13 | Double quotes multiline class docstring - - """ +12 ~ ''' +13 + Double quotes multiline class docstring 14 + ''' -15 | | Q002 [*] Double quote docstring found but single quotes preferred @@ -57,11 +50,7 @@ Q002 [*] Double quote docstring found but single quotes preferred | help: Replace double quotes docstring with single quotes | -23 | val=l[Cls():3]): - - """ -24 + ''' -25 | Double quotes multiline function docstring - - """ +24 ~ ''' +25 + Double quotes multiline function docstring 26 + ''' -27 | | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_class.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_class.py.snap index d520428d8ea3a..7472f8899e246 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_class.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_class.py.snap @@ -11,10 +11,8 @@ Q002 [*] Double quote docstring found but single quotes preferred | help: Replace double quotes docstring with single quotes | -1 | class SingleLineDocstrings(): - - """ Double quotes single line class docstring """ +2 - """ Double quotes single line class docstring """ 2 + ''' Double quotes single line class docstring ''' -3 | """ Not a docstring """ | Q002 [*] Double quote docstring found but single quotes preferred @@ -27,10 +25,8 @@ Q002 [*] Double quote docstring found but single quotes preferred | help: Replace double quotes docstring with single quotes | -5 | def foo(self, bar="""not a docstring"""): - - """ Double quotes single line method docstring""" +6 - """ Double quotes single line method docstring""" 6 + ''' Double quotes single line method docstring''' -7 | pass | Q002 [*] Double quote docstring found but single quotes preferred @@ -42,7 +38,6 @@ Q002 [*] Double quote docstring found but single quotes preferred | ^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace double quotes docstring with single quotes | -8 | - - class Nested(foo()[:]): """ inline docstring """; pass +9 - class Nested(foo()[:]): """ inline docstring """; pass 9 + class Nested(foo()[:]): ''' inline docstring '''; pass | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_function.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_function.py.snap index 90a6c15e18364..d3e9f26b51516 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_function.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_function.py.snap @@ -12,10 +12,8 @@ Q002 [*] Double quote docstring found but single quotes preferred | help: Replace double quotes docstring with single quotes | -1 | def foo(): - - """function without params, single line docstring""" +2 - """function without params, single line docstring""" 2 + '''function without params, single line docstring''' -3 | """ not a docstring""" | Q002 [*] Double quote docstring found but single quotes preferred @@ -31,13 +29,9 @@ Q002 [*] Double quote docstring found but single quotes preferred | help: Replace double quotes docstring with single quotes | -7 | def foo2(): - - """ -8 + ''' -9 | function without params, multiline docstring - - """ + 8 ~ ''' + 9 + function without params, multiline docstring 10 + ''' -11 | """ not a docstring""" | Q002 [*] Double quote docstring found but single quotes preferred @@ -48,8 +42,6 @@ Q002 [*] Double quote docstring found but single quotes preferred | ^^^^^^^^^^^^^^^^^^^^^^^ help: Replace double quotes docstring with single quotes | -26 | def function_with_single_docstring(a): - - "Single line docstring" +27 - "Single line docstring" 27 + 'Single line docstring' -28 | | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_mixed_quotes_class_var_2.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_mixed_quotes_class_var_2.py.snap index e5cc5e652231b..7a5d2c2e76025 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_mixed_quotes_class_var_2.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_mixed_quotes_class_var_2.py.snap @@ -11,10 +11,8 @@ Q002 [*] Double quote docstring found but single quotes preferred | help: Replace double quotes docstring with single quotes | -1 | class SingleLineDocstrings(): - - "Do not"' start with empty string' ' and lint docstring safely' +2 - "Do not"' start with empty string' ' and lint docstring safely' 2 + 'Do not'' start with empty string' ' and lint docstring safely' -3 | """ Not a docstring """ | Q002 [*] Double quote docstring found but single quotes preferred @@ -27,10 +25,8 @@ Q002 [*] Double quote docstring found but single quotes preferred | help: Replace double quotes docstring with single quotes | -5 | def foo(self, bar="""not a docstring"""): - - "Do not"' start with empty string' ' and lint docstring safely' +6 - "Do not"' start with empty string' ' and lint docstring safely' 6 + 'Do not'' start with empty string' ' and lint docstring safely' -7 | pass | Q002 [*] Double quote docstring found but single quotes preferred @@ -42,7 +38,6 @@ Q002 [*] Double quote docstring found but single quotes preferred | ^^^^^^^^ help: Replace double quotes docstring with single quotes | -8 | - - class Nested(foo()[:]): "Do not"' start with empty string' ' and lint docstring safely'; pass +9 - class Nested(foo()[:]): "Do not"' start with empty string' ' and lint docstring safely'; pass 9 + class Nested(foo()[:]): 'Do not'' start with empty string' ' and lint docstring safely'; pass | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_mixed_quotes_module_singleline_var_2.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_mixed_quotes_module_singleline_var_2.py.snap index ef442f3c12118..9277823de15b7 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_mixed_quotes_module_singleline_var_2.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_mixed_quotes_module_singleline_var_2.py.snap @@ -11,7 +11,6 @@ Q002 [*] Double quote docstring found but single quotes preferred | help: Replace double quotes docstring with single quotes | - - "Do not"' start with empty string' ' and lint docstring safely' +1 - "Do not"' start with empty string' ' and lint docstring safely' 1 + 'Do not'' start with empty string' ' and lint docstring safely' -2 | | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_module_multiline.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_module_multiline.py.snap index 98d0052553cf3..a2fc4efccb342 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_module_multiline.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_module_multiline.py.snap @@ -13,10 +13,7 @@ Q002 [*] Double quote docstring found but single quotes preferred | help: Replace double quotes docstring with single quotes | - - """ 1 + ''' -2 | Double quotes multiline module docstring - - """ +2 + Double quotes multiline module docstring 3 + ''' -4 | """ | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_module_singleline.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_module_singleline.py.snap index cae011579621f..62db3d161c005 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_module_singleline.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_doubles_module_singleline.py.snap @@ -10,7 +10,6 @@ Q002 [*] Double quote docstring found but single quotes preferred | help: Replace double quotes docstring with single quotes | - - """ Double quotes singleline module docstring """ +1 - """ Double quotes singleline module docstring """ 1 + ''' Double quotes singleline module docstring ''' -2 | """ this is not a docstring """ | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_singles.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_singles.py.snap index 031cd81c8ef54..dce11f0abf5bc 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_singles.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_singles.py.snap @@ -15,13 +15,9 @@ Q001 [*] Single quote multiline found but double quotes preferred | help: Replace single multiline quotes with double quotes | -4 | - - ''' 5 + """ -6 | this is not a docstring - - ''' +6 + this is not a docstring 7 + """ -8 | | Q001 [*] Single quote multiline found but double quotes preferred @@ -39,13 +35,9 @@ Q001 [*] Single quote multiline found but double quotes preferred | help: Replace single multiline quotes with double quotes | -10 | - - class Cls(MakeKlass(''' -11 + class Cls(MakeKlass(""" -12 | class params \t not a docstring - - ''')): -13 + """)): -14 | ''' +11 ~ class Cls(MakeKlass(""" +12 + class params \t not a docstring +13 ~ """)): | Q001 [*] Single quote multiline found but double quotes preferred @@ -62,13 +54,9 @@ Q001 [*] Single quote multiline found but double quotes preferred | help: Replace single multiline quotes with double quotes | -17 | - - ''' -18 + """ -19 | this is not a docstring - - ''' +18 ~ """ +19 + this is not a docstring 20 + """ -21 | | Q001 [*] Single quote multiline found but double quotes preferred @@ -84,12 +72,8 @@ Q001 [*] Single quote multiline found but double quotes preferred | help: Replace single multiline quotes with double quotes | -22 | # The colon in the list indexing below is an edge case for the docstring scanner - - def f(self, bar=''' - - definitely not a docstring''', -23 + def f(self, bar=""" -24 + definitely not a docstring""", -25 | val=l[Cls():3]): +23 ~ def f(self, bar=""" +24 ~ definitely not a docstring""", | Q001 [*] Single quote multiline found but double quotes preferred @@ -106,13 +90,9 @@ Q001 [*] Single quote multiline found but double quotes preferred | help: Replace single multiline quotes with double quotes | -31 | - - ''' -32 + """ -33 | this is not a docstring - - ''' +32 ~ """ +33 + this is not a docstring 34 + """ -35 | | Q001 [*] Single quote multiline found but double quotes preferred @@ -127,11 +107,7 @@ Q001 [*] Single quote multiline found but double quotes preferred | help: Replace single multiline quotes with double quotes | -36 | if l: - - ''' -37 + """ -38 | Looks like a docstring, but in reality it isn't - only modules, classes and functions - - ''' +37 ~ """ +38 + Looks like a docstring, but in reality it isn't - only modules, classes and functions 39 + """ -40 | pass | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_singles_class.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_singles_class.py.snap index 88dff41f9ee9c..5f97a91641b57 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_singles_class.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_singles_class.py.snap @@ -13,10 +13,8 @@ Q001 [*] Single quote multiline found but double quotes preferred | help: Replace single multiline quotes with double quotes | -2 | ''' Double quotes single line class docstring ''' - - ''' Not a docstring ''' +3 - ''' Not a docstring ''' 3 + """ Not a docstring """ -4 | | Q001 [*] Single quote multiline found but double quotes preferred @@ -31,8 +29,6 @@ Q001 [*] Single quote multiline found but double quotes preferred | help: Replace single multiline quotes with double quotes | -4 | - - def foo(self, bar='''not a docstring'''): +5 - def foo(self, bar='''not a docstring'''): 5 + def foo(self, bar="""not a docstring"""): -6 | ''' Double quotes single line method docstring''' | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_singles_function.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_singles_function.py.snap index 9c86567518145..385055e8e3f35 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_singles_function.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_singles_function.py.snap @@ -12,10 +12,8 @@ Q001 [*] Single quote multiline found but double quotes preferred | help: Replace single multiline quotes with double quotes | -2 | '''function without params, single line docstring''' - - ''' not a docstring''' +3 - ''' not a docstring''' 3 + """ not a docstring""" -4 | return | Q001 [*] Single quote multiline found but double quotes preferred @@ -29,10 +27,8 @@ Q001 [*] Single quote multiline found but double quotes preferred | help: Replace single multiline quotes with double quotes | -10 | ''' - - ''' not a docstring''' +11 - ''' not a docstring''' 11 + """ not a docstring""" -12 | return | Q001 [*] Single quote multiline found but double quotes preferred @@ -47,13 +43,9 @@ Q001 [*] Single quote multiline found but double quotes preferred | help: Replace single multiline quotes with double quotes | -14 | - - def fun_with_params_no_docstring(a, b=''' -15 + def fun_with_params_no_docstring(a, b=""" -16 | not a - - ''' '''docstring'''): -17 + """ '''docstring'''): -18 | pass +15 ~ def fun_with_params_no_docstring(a, b=""" +16 + not a +17 ~ """ '''docstring'''): | Q001 [*] Single quote multiline found but double quotes preferred @@ -67,10 +59,8 @@ Q001 [*] Single quote multiline found but double quotes preferred | help: Replace single multiline quotes with double quotes | -16 | not a - - ''' '''docstring'''): +17 - ''' '''docstring'''): 17 + ''' """docstring"""): -18 | pass | Q001 [*] Single quote multiline found but double quotes preferred @@ -83,8 +73,6 @@ Q001 [*] Single quote multiline found but double quotes preferred | help: Replace single multiline quotes with double quotes | -21 | def fun_with_params_no_docstring2(a, b=c[foo():], c=\ - - ''' not a docstring '''): +22 - ''' not a docstring '''): 22 + """ not a docstring """): -23 | pass | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_singles_module_multiline.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_singles_module_multiline.py.snap index 236d3304e20ec..53571e4533270 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_singles_module_multiline.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_singles_module_multiline.py.snap @@ -15,13 +15,9 @@ Q001 [*] Single quote multiline found but double quotes preferred | help: Replace single multiline quotes with double quotes | -3 | ''' - - ''' 4 + """ -5 | this is not a docstring - - ''' +5 + this is not a docstring 6 + """ -7 | def foo(): | Q001 [*] Single quote multiline found but double quotes preferred @@ -35,10 +31,7 @@ Q001 [*] Single quote multiline found but double quotes preferred | |___^ help: Replace single multiline quotes with double quotes | -8 | pass - - ''' -9 + """ -10 | this is not a docstring - - ''' + 9 + """ +10 + this is not a docstring 11 + """ | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_singles_module_singleline.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_singles_module_singleline.py.snap index a23fc81535198..0288c2ecf0117 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_singles_module_singleline.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_docstring_singles_over_docstring_singles_module_singleline.py.snap @@ -12,10 +12,8 @@ Q001 [*] Single quote multiline found but double quotes preferred | help: Replace single multiline quotes with double quotes | -1 | ''' Double quotes singleline module docstring ''' - - ''' this is not a docstring ''' +2 - ''' this is not a docstring ''' 2 + """ this is not a docstring """ -3 | | Q001 [*] Single quote multiline found but double quotes preferred @@ -27,7 +25,6 @@ Q001 [*] Single quote multiline found but double quotes preferred | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace single multiline quotes with double quotes | -5 | pass - - ''' this is not a docstring ''' +6 - ''' this is not a docstring ''' 6 + """ this is not a docstring """ | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles.py.snap index 37cf872131536..f97e1534f532f 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles.py.snap @@ -11,9 +11,8 @@ Q000 [*] Single quotes found but double quotes preferred | help: Replace single quotes with double quotes | - - this_should_be_linted = 'single quote string' +1 - this_should_be_linted = 'single quote string' 1 + this_should_be_linted = "single quote string" -2 | this_should_be_linted = u'double quote string' | Q000 [*] Single quotes found but double quotes preferred @@ -27,10 +26,8 @@ Q000 [*] Single quotes found but double quotes preferred | help: Replace single quotes with double quotes | -1 | this_should_be_linted = 'single quote string' - - this_should_be_linted = u'double quote string' +2 - this_should_be_linted = u'double quote string' 2 + this_should_be_linted = u"double quote string" -3 | this_should_be_linted = f'double quote string' | Q000 [*] Single quotes found but double quotes preferred @@ -44,8 +41,6 @@ Q000 [*] Single quotes found but double quotes preferred | help: Replace single quotes with double quotes | -2 | this_should_be_linted = u'double quote string' - - this_should_be_linted = f'double quote string' +3 - this_should_be_linted = f'double quote string' 3 + this_should_be_linted = f"double quote string" -4 | this_should_be_linted = f'double {"quote"} string' | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_escaped.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_escaped.py.snap index bd4d6fa017ab1..aef9bf2f7c018 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_escaped.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_escaped.py.snap @@ -11,9 +11,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | - - this_should_raise_Q003 = "This is a \"string\"" +1 - this_should_raise_Q003 = "This is a \"string\"" 1 + this_should_raise_Q003 = 'This is a "string"' -2 | this_is_fine = "'This' is a \"string\"" | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -26,12 +25,10 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes 10 | ) | help: Change outer quotes to avoid escaping inner quotes - | -8 | "This is a" - - "\"string\"" -9 + '"string"' -10 | ) - | + | +9 - "\"string\"" +9 + '"string"' + | Q003 [*] Change outer quotes to avoid escaping inner quotes --> singles_escaped.py:13:1 @@ -44,10 +41,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -12 | # Same as above, but with f-strings - - f"This is a \"string\"" +13 - f"This is a \"string\"" 13 + f'This is a "string"' -14 | f"'This' is a \"string\"" | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -61,10 +56,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -20 | f"This is a" - - f"\"string\"" +21 - f"\"string\"" 21 + f'"string"' -22 | ) | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -79,10 +72,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -30 | # but as the actual string itself is invalid pre 3.12, we don't catch it. - - f"\"foo\" {"foo"}" # Q003 +31 - f"\"foo\" {"foo"}" # Q003 31 + f'"foo" {"foo"}' # Q003 -32 | f"\"foo\" {f"foo"}" # Q003 | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -96,10 +87,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -31 | f"\"foo\" {"foo"}" # Q003 - - f"\"foo\" {f"foo"}" # Q003 +32 - f"\"foo\" {f"foo"}" # Q003 32 + f'"foo" {f"foo"}' # Q003 -33 | f"\"foo\" {f"\"foo\""} \"\"" # Q003 | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -114,10 +103,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -32 | f"\"foo\" {f"foo"}" # Q003 - - f"\"foo\" {f"\"foo\""} \"\"" # Q003 +33 - f"\"foo\" {f"\"foo\""} \"\"" # Q003 33 + f'"foo" {f"\"foo\""} ""' # Q003 -34 | | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -132,10 +119,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -32 | f"\"foo\" {f"foo"}" # Q003 - - f"\"foo\" {f"\"foo\""} \"\"" # Q003 +33 - f"\"foo\" {f"\"foo\""} \"\"" # Q003 33 + f"\"foo\" {f'"foo"'} \"\"" # Q003 -34 | | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -149,10 +134,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -35 | f"normal {f"nested"} normal" - - f"\"normal\" {f"nested"} normal" # Q003 +36 - f"\"normal\" {f"nested"} normal" # Q003 36 + f'"normal" {f"nested"} normal' # Q003 -37 | f"\"normal\" {f"nested"} 'single quotes'" | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -166,10 +149,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -37 | f"\"normal\" {f"nested"} 'single quotes'" - - f"\"normal\" {f"\"nested\" {"other"} normal"} 'single quotes'" # Q003 +38 - f"\"normal\" {f"\"nested\" {"other"} normal"} 'single quotes'" # Q003 38 + f"\"normal\" {f'"nested" {"other"} normal'} 'single quotes'" # Q003 -39 | f"\"normal\" {f"\"nested\" {"other"} 'single quotes'"} normal" # Q003 | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -181,10 +162,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Change outer quotes to avoid escaping inner quotes | -38 | f"\"normal\" {f"\"nested\" {"other"} normal"} 'single quotes'" # Q003 - - f"\"normal\" {f"\"nested\" {"other"} 'single quotes'"} normal" # Q003 +39 - f"\"normal\" {f"\"nested\" {"other"} 'single quotes'"} normal" # Q003 39 + f'"normal" {f"\"nested\" {"other"} 'single quotes'"} normal' # Q003 -40 | | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -198,10 +177,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -42 | # Same as above, but with t-strings - - t"This is a \"string\"" +43 - t"This is a \"string\"" 43 + t'This is a "string"' -44 | t"'This' is a \"string\"" | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -216,10 +193,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -50 | t"This is a" - - t"\"string\"" +51 - t"\"string\"" 51 + t'"string"' -52 | ) | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -234,10 +209,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -52 | ) - - t"\"foo\" {"foo"}" # Q003 +53 - t"\"foo\" {"foo"}" # Q003 53 + t'"foo" {"foo"}' # Q003 -54 | t"\"foo\" {t"foo"}" # Q003 | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -251,10 +224,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -53 | t"\"foo\" {"foo"}" # Q003 - - t"\"foo\" {t"foo"}" # Q003 +54 - t"\"foo\" {t"foo"}" # Q003 54 + t'"foo" {t"foo"}' # Q003 -55 | t"\"foo\" {t"\"foo\""} \"\"" # Q003 | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -269,10 +240,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -54 | t"\"foo\" {t"foo"}" # Q003 - - t"\"foo\" {t"\"foo\""} \"\"" # Q003 +55 - t"\"foo\" {t"\"foo\""} \"\"" # Q003 55 + t'"foo" {t"\"foo\""} ""' # Q003 -56 | | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -287,10 +256,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -54 | t"\"foo\" {t"foo"}" # Q003 - - t"\"foo\" {t"\"foo\""} \"\"" # Q003 +55 - t"\"foo\" {t"\"foo\""} \"\"" # Q003 55 + t"\"foo\" {t'"foo"'} \"\"" # Q003 -56 | | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -304,10 +271,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -57 | t"normal {t"nested"} normal" - - t"\"normal\" {t"nested"} normal" # Q003 +58 - t"\"normal\" {t"nested"} normal" # Q003 58 + t'"normal" {t"nested"} normal' # Q003 -59 | t"\"normal\" {t"nested"} 'single quotes'" | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -321,10 +286,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -59 | t"\"normal\" {t"nested"} 'single quotes'" - - t"\"normal\" {t"\"nested\" {"other"} normal"} 'single quotes'" # Q003 +60 - t"\"normal\" {t"\"nested\" {"other"} normal"} 'single quotes'" # Q003 60 + t"\"normal\" {t'"nested" {"other"} normal'} 'single quotes'" # Q003 -61 | t"\"normal\" {t"\"nested\" {"other"} 'single quotes'"} normal" # Q003 | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -336,7 +299,6 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Change outer quotes to avoid escaping inner quotes | -60 | t"\"normal\" {t"\"nested\" {"other"} normal"} 'single quotes'" # Q003 - - t"\"normal\" {t"\"nested\" {"other"} 'single quotes'"} normal" # Q003 +61 - t"\"normal\" {t"\"nested\" {"other"} 'single quotes'"} normal" # Q003 61 + t'"normal" {t"\"nested\" {"other"} 'single quotes'"} normal' # Q003 | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_escaped_py311.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_escaped_py311.snap index 2cc3c94994f24..461971ddddcc0 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_escaped_py311.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_escaped_py311.snap @@ -11,9 +11,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | - - this_should_raise_Q003 = "This is a \"string\"" +1 - this_should_raise_Q003 = "This is a \"string\"" 1 + this_should_raise_Q003 = 'This is a "string"' -2 | this_is_fine = "'This' is a \"string\"" | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -26,12 +25,10 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes 10 | ) | help: Change outer quotes to avoid escaping inner quotes - | -8 | "This is a" - - "\"string\"" -9 + '"string"' -10 | ) - | + | +9 - "\"string\"" +9 + '"string"' + | Q003 [*] Change outer quotes to avoid escaping inner quotes --> singles_escaped.py:13:1 @@ -44,10 +41,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -12 | # Same as above, but with f-strings - - f"This is a \"string\"" +13 - f"This is a \"string\"" 13 + f'This is a "string"' -14 | f"'This' is a \"string\"" | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -61,10 +56,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -20 | f"This is a" - - f"\"string\"" +21 - f"\"string\"" 21 + f'"string"' -22 | ) | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -78,10 +71,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -42 | # Same as above, but with t-strings - - t"This is a \"string\"" +43 - t"This is a \"string\"" 43 + t'This is a "string"' -44 | t"'This' is a \"string\"" | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -96,10 +87,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -50 | t"This is a" - - t"\"string\"" +51 - t"\"string\"" 51 + t'"string"' -52 | ) | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -114,10 +103,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -52 | ) - - t"\"foo\" {"foo"}" # Q003 +53 - t"\"foo\" {"foo"}" # Q003 53 + t'"foo" {"foo"}' # Q003 -54 | t"\"foo\" {t"foo"}" # Q003 | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -131,10 +118,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -53 | t"\"foo\" {"foo"}" # Q003 - - t"\"foo\" {t"foo"}" # Q003 +54 - t"\"foo\" {t"foo"}" # Q003 54 + t'"foo" {t"foo"}' # Q003 -55 | t"\"foo\" {t"\"foo\""} \"\"" # Q003 | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -149,10 +134,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -54 | t"\"foo\" {t"foo"}" # Q003 - - t"\"foo\" {t"\"foo\""} \"\"" # Q003 +55 - t"\"foo\" {t"\"foo\""} \"\"" # Q003 55 + t'"foo" {t"\"foo\""} ""' # Q003 -56 | | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -167,10 +150,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -54 | t"\"foo\" {t"foo"}" # Q003 - - t"\"foo\" {t"\"foo\""} \"\"" # Q003 +55 - t"\"foo\" {t"\"foo\""} \"\"" # Q003 55 + t"\"foo\" {t'"foo"'} \"\"" # Q003 -56 | | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -184,10 +165,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -57 | t"normal {t"nested"} normal" - - t"\"normal\" {t"nested"} normal" # Q003 +58 - t"\"normal\" {t"nested"} normal" # Q003 58 + t'"normal" {t"nested"} normal' # Q003 -59 | t"\"normal\" {t"nested"} 'single quotes'" | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -201,10 +180,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -59 | t"\"normal\" {t"nested"} 'single quotes'" - - t"\"normal\" {t"\"nested\" {"other"} normal"} 'single quotes'" # Q003 +60 - t"\"normal\" {t"\"nested\" {"other"} normal"} 'single quotes'" # Q003 60 + t"\"normal\" {t'"nested" {"other"} normal'} 'single quotes'" # Q003 -61 | t"\"normal\" {t"\"nested\" {"other"} 'single quotes'"} normal" # Q003 | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -216,7 +193,6 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Change outer quotes to avoid escaping inner quotes | -60 | t"\"normal\" {t"\"nested\" {"other"} normal"} 'single quotes'" # Q003 - - t"\"normal\" {t"\"nested\" {"other"} 'single quotes'"} normal" # Q003 +61 - t"\"normal\" {t"\"nested\" {"other"} 'single quotes'"} normal" # Q003 61 + t'"normal" {t"\"nested\" {"other"} 'single quotes'"} normal' # Q003 | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_escaped_unnecessary.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_escaped_unnecessary.py.snap index 08a6364fdcfaa..547dd3323be88 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_escaped_unnecessary.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_escaped_unnecessary.py.snap @@ -11,9 +11,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | - - this_should_raise_Q004 = "This is a \'string\'" +1 - this_should_raise_Q004 = "This is a \'string\'" 1 + this_should_raise_Q004 = "This is a 'string'" -2 | this_should_raise_Q004 = "'This' is a \'string\'" | Q004 [*] Unnecessary escape on inner quote character @@ -27,10 +26,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -1 | this_should_raise_Q004 = "This is a \'string\'" - - this_should_raise_Q004 = "'This' is a \'string\'" +2 - this_should_raise_Q004 = "'This' is a \'string\'" 2 + this_should_raise_Q004 = "'This' is a 'string'" -3 | this_is_fine = 'This is a "string"' | Q004 [*] Unnecessary escape on inner quote character @@ -43,12 +40,10 @@ Q004 [*] Unnecessary escape on inner quote character 10 | ) | help: Remove backslash - | -8 | "This is a" - - "\'string\'" -9 + "'string'" -10 | ) - | + | +9 - "\'string\'" +9 + "'string'" + | Q004 [*] Unnecessary escape on inner quote character --> singles_escaped_unnecessary.py:13:1 @@ -61,10 +56,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -12 | # Same as above, but with f-strings - - f"This is a \'string\'" # Q004 +13 - f"This is a \'string\'" # Q004 13 + f"This is a 'string'" # Q004 -14 | f"'This' is a \'string\'" # Q004 | Q004 [*] Unnecessary escape on inner quote character @@ -79,10 +72,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -13 | f"This is a \'string\'" # Q004 - - f"'This' is a \'string\'" # Q004 +14 - f"'This' is a \'string\'" # Q004 14 + f"'This' is a 'string'" # Q004 -15 | f'This is a "string"' | Q004 [*] Unnecessary escape on inner quote character @@ -96,10 +87,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -20 | f"This is a" - - f"\'string\'" # Q004 +21 - f"\'string\'" # Q004 21 + f"'string'" # Q004 -22 | ) | Q004 [*] Unnecessary escape on inner quote character @@ -114,10 +103,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -30 | # but as the actual string itself is invalid pre 3.12, we don't catch it. - - f"\'foo\' {"foo"}" # Q004 +31 - f"\'foo\' {"foo"}" # Q004 31 + f"'foo' {"foo"}" # Q004 -32 | f"\'foo\' {f"foo"}" # Q004 | Q004 [*] Unnecessary escape on inner quote character @@ -131,10 +118,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -31 | f"\'foo\' {"foo"}" # Q004 - - f"\'foo\' {f"foo"}" # Q004 +32 - f"\'foo\' {f"foo"}" # Q004 32 + f"'foo' {f"foo"}" # Q004 -33 | f"\'foo\' {f"\'foo\'"} \'\'" # Q004 | Q004 [*] Unnecessary escape on inner quote character @@ -149,10 +134,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -32 | f"\'foo\' {f"foo"}" # Q004 - - f"\'foo\' {f"\'foo\'"} \'\'" # Q004 +33 - f"\'foo\' {f"\'foo\'"} \'\'" # Q004 33 + f"'foo' {f"\'foo\'"} ''" # Q004 -34 | | Q004 [*] Unnecessary escape on inner quote character @@ -167,10 +150,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -32 | f"\'foo\' {f"foo"}" # Q004 - - f"\'foo\' {f"\'foo\'"} \'\'" # Q004 +33 - f"\'foo\' {f"\'foo\'"} \'\'" # Q004 33 + f"\'foo\' {f"'foo'"} \'\'" # Q004 -34 | | Q004 [*] Unnecessary escape on inner quote character @@ -184,10 +165,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -35 | f"normal {f"nested"} normal" - - f"\'normal\' {f"nested"} normal" # Q004 +36 - f"\'normal\' {f"nested"} normal" # Q004 36 + f"'normal' {f"nested"} normal" # Q004 -37 | f"\'normal\' {f"nested"} 'single quotes'" | Q004 [*] Unnecessary escape on inner quote character @@ -202,10 +181,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -36 | f"\'normal\' {f"nested"} normal" # Q004 - - f"\'normal\' {f"nested"} 'single quotes'" +37 - f"\'normal\' {f"nested"} 'single quotes'" 37 + f"'normal' {f"nested"} 'single quotes'" -38 | f"\'normal\' {f"\'nested\' {"other"} normal"} 'single quotes'" # Q004 | Q004 [*] Unnecessary escape on inner quote character @@ -219,10 +196,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -37 | f"\'normal\' {f"nested"} 'single quotes'" - - f"\'normal\' {f"\'nested\' {"other"} normal"} 'single quotes'" # Q004 +38 - f"\'normal\' {f"\'nested\' {"other"} normal"} 'single quotes'" # Q004 38 + f"'normal' {f"\'nested\' {"other"} normal"} 'single quotes'" # Q004 -39 | f"\'normal\' {f"\'nested\' {"other"} 'single quotes'"} normal" # Q004 | Q004 [*] Unnecessary escape on inner quote character @@ -236,10 +211,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -37 | f"\'normal\' {f"nested"} 'single quotes'" - - f"\'normal\' {f"\'nested\' {"other"} normal"} 'single quotes'" # Q004 +38 - f"\'normal\' {f"\'nested\' {"other"} normal"} 'single quotes'" # Q004 38 + f"\'normal\' {f"'nested' {"other"} normal"} 'single quotes'" # Q004 -39 | f"\'normal\' {f"\'nested\' {"other"} 'single quotes'"} normal" # Q004 | Q004 [*] Unnecessary escape on inner quote character @@ -254,10 +227,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -38 | f"\'normal\' {f"\'nested\' {"other"} normal"} 'single quotes'" # Q004 - - f"\'normal\' {f"\'nested\' {"other"} 'single quotes'"} normal" # Q004 +39 - f"\'normal\' {f"\'nested\' {"other"} 'single quotes'"} normal" # Q004 39 + f"'normal' {f"\'nested\' {"other"} 'single quotes'"} normal" # Q004 -40 | | Q004 [*] Unnecessary escape on inner quote character @@ -272,10 +243,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -38 | f"\'normal\' {f"\'nested\' {"other"} normal"} 'single quotes'" # Q004 - - f"\'normal\' {f"\'nested\' {"other"} 'single quotes'"} normal" # Q004 +39 - f"\'normal\' {f"\'nested\' {"other"} 'single quotes'"} normal" # Q004 39 + f"\'normal\' {f"'nested' {"other"} 'single quotes'"} normal" # Q004 -40 | | Q004 [*] Unnecessary escape on inner quote character @@ -290,10 +259,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -42 | this_is_fine = "This is an \\'escaped\\' quote" - - this_should_raise_Q004 = "This is an \\\'escaped\\\' quote with an extra backslash" # Q004 +43 - this_should_raise_Q004 = "This is an \\\'escaped\\\' quote with an extra backslash" # Q004 43 + this_should_raise_Q004 = "This is an \\'escaped\\' quote with an extra backslash" # Q004 -44 | | Q004 [*] Unnecessary escape on inner quote character @@ -304,7 +271,6 @@ Q004 [*] Unnecessary escape on inner quote character | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove backslash | -45 | # Invalid escapes in bytestrings are also triggered: - - x = b"\xe7\xeb\x0c\xa1\x1b\x83tN\xce=x\xe9\xbe\x01\xb9\x13B_\xba\xe7\x0c2\xce\'rm\x0e\xcd\xe9.\xf8\xd2" # Q004 +46 - x = b"\xe7\xeb\x0c\xa1\x1b\x83tN\xce=x\xe9\xbe\x01\xb9\x13B_\xba\xe7\x0c2\xce\'rm\x0e\xcd\xe9.\xf8\xd2" # Q004 46 + x = b"\xe7\xeb\x0c\xa1\x1b\x83tN\xce=x\xe9\xbe\x01\xb9\x13B_\xba\xe7\x0c2\xce'rm\x0e\xcd\xe9.\xf8\xd2" # Q004 | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_implicit.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_implicit.py.snap index 092dc8ec5a407..1cdfe8417dd3b 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_implicit.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_implicit.py.snap @@ -12,10 +12,8 @@ Q000 [*] Single quotes found but double quotes preferred | help: Replace single quotes with double quotes | -1 | x = ( - - 'This' +2 - 'This' 2 + "This" -3 | 'is' | Q000 [*] Single quotes found but double quotes preferred @@ -30,10 +28,8 @@ Q000 [*] Single quotes found but double quotes preferred | help: Replace single quotes with double quotes | -2 | 'This' - - 'is' +3 - 'is' 3 + "is" -4 | 'not' | Q000 [*] Single quotes found but double quotes preferred @@ -47,10 +43,8 @@ Q000 [*] Single quotes found but double quotes preferred | help: Replace single quotes with double quotes | -3 | 'is' - - 'not' +4 - 'not' 4 + "not" -5 | ) | Q000 [*] Single quotes found but double quotes preferred @@ -64,10 +58,8 @@ Q000 [*] Single quotes found but double quotes preferred | help: Replace single quotes with double quotes | -7 | x = ( - - 'This' \ +8 - 'This' \ 8 + "This" \ -9 | 'is' \ | Q000 [*] Single quotes found but double quotes preferred @@ -81,12 +73,10 @@ Q000 [*] Single quotes found but double quotes preferred 11 | ) | help: Replace single quotes with double quotes - | -8 | 'This' \ - - 'is' \ -9 + "is" \ -10 | 'not' - | + | +9 - 'is' \ +9 + "is" \ + | Q000 [*] Single quotes found but double quotes preferred --> singles_implicit.py:10:5 @@ -99,10 +89,8 @@ Q000 [*] Single quotes found but double quotes preferred | help: Replace single quotes with double quotes | -9 | 'is' \ - - 'not' +10 - 'not' 10 + "not" -11 | ) | Q000 [*] Single quotes found but double quotes preferred @@ -114,7 +102,6 @@ Q000 [*] Single quotes found but double quotes preferred | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace single quotes with double quotes | -26 | 'This can use "single" quotes' - - 'But this needs to be changed' +27 - 'But this needs to be changed' 27 + "But this needs to be changed" | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_multiline_string.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_multiline_string.py.snap index c3d4995483b39..f48f315f7c878 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_multiline_string.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_multiline_string.py.snap @@ -14,10 +14,7 @@ Q001 [*] Single quote multiline found but double quotes preferred | help: Replace single multiline quotes with double quotes | - - s = ''' This 'should' -1 + s = """ This 'should' -2 | be - - 'linted' ''' +1 ~ s = """ This 'should' +2 + be 3 + 'linted' """ -4 | | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_would_be_triple_quotes.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_would_be_triple_quotes.py.snap index 6260fa19f6728..3c7af148a0697 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_would_be_triple_quotes.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_doubles_over_singles_would_be_triple_quotes.py.snap @@ -19,9 +19,8 @@ Q000 [*] Single quotes found but double quotes preferred | help: Replace single quotes with double quotes | - - s = ''"Start with empty string" ' and lint docstring safely' +1 - s = ''"Start with empty string" ' and lint docstring safely' 1 + s = ''"Start with empty string" " and lint docstring safely" -2 | s = 'Do not'" start with empty string" ' and lint docstring safely' | Q000 [*] Single quotes found but double quotes preferred @@ -32,8 +31,7 @@ Q000 [*] Single quotes found but double quotes preferred | ^^^^^^^^ help: Replace single quotes with double quotes | -1 | s = ''"Start with empty string" ' and lint docstring safely' - - s = 'Do not'" start with empty string" ' and lint docstring safely' +2 - s = 'Do not'" start with empty string" ' and lint docstring safely' 2 + s = "Do not"" start with empty string" ' and lint docstring safely' | @@ -45,7 +43,6 @@ Q000 [*] Single quotes found but double quotes preferred | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace single quotes with double quotes | -1 | s = ''"Start with empty string" ' and lint docstring safely' - - s = 'Do not'" start with empty string" ' and lint docstring safely' +2 - s = 'Do not'" start with empty string" ' and lint docstring safely' 2 + s = 'Do not'" start with empty string" " and lint docstring safely" | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles.py.snap index d54a772c714d8..c1fa1a59ef1b1 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles.py.snap @@ -11,9 +11,8 @@ Q000 [*] Double quotes found but single quotes preferred | help: Replace double quotes with single quotes | - - this_should_be_linted = "double quote string" +1 - this_should_be_linted = "double quote string" 1 + this_should_be_linted = 'double quote string' -2 | this_should_be_linted = u"double quote string" | Q000 [*] Double quotes found but single quotes preferred @@ -27,10 +26,8 @@ Q000 [*] Double quotes found but single quotes preferred | help: Replace double quotes with single quotes | -1 | this_should_be_linted = "double quote string" - - this_should_be_linted = u"double quote string" +2 - this_should_be_linted = u"double quote string" 2 + this_should_be_linted = u'double quote string' -3 | this_should_be_linted = f"double quote string" | Q000 [*] Double quotes found but single quotes preferred @@ -44,8 +41,6 @@ Q000 [*] Double quotes found but single quotes preferred | help: Replace double quotes with single quotes | -2 | this_should_be_linted = u"double quote string" - - this_should_be_linted = f"double quote string" +3 - this_should_be_linted = f"double quote string" 3 + this_should_be_linted = f'double quote string' -4 | this_should_be_linted = f"double {'quote'} string" | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_escaped.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_escaped.py.snap index 46600a513b943..e2fed222caa2a 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_escaped.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_escaped.py.snap @@ -11,9 +11,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | - - this_should_raise_Q003 = 'This is a \'string\'' +1 - this_should_raise_Q003 = 'This is a \'string\'' 1 + this_should_raise_Q003 = "This is a 'string'" -2 | this_should_raise_Q003 = 'This is \\ a \\\'string\'' | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -27,10 +26,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -1 | this_should_raise_Q003 = 'This is a \'string\'' - - this_should_raise_Q003 = 'This is \\ a \\\'string\'' +2 - this_should_raise_Q003 = 'This is \\ a \\\'string\'' 2 + this_should_raise_Q003 = "This is \\ a \\'string'" -3 | this_is_fine = '"This" is a \'string\'' | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -44,10 +41,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -9 | 'This is a' - - '\'string\'' +10 - '\'string\'' 10 + "'string'" -11 | ) | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -61,10 +56,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -13 | # Same as above, but with f-strings - - f'This is a \'string\'' # Q003 +14 - f'This is a \'string\'' # Q003 14 + f"This is a 'string'" # Q003 -15 | f'This is \\ a \\\'string\'' # Q003 | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -79,10 +72,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -14 | f'This is a \'string\'' # Q003 - - f'This is \\ a \\\'string\'' # Q003 +15 - f'This is \\ a \\\'string\'' # Q003 15 + f"This is \\ a \\'string'" # Q003 -16 | f'"This" is a \'string\'' | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -96,10 +87,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -22 | f'This is a' - - f'\'string\'' # Q003 +23 - f'\'string\'' # Q003 23 + f"'string'" # Q003 -24 | ) | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -114,10 +103,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -32 | # but as the actual string itself is invalid pre 3.12, we don't catch it. - - f'\'foo\' {'nested'}' # Q003 +33 - f'\'foo\' {'nested'}' # Q003 33 + f"'foo' {'nested'}" # Q003 -34 | f'\'foo\' {f'nested'}' # Q003 | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -131,10 +118,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -33 | f'\'foo\' {'nested'}' # Q003 - - f'\'foo\' {f'nested'}' # Q003 +34 - f'\'foo\' {f'nested'}' # Q003 34 + f"'foo' {f'nested'}" # Q003 -35 | f'\'foo\' {f'\'nested\''} \'\'' # Q003 | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -149,10 +134,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -34 | f'\'foo\' {f'nested'}' # Q003 - - f'\'foo\' {f'\'nested\''} \'\'' # Q003 +35 - f'\'foo\' {f'\'nested\''} \'\'' # Q003 35 + f"'foo' {f'\'nested\''} ''" # Q003 -36 | | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -167,10 +150,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -34 | f'\'foo\' {f'nested'}' # Q003 - - f'\'foo\' {f'\'nested\''} \'\'' # Q003 +35 - f'\'foo\' {f'\'nested\''} \'\'' # Q003 35 + f'\'foo\' {f"'nested'"} \'\'' # Q003 -36 | | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -184,10 +165,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -37 | f'normal {f'nested'} normal' - - f'\'normal\' {f'nested'} normal' # Q003 +38 - f'\'normal\' {f'nested'} normal' # Q003 38 + f"'normal' {f'nested'} normal" # Q003 -39 | f'\'normal\' {f'nested'} "double quotes"' | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -201,10 +180,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -39 | f'\'normal\' {f'nested'} "double quotes"' - - f'\'normal\' {f'\'nested\' {'other'} normal'} "double quotes"' # Q003 +40 - f'\'normal\' {f'\'nested\' {'other'} normal'} "double quotes"' # Q003 40 + f'\'normal\' {f"'nested' {'other'} normal"} "double quotes"' # Q003 -41 | f'\'normal\' {f'\'nested\' {'other'} "double quotes"'} normal' # Q00l | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -216,10 +193,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Change outer quotes to avoid escaping inner quotes | -40 | f'\'normal\' {f'\'nested\' {'other'} normal'} "double quotes"' # Q003 - - f'\'normal\' {f'\'nested\' {'other'} "double quotes"'} normal' # Q00l +41 - f'\'normal\' {f'\'nested\' {'other'} "double quotes"'} normal' # Q00l 41 + f"'normal' {f'\'nested\' {'other'} "double quotes"'} normal" # Q00l -42 | | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -233,10 +208,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -45 | # Same as above, but with t-strings - - t'This is a \'string\'' # Q003 +46 - t'This is a \'string\'' # Q003 46 + t"This is a 'string'" # Q003 -47 | t'This is \\ a \\\'string\'' # Q003 | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -251,10 +224,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -46 | t'This is a \'string\'' # Q003 - - t'This is \\ a \\\'string\'' # Q003 +47 - t'This is \\ a \\\'string\'' # Q003 47 + t"This is \\ a \\'string'" # Q003 -48 | t'"This" is a \'string\'' | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -269,10 +240,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -54 | t'This is a' - - t'\'string\'' # Q003 +55 - t'\'string\'' # Q003 55 + t"'string'" # Q003 -56 | ) | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -287,10 +256,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -56 | ) - - t'\'foo\' {'nested'}' # Q003 +57 - t'\'foo\' {'nested'}' # Q003 57 + t"'foo' {'nested'}" # Q003 -58 | t'\'foo\' {t'nested'}' # Q003 | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -304,10 +271,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -57 | t'\'foo\' {'nested'}' # Q003 - - t'\'foo\' {t'nested'}' # Q003 +58 - t'\'foo\' {t'nested'}' # Q003 58 + t"'foo' {t'nested'}" # Q003 -59 | t'\'foo\' {t'\'nested\''} \'\'' # Q003 | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -322,10 +287,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -58 | t'\'foo\' {t'nested'}' # Q003 - - t'\'foo\' {t'\'nested\''} \'\'' # Q003 +59 - t'\'foo\' {t'\'nested\''} \'\'' # Q003 59 + t"'foo' {t'\'nested\''} ''" # Q003 -60 | | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -340,10 +303,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -58 | t'\'foo\' {t'nested'}' # Q003 - - t'\'foo\' {t'\'nested\''} \'\'' # Q003 +59 - t'\'foo\' {t'\'nested\''} \'\'' # Q003 59 + t'\'foo\' {t"'nested'"} \'\'' # Q003 -60 | | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -357,10 +318,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -61 | t'normal {t'nested'} normal' - - t'\'normal\' {t'nested'} normal' # Q003 +62 - t'\'normal\' {t'nested'} normal' # Q003 62 + t"'normal' {t'nested'} normal" # Q003 -63 | t'\'normal\' {t'nested'} "double quotes"' | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -374,10 +333,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -63 | t'\'normal\' {t'nested'} "double quotes"' - - t'\'normal\' {t'\'nested\' {'other'} normal'} "double quotes"' # Q003 +64 - t'\'normal\' {t'\'nested\' {'other'} normal'} "double quotes"' # Q003 64 + t'\'normal\' {t"'nested' {'other'} normal"} "double quotes"' # Q003 -65 | t'\'normal\' {t'\'nested\' {'other'} "double quotes"'} normal' # Q00l | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -389,7 +346,6 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Change outer quotes to avoid escaping inner quotes | -64 | t'\'normal\' {t'\'nested\' {'other'} normal'} "double quotes"' # Q003 - - t'\'normal\' {t'\'nested\' {'other'} "double quotes"'} normal' # Q00l +65 - t'\'normal\' {t'\'nested\' {'other'} "double quotes"'} normal' # Q00l 65 + t"'normal' {t'\'nested\' {'other'} "double quotes"'} normal" # Q00l | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_escaped_py311.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_escaped_py311.snap index a034a879a6c16..a9f184cc15a3b 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_escaped_py311.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_escaped_py311.snap @@ -11,9 +11,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | - - this_should_raise_Q003 = 'This is a \'string\'' +1 - this_should_raise_Q003 = 'This is a \'string\'' 1 + this_should_raise_Q003 = "This is a 'string'" -2 | this_should_raise_Q003 = 'This is \\ a \\\'string\'' | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -27,10 +26,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -1 | this_should_raise_Q003 = 'This is a \'string\'' - - this_should_raise_Q003 = 'This is \\ a \\\'string\'' +2 - this_should_raise_Q003 = 'This is \\ a \\\'string\'' 2 + this_should_raise_Q003 = "This is \\ a \\'string'" -3 | this_is_fine = '"This" is a \'string\'' | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -44,10 +41,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -9 | 'This is a' - - '\'string\'' +10 - '\'string\'' 10 + "'string'" -11 | ) | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -61,10 +56,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -13 | # Same as above, but with f-strings - - f'This is a \'string\'' # Q003 +14 - f'This is a \'string\'' # Q003 14 + f"This is a 'string'" # Q003 -15 | f'This is \\ a \\\'string\'' # Q003 | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -79,10 +72,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -14 | f'This is a \'string\'' # Q003 - - f'This is \\ a \\\'string\'' # Q003 +15 - f'This is \\ a \\\'string\'' # Q003 15 + f"This is \\ a \\'string'" # Q003 -16 | f'"This" is a \'string\'' | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -96,10 +87,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -22 | f'This is a' - - f'\'string\'' # Q003 +23 - f'\'string\'' # Q003 23 + f"'string'" # Q003 -24 | ) | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -113,10 +102,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -45 | # Same as above, but with t-strings - - t'This is a \'string\'' # Q003 +46 - t'This is a \'string\'' # Q003 46 + t"This is a 'string'" # Q003 -47 | t'This is \\ a \\\'string\'' # Q003 | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -131,10 +118,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -46 | t'This is a \'string\'' # Q003 - - t'This is \\ a \\\'string\'' # Q003 +47 - t'This is \\ a \\\'string\'' # Q003 47 + t"This is \\ a \\'string'" # Q003 -48 | t'"This" is a \'string\'' | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -149,10 +134,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -54 | t'This is a' - - t'\'string\'' # Q003 +55 - t'\'string\'' # Q003 55 + t"'string'" # Q003 -56 | ) | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -167,10 +150,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -56 | ) - - t'\'foo\' {'nested'}' # Q003 +57 - t'\'foo\' {'nested'}' # Q003 57 + t"'foo' {'nested'}" # Q003 -58 | t'\'foo\' {t'nested'}' # Q003 | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -184,10 +165,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -57 | t'\'foo\' {'nested'}' # Q003 - - t'\'foo\' {t'nested'}' # Q003 +58 - t'\'foo\' {t'nested'}' # Q003 58 + t"'foo' {t'nested'}" # Q003 -59 | t'\'foo\' {t'\'nested\''} \'\'' # Q003 | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -202,10 +181,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -58 | t'\'foo\' {t'nested'}' # Q003 - - t'\'foo\' {t'\'nested\''} \'\'' # Q003 +59 - t'\'foo\' {t'\'nested\''} \'\'' # Q003 59 + t"'foo' {t'\'nested\''} ''" # Q003 -60 | | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -220,10 +197,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -58 | t'\'foo\' {t'nested'}' # Q003 - - t'\'foo\' {t'\'nested\''} \'\'' # Q003 +59 - t'\'foo\' {t'\'nested\''} \'\'' # Q003 59 + t'\'foo\' {t"'nested'"} \'\'' # Q003 -60 | | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -237,10 +212,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -61 | t'normal {t'nested'} normal' - - t'\'normal\' {t'nested'} normal' # Q003 +62 - t'\'normal\' {t'nested'} normal' # Q003 62 + t"'normal' {t'nested'} normal" # Q003 -63 | t'\'normal\' {t'nested'} "double quotes"' | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -254,10 +227,8 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | help: Change outer quotes to avoid escaping inner quotes | -63 | t'\'normal\' {t'nested'} "double quotes"' - - t'\'normal\' {t'\'nested\' {'other'} normal'} "double quotes"' # Q003 +64 - t'\'normal\' {t'\'nested\' {'other'} normal'} "double quotes"' # Q003 64 + t'\'normal\' {t"'nested' {'other'} normal"} "double quotes"' # Q003 -65 | t'\'normal\' {t'\'nested\' {'other'} "double quotes"'} normal' # Q00l | Q003 [*] Change outer quotes to avoid escaping inner quotes @@ -269,7 +240,6 @@ Q003 [*] Change outer quotes to avoid escaping inner quotes | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Change outer quotes to avoid escaping inner quotes | -64 | t'\'normal\' {t'\'nested\' {'other'} normal'} "double quotes"' # Q003 - - t'\'normal\' {t'\'nested\' {'other'} "double quotes"'} normal' # Q00l +65 - t'\'normal\' {t'\'nested\' {'other'} "double quotes"'} normal' # Q00l 65 + t"'normal' {t'\'nested\' {'other'} "double quotes"'} normal" # Q00l | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_escaped_unnecessary.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_escaped_unnecessary.py.snap index dcdf0dd56afed..1fb8df89cd878 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_escaped_unnecessary.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_escaped_unnecessary.py.snap @@ -11,9 +11,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | - - this_should_raise_Q004 = 'This is a \"string\"' +1 - this_should_raise_Q004 = 'This is a \"string\"' 1 + this_should_raise_Q004 = 'This is a "string"' -2 | this_should_raise_Q004 = 'This is \\ a \\\"string\"' | Q004 [*] Unnecessary escape on inner quote character @@ -27,10 +26,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -1 | this_should_raise_Q004 = 'This is a \"string\"' - - this_should_raise_Q004 = 'This is \\ a \\\"string\"' +2 - this_should_raise_Q004 = 'This is \\ a \\\"string\"' 2 + this_should_raise_Q004 = 'This is \\ a \\"string"' -3 | this_is_fine = '"This" is a \"string\"' | Q004 [*] Unnecessary escape on inner quote character @@ -45,10 +42,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -2 | this_should_raise_Q004 = 'This is \\ a \\\"string\"' - - this_is_fine = '"This" is a \"string\"' +3 - this_is_fine = '"This" is a \"string\"' 3 + this_is_fine = '"This" is a "string"' -4 | this_is_fine = "This is a 'string'" | Q004 [*] Unnecessary escape on inner quote character @@ -62,10 +57,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -9 | 'This is a' - - '\"string\"' +10 - '\"string\"' 10 + '"string"' -11 | ) | Q004 [*] Unnecessary escape on inner quote character @@ -79,10 +72,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -13 | # Same as above, but with f-strings - - f'This is a \"string\"' # Q004 +14 - f'This is a \"string\"' # Q004 14 + f'This is a "string"' # Q004 -15 | f'This is \\ a \\\"string\"' # Q004 | Q004 [*] Unnecessary escape on inner quote character @@ -97,10 +88,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -14 | f'This is a \"string\"' # Q004 - - f'This is \\ a \\\"string\"' # Q004 +15 - f'This is \\ a \\\"string\"' # Q004 15 + f'This is \\ a \\"string"' # Q004 -16 | f'"This" is a \"string\"' | Q004 [*] Unnecessary escape on inner quote character @@ -115,10 +104,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -15 | f'This is \\ a \\\"string\"' # Q004 - - f'"This" is a \"string\"' +16 - f'"This" is a \"string\"' 16 + f'"This" is a "string"' -17 | f"This is a 'string'" | Q004 [*] Unnecessary escape on inner quote character @@ -132,10 +119,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -22 | f'This is a' - - f'\"string\"' # Q004 +23 - f'\"string\"' # Q004 23 + f'"string"' # Q004 -24 | ) | Q004 [*] Unnecessary escape on inner quote character @@ -150,10 +135,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -32 | # but as the actual string itself is invalid pre 3.12, we don't catch it. - - f'\"foo\" {'nested'}' # Q004 +33 - f'\"foo\" {'nested'}' # Q004 33 + f'"foo" {'nested'}' # Q004 -34 | f'\"foo\" {f'nested'}' # Q004 | Q004 [*] Unnecessary escape on inner quote character @@ -167,10 +150,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -33 | f'\"foo\" {'nested'}' # Q004 - - f'\"foo\" {f'nested'}' # Q004 +34 - f'\"foo\" {f'nested'}' # Q004 34 + f'"foo" {f'nested'}' # Q004 -35 | f'\"foo\" {f'\"nested\"'} \"\"' # Q004 | Q004 [*] Unnecessary escape on inner quote character @@ -185,10 +166,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -34 | f'\"foo\" {f'nested'}' # Q004 - - f'\"foo\" {f'\"nested\"'} \"\"' # Q004 +35 - f'\"foo\" {f'\"nested\"'} \"\"' # Q004 35 + f'"foo" {f'\"nested\"'} ""' # Q004 -36 | | Q004 [*] Unnecessary escape on inner quote character @@ -203,10 +182,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -34 | f'\"foo\" {f'nested'}' # Q004 - - f'\"foo\" {f'\"nested\"'} \"\"' # Q004 +35 - f'\"foo\" {f'\"nested\"'} \"\"' # Q004 35 + f'\"foo\" {f'"nested"'} \"\"' # Q004 -36 | | Q004 [*] Unnecessary escape on inner quote character @@ -220,10 +197,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -37 | f'normal {f'nested'} normal' - - f'\"normal\" {f'nested'} normal' # Q004 +38 - f'\"normal\" {f'nested'} normal' # Q004 38 + f'"normal" {f'nested'} normal' # Q004 -39 | f'\"normal\" {f'nested'} "double quotes"' | Q004 [*] Unnecessary escape on inner quote character @@ -238,10 +213,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -38 | f'\"normal\" {f'nested'} normal' # Q004 - - f'\"normal\" {f'nested'} "double quotes"' +39 - f'\"normal\" {f'nested'} "double quotes"' 39 + f'"normal" {f'nested'} "double quotes"' -40 | f'\"normal\" {f'\"nested\" {'other'} normal'} "double quotes"' # Q004 | Q004 [*] Unnecessary escape on inner quote character @@ -255,10 +228,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -39 | f'\"normal\" {f'nested'} "double quotes"' - - f'\"normal\" {f'\"nested\" {'other'} normal'} "double quotes"' # Q004 +40 - f'\"normal\" {f'\"nested\" {'other'} normal'} "double quotes"' # Q004 40 + f'"normal" {f'\"nested\" {'other'} normal'} "double quotes"' # Q004 -41 | f'\"normal\" {f'\"nested\" {'other'} "double quotes"'} normal' # Q004 | Q004 [*] Unnecessary escape on inner quote character @@ -272,10 +243,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -39 | f'\"normal\" {f'nested'} "double quotes"' - - f'\"normal\" {f'\"nested\" {'other'} normal'} "double quotes"' # Q004 +40 - f'\"normal\" {f'\"nested\" {'other'} normal'} "double quotes"' # Q004 40 + f'\"normal\" {f'"nested" {'other'} normal'} "double quotes"' # Q004 -41 | f'\"normal\" {f'\"nested\" {'other'} "double quotes"'} normal' # Q004 | Q004 [*] Unnecessary escape on inner quote character @@ -290,10 +259,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -40 | f'\"normal\" {f'\"nested\" {'other'} normal'} "double quotes"' # Q004 - - f'\"normal\" {f'\"nested\" {'other'} "double quotes"'} normal' # Q004 +41 - f'\"normal\" {f'\"nested\" {'other'} "double quotes"'} normal' # Q004 41 + f'"normal" {f'\"nested\" {'other'} "double quotes"'} normal' # Q004 -42 | | Q004 [*] Unnecessary escape on inner quote character @@ -308,10 +275,8 @@ Q004 [*] Unnecessary escape on inner quote character | help: Remove backslash | -40 | f'\"normal\" {f'\"nested\" {'other'} normal'} "double quotes"' # Q004 - - f'\"normal\" {f'\"nested\" {'other'} "double quotes"'} normal' # Q004 +41 - f'\"normal\" {f'\"nested\" {'other'} "double quotes"'} normal' # Q004 41 + f'\"normal\" {f'"nested" {'other'} "double quotes"'} normal' # Q004 -42 | | Q004 [*] Unnecessary escape on inner quote character @@ -323,7 +288,6 @@ Q004 [*] Unnecessary escape on inner quote character | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove backslash | -44 | this_is_fine = 'This is an \\"escaped\\" quote' - - this_should_raise_Q004 = 'This is an \\\"escaped\\\" quote with an extra backslash' +45 - this_should_raise_Q004 = 'This is an \\\"escaped\\\" quote with an extra backslash' 45 + this_should_raise_Q004 = 'This is an \\"escaped\\" quote with an extra backslash' | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_implicit.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_implicit.py.snap index 4aeda3de02587..d6f7b17073ec2 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_implicit.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_implicit.py.snap @@ -12,10 +12,8 @@ Q000 [*] Double quotes found but single quotes preferred | help: Replace double quotes with single quotes | -1 | x = ( - - "This" +2 - "This" 2 + 'This' -3 | "is" | Q000 [*] Double quotes found but single quotes preferred @@ -30,10 +28,8 @@ Q000 [*] Double quotes found but single quotes preferred | help: Replace double quotes with single quotes | -2 | "This" - - "is" +3 - "is" 3 + 'is' -4 | "not" | Q000 [*] Double quotes found but single quotes preferred @@ -47,10 +43,8 @@ Q000 [*] Double quotes found but single quotes preferred | help: Replace double quotes with single quotes | -3 | "is" - - "not" +4 - "not" 4 + 'not' -5 | ) | Q000 [*] Double quotes found but single quotes preferred @@ -64,10 +58,8 @@ Q000 [*] Double quotes found but single quotes preferred | help: Replace double quotes with single quotes | -7 | x = ( - - "This" \ +8 - "This" \ 8 + 'This' \ -9 | "is" \ | Q000 [*] Double quotes found but single quotes preferred @@ -81,12 +73,10 @@ Q000 [*] Double quotes found but single quotes preferred 11 | ) | help: Replace double quotes with single quotes - | -8 | "This" \ - - "is" \ -9 + 'is' \ -10 | "not" - | + | +9 - "is" \ +9 + 'is' \ + | Q000 [*] Double quotes found but single quotes preferred --> doubles_implicit.py:10:5 @@ -99,10 +89,8 @@ Q000 [*] Double quotes found but single quotes preferred | help: Replace double quotes with single quotes | -9 | "is" \ - - "not" +10 - "not" 10 + 'not' -11 | ) | Q000 [*] Double quotes found but single quotes preferred @@ -114,7 +102,6 @@ Q000 [*] Double quotes found but single quotes preferred | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace double quotes with single quotes | -26 | "This can use 'double' quotes" - - "But this needs to be changed" +27 - "But this needs to be changed" 27 + 'But this needs to be changed' | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_multiline_string.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_multiline_string.py.snap index e1eaf21fd91d8..13bea39db16da 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_multiline_string.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_multiline_string.py.snap @@ -14,10 +14,7 @@ Q001 [*] Double quote multiline found but single quotes preferred | help: Replace double multiline quotes with single quotes | - - s = """ This "should" -1 + s = ''' This "should" -2 | be - - "linted" """ +1 ~ s = ''' This "should" +2 + be 3 + "linted" ''' -4 | | diff --git a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_would_be_triple_quotes.py.snap b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_would_be_triple_quotes.py.snap index abfdc49025355..9bcc1072b2696 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_would_be_triple_quotes.py.snap +++ b/crates/ruff_linter/src/rules/flake8_quotes/snapshots/ruff_linter__rules__flake8_quotes__tests__require_singles_over_doubles_would_be_triple_quotes.py.snap @@ -18,7 +18,6 @@ Q000 [*] Double quotes found but single quotes preferred | ^^^^^^^^ help: Replace double quotes with single quotes | -1 | s = ""'Start with empty string' ' and lint docstring safely' - - s = "Do not"' start with empty string' ' and lint docstring safely' +2 - s = "Do not"' start with empty string' ' and lint docstring safely' 2 + s = 'Do not'' start with empty string' ' and lint docstring safely' | diff --git a/crates/ruff_linter/src/rules/flake8_raise/snapshots/ruff_linter__rules__flake8_raise__tests__unnecessary-paren-on-raise-exception_RSE102.py.snap b/crates/ruff_linter/src/rules/flake8_raise/snapshots/ruff_linter__rules__flake8_raise__tests__unnecessary-paren-on-raise-exception_RSE102.py.snap index 5e2ff0db58e08..b0148bb965c12 100644 --- a/crates/ruff_linter/src/rules/flake8_raise/snapshots/ruff_linter__rules__flake8_raise__tests__unnecessary-paren-on-raise-exception_RSE102.py.snap +++ b/crates/ruff_linter/src/rules/flake8_raise/snapshots/ruff_linter__rules__flake8_raise__tests__unnecessary-paren-on-raise-exception_RSE102.py.snap @@ -13,10 +13,8 @@ RSE102 [*] Unnecessary parentheses on raised exception | help: Remove unnecessary parentheses | -4 | # RSE102 - - raise ValueError() +5 - raise ValueError() 5 + raise ValueError -6 | | RSE102 [*] Unnecessary parentheses on raised exception @@ -30,10 +28,8 @@ RSE102 [*] Unnecessary parentheses on raised exception | help: Remove unnecessary parentheses | -12 | # RSE102 - - raise TypeError() +13 - raise TypeError() 13 + raise TypeError -14 | | RSE102 [*] Unnecessary parentheses on raised exception @@ -47,10 +43,8 @@ RSE102 [*] Unnecessary parentheses on raised exception | help: Remove unnecessary parentheses | -15 | # RSE102 - - raise TypeError () +16 - raise TypeError () 16 + raise TypeError -17 | | RSE102 [*] Unnecessary parentheses on raised exception @@ -65,10 +59,7 @@ RSE102 [*] Unnecessary parentheses on raised exception | help: Remove unnecessary parentheses | -19 | raise TypeError \ - - () -20 + -21 | +20 - () | RSE102 [*] Unnecessary parentheses on raised exception @@ -83,10 +74,8 @@ RSE102 [*] Unnecessary parentheses on raised exception | help: Remove unnecessary parentheses | -23 | raise TypeError \ - - (); +24 - (); 24 + ; -25 | | RSE102 [*] Unnecessary parentheses on raised exception @@ -103,12 +92,10 @@ RSE102 [*] Unnecessary parentheses on raised exception | help: Remove unnecessary parentheses | -26 | # RSE102 - - raise TypeError( - - - - ) +27 - raise TypeError( +28 - +29 - ) 27 + raise TypeError -28 | | RSE102 [*] Unnecessary parentheses on raised exception @@ -125,12 +112,10 @@ RSE102 [*] Unnecessary parentheses on raised exception | help: Remove unnecessary parentheses | -31 | # RSE102 - - raise (TypeError) ( - - - - ) +32 - raise (TypeError) ( +33 - +34 - ) 32 + raise (TypeError) -33 | | RSE102 [*] Unnecessary parentheses on raised exception @@ -147,12 +132,10 @@ RSE102 [*] Unnecessary parentheses on raised exception | help: Remove unnecessary parentheses | -36 | # RSE102 - - raise TypeError( - - # Hello, world! - - ) +37 - raise TypeError( +38 - # Hello, world! +39 - ) 37 + raise TypeError -38 | | note: This is an unsafe fix and may change runtime behavior @@ -167,10 +150,8 @@ RSE102 [*] Unnecessary parentheses on raised exception | help: Remove unnecessary parentheses | -73 | # RSE102 - - raise IndexError()from ZeroDivisionError +74 - raise IndexError()from ZeroDivisionError 74 + raise IndexError from ZeroDivisionError -75 | | RSE102 [*] Unnecessary parentheses on raised exception @@ -184,10 +165,8 @@ RSE102 [*] Unnecessary parentheses on raised exception | help: Remove unnecessary parentheses | -75 | - - raise IndexError()\ +76 - raise IndexError()\ 76 + raise IndexError\ -77 | from ZeroDivisionError | RSE102 [*] Unnecessary parentheses on raised exception @@ -202,10 +181,8 @@ RSE102 [*] Unnecessary parentheses on raised exception | help: Remove unnecessary parentheses | -78 | - - raise IndexError() from ZeroDivisionError +79 - raise IndexError() from ZeroDivisionError 79 + raise IndexError from ZeroDivisionError -80 | | RSE102 [*] Unnecessary parentheses on raised exception @@ -220,10 +197,8 @@ RSE102 [*] Unnecessary parentheses on raised exception | help: Remove unnecessary parentheses | -80 | - - raise IndexError(); +81 - raise IndexError(); 81 + raise IndexError; -82 | | RSE102 [*] Unnecessary parentheses on raised exception @@ -237,10 +212,8 @@ RSE102 [*] Unnecessary parentheses on raised exception | help: Remove unnecessary parentheses | -83 | # RSE102 - - raise Foo() +84 - raise Foo() 84 + raise Foo -85 | | note: This is an unsafe fix and may change runtime behavior @@ -253,10 +226,8 @@ RSE102 [*] Unnecessary parentheses on raised exception | ^^ help: Remove unnecessary parentheses | -106 | if future.exception(): - - raise future.Exception() +107 - raise future.Exception() 107 + raise future.Exception -108 | | note: This is an unsafe fix and may change runtime behavior @@ -270,10 +241,9 @@ RSE102 [*] Unnecessary parentheses on raised exception | |_^ help: Remove unnecessary parentheses | -109 | - - raise TypeError( - - # comment - - ) +110 - raise TypeError( +111 - # comment +112 - ) 110 + raise TypeError | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET501_RET501.py.snap b/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET501_RET501.py.snap index e741c2ab9b792..325d6dc43fb60 100644 --- a/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET501_RET501.py.snap +++ b/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET501_RET501.py.snap @@ -10,10 +10,8 @@ RET501 [*] Do not explicitly `return None` in function if it is the only possibl | ^^^^^^^^^^^ help: Remove explicit `return None` | -3 | return - - return None # error +4 - return None # error 4 + return # error -5 | | RET501 [*] Do not explicitly `return None` in function if it is the only possible return value @@ -28,10 +26,8 @@ RET501 [*] Do not explicitly `return None` in function if it is the only possibl | help: Remove explicit `return None` | -13 | print(f"{key} not found") - - return None +14 - return None 14 + return -15 | | RET501 [*] Do not explicitly `return None` in function if it is the only possible return value @@ -45,10 +41,9 @@ RET501 [*] Do not explicitly `return None` in function if it is the only possibl | |_________^ help: Remove explicit `return None` | -58 | return - - return ( - - None # comment - - ) +59 - return ( +60 - None # comment +61 - ) 59 + return | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET502_RET502.py.snap b/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET502_RET502.py.snap index 153119fe8d42b..02d3010c36a8a 100644 --- a/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET502_RET502.py.snap +++ b/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET502_RET502.py.snap @@ -12,8 +12,5 @@ RET502 [*] Do not implicitly `return None` in function able to return non-`None` | help: Add explicit `None` return value | -2 | if not y: - - return # error -3 + return None # error -4 | return 1 - | +3 | return None # error + | ++++ diff --git a/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET503_RET503.py.snap b/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET503_RET503.py.snap index eaaa56b939d77..3686f68054125 100644 --- a/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET503_RET503.py.snap +++ b/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET503_RET503.py.snap @@ -13,9 +13,8 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | help: Add explicit `return` statement | -22 | return 1 +22 ~ return 1 23 + return None -24 | # error | note: This is an unsafe fix and may change runtime behavior @@ -30,9 +29,8 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | |________________^ help: Add explicit `return` statement | -30 | return 2 +30 ~ return 2 31 + return None -32 | | note: This is an unsafe fix and may change runtime behavior @@ -47,9 +45,8 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | |___________^ help: Add explicit `return` statement | -37 | print() # error +37 ~ print() # error 38 + return None -39 | | note: This is an unsafe fix and may change runtime behavior @@ -66,9 +63,8 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | help: Add explicit `return` statement | -44 | return i +44 ~ return i 45 + return None -46 | # error | note: This is an unsafe fix and may change runtime behavior @@ -84,9 +80,8 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | |_______________^ help: Add explicit `return` statement | -53 | print() # error +53 ~ print() # error 54 + return None -55 | | note: This is an unsafe fix and may change runtime behavior @@ -101,9 +96,8 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | |______________________^ help: Add explicit `return` statement | -60 | no_such_function() # error +60 ~ no_such_function() # error 61 + return None -62 | | note: This is an unsafe fix and may change runtime behavior @@ -118,9 +112,8 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | |_____________________^ help: Add explicit `return` statement | -67 | print("", end="") # error +67 ~ print("", end="") # error 68 + return None -69 | | note: This is an unsafe fix and may change runtime behavior @@ -136,9 +129,8 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | |______________^ help: Add explicit `return` statement | -86 | y += 1 +86 ~ y += 1 87 + return None -88 | | note: This is an unsafe fix and may change runtime behavior @@ -154,9 +146,8 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | |________________^ help: Add explicit `return` statement | -117 | return z +117 ~ return z 118 + return None -119 | | note: This is an unsafe fix and may change runtime behavior @@ -174,9 +165,8 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | |___________________^ help: Add explicit `return` statement | -127 | return None +127 ~ return None 128 + return None -129 | | note: This is an unsafe fix and may change runtime behavior @@ -191,9 +181,8 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | |________________^ help: Add explicit `return` statement | -134 | return z +134 ~ return z 135 + return None -136 | | note: This is an unsafe fix and may change runtime behavior @@ -211,9 +200,8 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | |___________________^ help: Add explicit `return` statement | -144 | return None +144 ~ return None 145 + return None -146 | | note: This is an unsafe fix and may change runtime behavior @@ -229,9 +217,8 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | |____________________^ help: Add explicit `return` statement | -276 | print(value) +276 ~ print(value) 277 + return None -278 | | note: This is an unsafe fix and may change runtime behavior @@ -248,9 +235,8 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | |___________________^ help: Add explicit `return` statement | -292 | print() # error +292 ~ print() # error 293 + return None -294 | | note: This is an unsafe fix and may change runtime behavior @@ -264,9 +250,8 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | |_____________________^ help: Add explicit `return` statement | -302 | return "" +302 ~ return "" 303 + return None -304 | | note: This is an unsafe fix and may change runtime behavior @@ -279,9 +264,8 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | |_____________________^ help: Add explicit `return` statement | -307 | return "" +307 ~ return "" 308 + return None -309 | | note: This is an unsafe fix and may change runtime behavior @@ -294,9 +278,8 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | |_____________________^ help: Add explicit `return` statement | -312 | return "" # type: ignore +312 ~ return "" # type: ignore 313 + return None -314 | | note: This is an unsafe fix and may change runtime behavior @@ -309,9 +292,8 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | |_____________________^ help: Add explicit `return` statement | -317 | return "" ; +317 ~ return "" ; 318 + return None -319 | | note: This is an unsafe fix and may change runtime behavior @@ -326,9 +308,8 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | help: Add explicit `return` statement | -323 | ; # type: ignore +323 ~ ; # type: ignore 324 + return None -325 | | note: This is an unsafe fix and may change runtime behavior @@ -342,9 +323,8 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | |_________^ help: Add explicit `return` statement | -330 | +330 + 331 + return None -332 | | note: This is an unsafe fix and may change runtime behavior @@ -360,9 +340,8 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | |_____________^ help: Add explicit `return` statement | -403 | d +403 ~ d 404 + return None -405 | | note: This is an unsafe fix and may change runtime behavior @@ -380,9 +359,7 @@ RET503 [*] Missing explicit `return` at the end of function able to return non-` | |_________^ help: Add explicit `return` statement | -417 | return 5 - - bar() -418 + bar() +418 ~ bar() 419 + return None | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET504_RET504.py.snap b/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET504_RET504.py.snap index f86aab6b5a37f..f5d7b24ffa8fc 100644 --- a/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET504_RET504.py.snap +++ b/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET504_RET504.py.snap @@ -10,11 +10,10 @@ RET504 [*] Unnecessary assignment to `a` before `return` statement | ^ help: Remove unnecessary assignment | -4 | def x(): - - a = 1 - - return a # RET504 +5 - a = 1 +6 - return a # RET504 +7 - 5 + return 1 -6 | | note: This is an unsafe fix and may change runtime behavior @@ -27,11 +26,10 @@ RET504 [*] Unnecessary assignment to `formatted` before `return` statement | ^^^^^^^^^ help: Remove unnecessary assignment | -21 | # clean up after any blank components - - formatted = formatted.replace("()", "").replace(" ", " ").strip() - - return formatted +22 - formatted = formatted.replace("()", "").replace(" ", " ").strip() +23 - return formatted +24 - 22 + return formatted.replace("()", "").replace(" ", " ").strip() -23 | | note: This is an unsafe fix and may change runtime behavior @@ -44,11 +42,10 @@ RET504 [*] Unnecessary assignment to `queryset` before `return` statement | ^^^^^^^^ help: Remove unnecessary assignment | -244 | queryset = Model.filter(a=1) - - queryset = queryset.filter(c=3) - - return queryset +245 - queryset = queryset.filter(c=3) +246 - return queryset +247 - 245 + return queryset.filter(c=3) -246 | | note: This is an unsafe fix and may change runtime behavior @@ -61,11 +58,10 @@ RET504 [*] Unnecessary assignment to `queryset` before `return` statement | ^^^^^^^^ help: Remove unnecessary assignment | -249 | def get_queryset(): - - queryset = Model.filter(a=1) - - return queryset # RET504 +250 - queryset = Model.filter(a=1) +251 - return queryset # RET504 +252 - 250 + return Model.filter(a=1) -251 | | note: This is an unsafe fix and may change runtime behavior @@ -78,11 +74,10 @@ RET504 [*] Unnecessary assignment to `val` before `return` statement | ^^^ help: Remove unnecessary assignment | -267 | return val - - val = 1 - - return val # RET504 +268 - val = 1 +269 - return val # RET504 +270 - 268 + return 1 -269 | | note: This is an unsafe fix and may change runtime behavior @@ -95,11 +90,10 @@ RET504 [*] Unnecessary assignment to `x` before `return` statement | ^ help: Remove unnecessary assignment | -319 | with open("foo.txt", "r") as f: - - x = f.read() - - return x # RET504 +320 - x = f.read() +321 - return x # RET504 +322 - 320 + return f.read() -321 | | note: This is an unsafe fix and may change runtime behavior @@ -112,11 +106,10 @@ RET504 [*] Unnecessary assignment to `b` before `return` statement | ^ help: Remove unnecessary assignment | -340 | a = 1 - - b=a - - return b # RET504 +341 - b=a +342 - return b # RET504 +343 - 341 + return a -342 | | note: This is an unsafe fix and may change runtime behavior @@ -129,11 +122,10 @@ RET504 [*] Unnecessary assignment to `b` before `return` statement | ^ help: Remove unnecessary assignment | -346 | a = 1 - - b =a - - return b # RET504 +347 - b =a +348 - return b # RET504 +349 - 347 + return a -348 | | note: This is an unsafe fix and may change runtime behavior @@ -146,11 +138,10 @@ RET504 [*] Unnecessary assignment to `b` before `return` statement | ^ help: Remove unnecessary assignment | -352 | a = 1 - - b= a - - return b # RET504 +353 - b= a +354 - return b # RET504 +355 - 353 + return a -354 | | note: This is an unsafe fix and may change runtime behavior @@ -163,11 +154,10 @@ RET504 [*] Unnecessary assignment to `a` before `return` statement | ^ help: Remove unnecessary assignment | -357 | def foo(): - - a = 1 # Comment - - return a +358 - a = 1 # Comment +359 - return a +360 - 358 + return 1 # Comment -359 | | note: This is an unsafe fix and may change runtime behavior @@ -180,11 +170,10 @@ RET504 [*] Unnecessary assignment to `D` before `return` statement | ^ help: Remove unnecessary assignment | -363 | def mavko_debari(P_kbar): - - D=0.4853881 + 3.6006116*P - 0.0117368*(P-1.3822)**2 - - return D +364 - D=0.4853881 + 3.6006116*P - 0.0117368*(P-1.3822)**2 +365 - return D +366 - 364 + return 0.4853881 + 3.6006116*P - 0.0117368*(P-1.3822)**2 -365 | | note: This is an unsafe fix and may change runtime behavior @@ -197,11 +186,10 @@ RET504 [*] Unnecessary assignment to `y` before `return` statement | ^ help: Remove unnecessary assignment | -398 | x = 1 - - y = y + 2 - - return y # RET504 +399 - y = y + 2 +400 - return y # RET504 +401 - 399 + return y + 2 -400 | | note: This is an unsafe fix and may change runtime behavior @@ -214,11 +202,10 @@ RET504 [*] Unnecessary assignment to `services` before `return` statement | ^^^^^^^^ help: Remove unnecessary assignment | -421 | if "services" in a: - - services = a["services"] - - return services +422 - services = a["services"] +423 - return services +424 - 422 + return a["services"] -423 | | note: This is an unsafe fix and may change runtime behavior @@ -234,12 +221,11 @@ RET504 [*] Unnecessary assignment to `x` before `return` statement | help: Remove unnecessary assignment | -455 | def f(): - - (#= - - x) = 1 - - return x +456 - (#= +457 - x) = 1 +458 - return x +459 - 456 + return 1 -457 | | note: This is an unsafe fix and may change runtime behavior @@ -252,10 +238,6 @@ RET504 [*] Unnecessary assignment to `x` before `return` statement | ^ help: Remove unnecessary assignment | -460 | def f(): - - x = (1 -461 + return (1 -462 | ) - - return x +461 ~ return (1 | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET505_RET505.py.snap b/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET505_RET505.py.snap index 7882189b06b24..b1de2088ef19e 100644 --- a/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET505_RET505.py.snap +++ b/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET505_RET505.py.snap @@ -13,10 +13,8 @@ RET505 [*] Unnecessary `elif` after `return` statement | help: Remove unnecessary `elif` | -7 | return y - - elif z: +8 - elif z: 8 + if z: -9 | b = 2 | RET505 [*] Unnecessary `elif` after `return` statement @@ -31,10 +29,8 @@ RET505 [*] Unnecessary `elif` after `return` statement | help: Remove unnecessary `elif` | -22 | return - - elif z: +23 - elif z: 23 + if z: -24 | c = 2 | RET505 [*] Unnecessary `elif` after `return` statement @@ -49,10 +45,8 @@ RET505 [*] Unnecessary `elif` after `return` statement | help: Remove unnecessary `elif` | -40 | return y - - elif z: +41 - elif z: 41 + if z: -42 | b = 2 | RET505 [*] Unnecessary `else` after `return` statement @@ -67,13 +61,8 @@ RET505 [*] Unnecessary `else` after `return` statement | help: Remove unnecessary `else` | -52 | return y - - else: - - b = 2 - - return z 53 + b = 2 54 + return z -55 | | RET505 [*] Unnecessary `else` after `return` statement @@ -88,13 +77,8 @@ RET505 [*] Unnecessary `else` after `return` statement | help: Remove unnecessary `else` | -63 | return y - - else: - - c = 3 - - return x 64 + c = 3 65 + return x -66 | else: | RET505 [*] Unnecessary `else` after `return` statement @@ -109,11 +93,9 @@ RET505 [*] Unnecessary `else` after `return` statement | help: Remove unnecessary `else` | -78 | return - - else: - - c = 3 +79 - else: +80 - c = 3 79 + c = 3 -80 | return | RET505 [*] Unnecessary `else` after `return` statement @@ -128,11 +110,9 @@ RET505 [*] Unnecessary `else` after `return` statement | help: Remove unnecessary `else` | -88 | return - - else: - - b = 2 +89 - else: +90 - b = 2 89 + b = 2 -90 | else: | RET505 [*] Unnecessary `else` after `return` statement @@ -147,17 +127,10 @@ RET505 [*] Unnecessary `else` after `return` statement | help: Remove unnecessary `else` | -98 | return True - - else: - - try: - - return False - - except ValueError: - - return None -99 + try: + 99 + try: 100 + return False 101 + except ValueError: 102 + return None -103 | | RET505 [*] Unnecessary `else` after `return` statement @@ -172,13 +145,8 @@ RET505 [*] Unnecessary `else` after `return` statement | help: Remove unnecessary `else` | -108 | return n; - - else: - - last = 1; - - last2 = 0; 109 + last = 1; -110 + last2 = 0; -111 | +110 ~ last2 = 0; | RET505 [*] Unnecessary `else` after `return` statement @@ -193,13 +161,8 @@ RET505 [*] Unnecessary `else` after `return` statement | help: Remove unnecessary `else` | -144 | return - - else: - - # comment - - pass 145 + # comment 146 + pass -147 | | RET505 [*] Unnecessary `else` after `return` statement @@ -213,12 +176,8 @@ RET505 [*] Unnecessary `else` after `return` statement | help: Remove unnecessary `else` | -152 | return - - else: # comment - - pass 153 + # comment 154 + pass -155 | | RET505 [*] Unnecessary `else` after `return` statement @@ -233,14 +192,8 @@ RET505 [*] Unnecessary `else` after `return` statement | help: Remove unnecessary `else` | -159 | return - - else\ - - :\ - - # comment - - pass 160 + # comment 161 + pass -162 | | RET505 [*] Unnecessary `else` after `return` statement @@ -255,13 +208,8 @@ RET505 [*] Unnecessary `else` after `return` statement | help: Remove unnecessary `else` | -168 | return - - else\ - - : # comment - - pass 169 + # comment 170 + pass -171 | | RET505 [*] Unnecessary `else` after `return` statement @@ -273,10 +221,8 @@ RET505 [*] Unnecessary `else` after `return` statement | ^^^^ help: Remove unnecessary `else` | -176 | return - - else: pass +177 - else: pass 177 + pass -178 | | RET505 [*] Unnecessary `else` after `return` statement @@ -290,11 +236,9 @@ RET505 [*] Unnecessary `else` after `return` statement | help: Remove unnecessary `else` | -182 | return - - else:\ - - pass +183 - else:\ +184 - pass 183 + pass -184 | | RET505 [*] Unnecessary `else` after `return` statement @@ -306,10 +250,8 @@ RET505 [*] Unnecessary `else` after `return` statement | ^^^^ help: Remove unnecessary `else` | -199 | if self._sb is not None: return self._sb - - else: self._sb = '\033[01;%dm'; self._sa = '\033[0;0m'; +200 - else: self._sb = '\033[01;%dm'; self._sa = '\033[0;0m'; 200 + self._sb = '\033[01;%dm'; self._sa = '\033[0;0m'; -201 | | RET505 [*] Unnecessary `else` after `return` statement @@ -324,14 +266,9 @@ RET505 [*] Unnecessary `else` after `return` statement | help: Remove unnecessary `else` | -206 | return y - - else: -207 | - - c = 3 - - return z +207 + 208 + c = 3 209 + return z -210 | | RET505 [*] Unnecessary `else` after `return` statement @@ -346,15 +283,9 @@ RET505 [*] Unnecessary `else` after `return` statement | help: Remove unnecessary `else` | -216 | return y - - else: - - # comment - - c = 3 - - return z 217 + # comment 218 + c = 3 219 + return z -220 | | RET505 [*] Unnecessary `else` after `return` statement @@ -369,15 +300,9 @@ RET505 [*] Unnecessary `else` after `return` statement | help: Remove unnecessary `else` | -226 | return y - - else: - - # comment - - c = 3 - - return z 227 + # comment 228 + c = 3 229 + return z -230 | | RET505 [*] Unnecessary `else` after `return` statement @@ -392,14 +317,9 @@ RET505 [*] Unnecessary `else` after `return` statement | help: Remove unnecessary `else` | -236 | return y - - else: -237 | # comment - - c = 3 - - return z +237 + # comment 238 + c = 3 239 + return z -240 | | RET505 [*] Unnecessary `else` after `return` statement @@ -413,11 +333,9 @@ RET505 [*] Unnecessary `else` after `return` statement | help: Remove unnecessary `else` | -244 | return True - - else: - - return False -245 + return False -246 | +245 - else: +246 - return False +245 + return False | RET505 Unnecessary `else` after `return` statement diff --git a/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET506_RET506.py.snap b/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET506_RET506.py.snap index 7e899bb6d0eb1..198f796f8c629 100644 --- a/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET506_RET506.py.snap +++ b/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET506_RET506.py.snap @@ -13,10 +13,8 @@ RET506 [*] Unnecessary `elif` after `raise` statement | help: Remove unnecessary `elif` | -7 | raise Exception(y) - - elif z: +8 - elif z: 8 + if z: -9 | b = 2 | RET506 [*] Unnecessary `elif` after `raise` statement @@ -31,10 +29,8 @@ RET506 [*] Unnecessary `elif` after `raise` statement | help: Remove unnecessary `elif` | -22 | raise Exception(x) - - elif z: +23 - elif z: 23 + if z: -24 | raise Exception(y) | RET506 [*] Unnecessary `else` after `raise` statement @@ -49,13 +45,8 @@ RET506 [*] Unnecessary `else` after `raise` statement | help: Remove unnecessary `else` | -33 | raise Exception(y) - - else: - - b = 2 - - raise Exception(z) 34 + b = 2 35 + raise Exception(z) -36 | | RET506 [*] Unnecessary `else` after `raise` statement @@ -70,13 +61,8 @@ RET506 [*] Unnecessary `else` after `raise` statement | help: Remove unnecessary `else` | -44 | raise Exception(y) - - else: - - c = 3 - - raise Exception(x) 45 + c = 3 46 + raise Exception(x) -47 | else: | RET506 [*] Unnecessary `else` after `raise` statement @@ -91,11 +77,9 @@ RET506 [*] Unnecessary `else` after `raise` statement | help: Remove unnecessary `else` | -59 | raise Exception(x) - - else: - - c = 3 +60 - else: +61 - c = 3 60 + c = 3 -61 | raise Exception(y) | RET506 [*] Unnecessary `else` after `raise` statement @@ -110,11 +94,9 @@ RET506 [*] Unnecessary `else` after `raise` statement | help: Remove unnecessary `else` | -69 | raise Exception(x) - - else: - - b = 2 +70 - else: +71 - b = 2 70 + b = 2 -71 | else: | RET506 [*] Unnecessary `else` after `raise` statement @@ -129,15 +111,8 @@ RET506 [*] Unnecessary `else` after `raise` statement | help: Remove unnecessary `else` | -79 | raise Exception(True) - - else: - - try: - - raise Exception(False) - - except ValueError: - - raise Exception(None) 80 + try: 81 + raise Exception(False) 82 + except ValueError: 83 + raise Exception(None) -84 | | diff --git a/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET507_RET507.py.snap b/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET507_RET507.py.snap index 42e07cf29fbb2..6a9efe9d56d00 100644 --- a/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET507_RET507.py.snap +++ b/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET507_RET507.py.snap @@ -13,10 +13,8 @@ RET507 [*] Unnecessary `elif` after `continue` statement | help: Remove unnecessary `elif` | -7 | continue - - elif i < w: +8 - elif i < w: 8 + if i < w: -9 | continue | RET507 [*] Unnecessary `elif` after `continue` statement @@ -31,10 +29,8 @@ RET507 [*] Unnecessary `elif` after `continue` statement | help: Remove unnecessary `elif` | -21 | continue - - elif z: +22 - elif z: 22 + if z: -23 | c = 2 | RET507 [*] Unnecessary `else` after `continue` statement @@ -48,11 +44,9 @@ RET507 [*] Unnecessary `else` after `continue` statement | help: Remove unnecessary `else` | -35 | continue - - else: - - a = z +36 - else: +37 - a = z 36 + a = z -37 | | RET507 [*] Unnecessary `else` after `continue` statement @@ -67,13 +61,8 @@ RET507 [*] Unnecessary `else` after `continue` statement | help: Remove unnecessary `else` | -46 | continue - - else: - - c = 3 - - continue 47 + c = 3 48 + continue -49 | else: | RET507 [*] Unnecessary `else` after `continue` statement @@ -88,11 +77,9 @@ RET507 [*] Unnecessary `else` after `continue` statement | help: Remove unnecessary `else` | -62 | continue - - else: - - c = 3 +63 - else: +64 - c = 3 63 + c = 3 -64 | continue | RET507 [*] Unnecessary `else` after `continue` statement @@ -107,11 +94,9 @@ RET507 [*] Unnecessary `else` after `continue` statement | help: Remove unnecessary `else` | -73 | continue - - else: - - b = 2 +74 - else: +75 - b = 2 74 + b = 2 -75 | else: | RET507 [*] Unnecessary `else` after `continue` statement @@ -126,15 +111,8 @@ RET507 [*] Unnecessary `else` after `continue` statement | help: Remove unnecessary `else` | -84 | continue - - else: - - try: - - return - - except ValueError: - - continue 85 + try: 86 + return 87 + except ValueError: 88 + continue -89 | | diff --git a/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET508_RET508.py.snap b/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET508_RET508.py.snap index 0a43321d6ff6e..ac49dddcf0519 100644 --- a/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET508_RET508.py.snap +++ b/crates/ruff_linter/src/rules/flake8_return/snapshots/ruff_linter__rules__flake8_return__tests__RET508_RET508.py.snap @@ -13,10 +13,8 @@ RET508 [*] Unnecessary `elif` after `break` statement | help: Remove unnecessary `elif` | -7 | break - - elif i > w: +8 - elif i > w: 8 + if i > w: -9 | break | RET508 [*] Unnecessary `elif` after `break` statement @@ -31,10 +29,8 @@ RET508 [*] Unnecessary `elif` after `break` statement | help: Remove unnecessary `elif` | -21 | break - - elif z: +22 - elif z: 22 + if z: -23 | c = 2 | RET508 [*] Unnecessary `else` after `break` statement @@ -48,11 +44,9 @@ RET508 [*] Unnecessary `else` after `break` statement | help: Remove unnecessary `else` | -32 | break - - else: - - a = z +33 - else: +34 - a = z 33 + a = z -34 | | RET508 [*] Unnecessary `else` after `break` statement @@ -67,13 +61,8 @@ RET508 [*] Unnecessary `else` after `break` statement | help: Remove unnecessary `else` | -43 | break - - else: - - c = 3 - - break 44 + c = 3 45 + break -46 | else: | RET508 [*] Unnecessary `else` after `break` statement @@ -88,11 +77,9 @@ RET508 [*] Unnecessary `else` after `break` statement | help: Remove unnecessary `else` | -59 | break - - else: - - c = 3 +60 - else: +61 - c = 3 60 + c = 3 -61 | break | RET508 [*] Unnecessary `else` after `break` statement @@ -107,11 +94,9 @@ RET508 [*] Unnecessary `else` after `break` statement | help: Remove unnecessary `else` | -70 | break - - else: - - b = 2 +71 - else: +72 - b = 2 71 + b = 2 -72 | else: | RET508 [*] Unnecessary `else` after `break` statement @@ -126,17 +111,10 @@ RET508 [*] Unnecessary `else` after `break` statement | help: Remove unnecessary `else` | -81 | break - - else: - - try: - - return - - except ValueError: - - break 82 + try: 83 + return 84 + except ValueError: 85 + break -86 | | RET508 [*] Unnecessary `else` after `break` statement @@ -150,8 +128,7 @@ RET508 [*] Unnecessary `else` after `break` statement | help: Remove unnecessary `else` | -157 | break - - else: - - a = z +158 - else: +159 - a = z 158 + a = z | diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM101_SIM101.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM101_SIM101.py.snap index 193b47c6ded60..de084de123598 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM101_SIM101.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM101_SIM101.py.snap @@ -10,9 +10,8 @@ SIM101 [*] Multiple `isinstance` calls for `a`, merge into a single call | help: Merge `isinstance` calls for `a` | - - if isinstance(a, int) or isinstance(a, float): # SIM101 +1 - if isinstance(a, int) or isinstance(a, float): # SIM101 1 + if isinstance(a, (int, float)): # SIM101 -2 | pass | note: This is an unsafe fix and may change runtime behavior @@ -27,10 +26,8 @@ SIM101 [*] Multiple `isinstance` calls for `a`, merge into a single call | help: Merge `isinstance` calls for `a` | -3 | - - if isinstance(a, (int, float)) or isinstance(a, bool): # SIM101 +4 - if isinstance(a, (int, float)) or isinstance(a, bool): # SIM101 4 + if isinstance(a, (int, float, bool)): # SIM101 -5 | pass | note: This is an unsafe fix and may change runtime behavior @@ -45,10 +42,8 @@ SIM101 [*] Multiple `isinstance` calls for `a`, merge into a single call | help: Merge `isinstance` calls for `a` | -6 | - - if isinstance(a, int) or isinstance(a, float) or isinstance(b, bool): # SIM101 +7 - if isinstance(a, int) or isinstance(a, float) or isinstance(b, bool): # SIM101 7 + if isinstance(a, (int, float)) or isinstance(b, bool): # SIM101 -8 | pass | note: This is an unsafe fix and may change runtime behavior @@ -63,10 +58,8 @@ SIM101 [*] Multiple `isinstance` calls for `a`, merge into a single call | help: Merge `isinstance` calls for `a` | -9 | - - if isinstance(b, bool) or isinstance(a, int) or isinstance(a, float): # SIM101 +10 - if isinstance(b, bool) or isinstance(a, int) or isinstance(a, float): # SIM101 10 + if isinstance(b, bool) or isinstance(a, (int, float)): # SIM101 -11 | pass | note: This is an unsafe fix and may change runtime behavior @@ -81,10 +74,8 @@ SIM101 [*] Multiple `isinstance` calls for `a`, merge into a single call | help: Merge `isinstance` calls for `a` | -15 | - - if (isinstance(a, int) or isinstance(a, float)) and isinstance(b, bool): # SIM101 +16 - if (isinstance(a, int) or isinstance(a, float)) and isinstance(b, bool): # SIM101 16 + if (isinstance(a, (int, float))) and isinstance(b, bool): # SIM101 -17 | pass | note: This is an unsafe fix and may change runtime behavior @@ -99,10 +90,8 @@ SIM101 [*] Multiple `isinstance` calls for expression, merge into a single call | help: Merge `isinstance` calls | -18 | - - if isinstance(a.b, int) or isinstance(a.b, float): # SIM101 +19 - if isinstance(a.b, int) or isinstance(a.b, float): # SIM101 19 + if isinstance(a.b, (int, float)): # SIM101 -20 | pass | note: This is an unsafe fix and may change runtime behavior @@ -128,10 +117,8 @@ SIM101 [*] Multiple `isinstance` calls for `a`, merge into a single call | help: Merge `isinstance` calls for `a` | -37 | - - if x or isinstance(a, int) or isinstance(a, float): +38 - if x or isinstance(a, int) or isinstance(a, float): 38 + if x or isinstance(a, (int, float)): -39 | pass | note: This is an unsafe fix and may change runtime behavior @@ -146,10 +133,8 @@ SIM101 [*] Multiple `isinstance` calls for `a`, merge into a single call | help: Merge `isinstance` calls for `a` | -40 | - - if x or y or isinstance(a, int) or isinstance(a, float) or z: +41 - if x or y or isinstance(a, int) or isinstance(a, float) or z: 41 + if x or y or isinstance(a, (int, float)) or z: -42 | pass | note: This is an unsafe fix and may change runtime behavior @@ -163,10 +148,8 @@ SIM101 [*] Multiple `isinstance` calls for `a`, merge into a single call | help: Merge `isinstance` calls for `a` | -52 | # Regression test for: https://github.com/astral-sh/ruff/issues/7455#issuecomment-1722460483 - - if(isinstance(a, int)) or (isinstance(a, float)): +53 - if(isinstance(a, int)) or (isinstance(a, float)): 53 + if isinstance(a, (int, float)): -54 | pass | note: This is an unsafe fix and may change runtime behavior @@ -182,10 +165,8 @@ SIM101 [*] Multiple `isinstance` calls for expression, merge into a single call | help: Merge `isinstance` calls | -59 | # whose interpolations include lambdas. - - isinstance(f"{(lambda: 0)}", int) or isinstance(f"{(lambda: 0)}", str) +60 - isinstance(f"{(lambda: 0)}", int) or isinstance(f"{(lambda: 0)}", str) 60 + isinstance(f"{(lambda: 0)}", (int, str)) -61 | isinstance(f"{0:{(lambda: 0)}}", int) or isinstance(f"{0:{(lambda: 0)}}", str) | note: This is an unsafe fix and may change runtime behavior @@ -201,10 +182,8 @@ SIM101 [*] Multiple `isinstance` calls for expression, merge into a single call | help: Merge `isinstance` calls | -60 | isinstance(f"{(lambda: 0)}", int) or isinstance(f"{(lambda: 0)}", str) - - isinstance(f"{0:{(lambda: 0)}}", int) or isinstance(f"{0:{(lambda: 0)}}", str) +61 - isinstance(f"{0:{(lambda: 0)}}", int) or isinstance(f"{0:{(lambda: 0)}}", str) 61 + isinstance(f"{0:{(lambda: 0)}}", (int, str)) -62 | isinstance(f"{0:\x22}", int) or isinstance(f"{0:\x22}", str) | note: This is an unsafe fix and may change runtime behavior @@ -219,10 +198,8 @@ SIM101 [*] Multiple `isinstance` calls for expression, merge into a single call | help: Merge `isinstance` calls | -61 | isinstance(f"{0:{(lambda: 0)}}", int) or isinstance(f"{0:{(lambda: 0)}}", str) - - isinstance(f"{0:\x22}", int) or isinstance(f"{0:\x22}", str) +62 - isinstance(f"{0:\x22}", int) or isinstance(f"{0:\x22}", str) 62 + isinstance(f"{0:\x22}", (int, str)) -63 | isinstance(f"{0:\x7b}", int) or isinstance(f"{0:\x7b}", str) | note: This is an unsafe fix and may change runtime behavior @@ -238,10 +215,8 @@ SIM101 [*] Multiple `isinstance` calls for expression, merge into a single call | help: Merge `isinstance` calls | -62 | isinstance(f"{0:\x22}", int) or isinstance(f"{0:\x22}", str) - - isinstance(f"{0:\x7b}", int) or isinstance(f"{0:\x7b}", str) +63 - isinstance(f"{0:\x7b}", int) or isinstance(f"{0:\x7b}", str) 63 + isinstance(f"{0:\x7b}", (int, str)) -64 | | note: This is an unsafe fix and may change runtime behavior @@ -257,10 +232,8 @@ SIM101 [*] Multiple `isinstance` calls for `x`, merge into a single call | help: Merge `isinstance` calls for `x` | -66 | types = (int,) - - isinstance(x, (*types,)) or isinstance(x, ()) +67 - isinstance(x, (*types,)) or isinstance(x, ()) 67 + isinstance(x, (*types,)) -68 | isinstance(x, (*types,)) or isinstance(x, (*types,)) | note: This is an unsafe fix and may change runtime behavior @@ -276,10 +249,8 @@ SIM101 [*] Multiple `isinstance` calls for `x`, merge into a single call | help: Merge `isinstance` calls for `x` | -67 | isinstance(x, (*types,)) or isinstance(x, ()) - - isinstance(x, (*types,)) or isinstance(x, (*types,)) +68 - isinstance(x, (*types,)) or isinstance(x, (*types,)) 68 + isinstance(x, (*types, *types)) -69 | isinstance(x, ()) or isinstance(x, int) | note: This is an unsafe fix and may change runtime behavior @@ -295,10 +266,8 @@ SIM101 [*] Multiple `isinstance` calls for `x`, merge into a single call | help: Merge `isinstance` calls for `x` | -68 | isinstance(x, (*types,)) or isinstance(x, (*types,)) - - isinstance(x, ()) or isinstance(x, int) +69 - isinstance(x, ()) or isinstance(x, int) 69 + isinstance(x, (int)) -70 | isinstance(x, ()) or isinstance(x, ()) | note: This is an unsafe fix and may change runtime behavior @@ -314,10 +283,8 @@ SIM101 [*] Multiple `isinstance` calls for `x`, merge into a single call | help: Merge `isinstance` calls for `x` | -69 | isinstance(x, ()) or isinstance(x, int) - - isinstance(x, ()) or isinstance(x, ()) +70 - isinstance(x, ()) or isinstance(x, ()) 70 + isinstance(x, ()) -71 | ((isinstance(x, int)) or isinstance(x, str)) | note: This is an unsafe fix and may change runtime behavior @@ -332,10 +299,8 @@ SIM101 [*] Multiple `isinstance` calls for `x`, merge into a single call | help: Merge `isinstance` calls for `x` | -70 | isinstance(x, ()) or isinstance(x, ()) - - ((isinstance(x, int)) or isinstance(x, str)) +71 - ((isinstance(x, int)) or isinstance(x, str)) 71 + (isinstance(x, (int, str))) -72 | isinstance(x, int) or (isinstance(x, str)) | note: This is an unsafe fix and may change runtime behavior @@ -348,8 +313,7 @@ SIM101 [*] Multiple `isinstance` calls for `x`, merge into a single call | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Merge `isinstance` calls for `x` | -71 | ((isinstance(x, int)) or isinstance(x, str)) - - isinstance(x, int) or (isinstance(x, str)) +72 - isinstance(x, int) or (isinstance(x, str)) 72 + isinstance(x, (int, str)) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM102_SIM102.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM102_SIM102.py.snap index b00195308333c..2f1e22b7a68ec 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM102_SIM102.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM102_SIM102.py.snap @@ -12,13 +12,8 @@ SIM102 [*] Use a single `if` statement instead of nested `if` statements | help: Combine `if` statements using `and` | -1 | # SIM102 - - if a: - - if b: - - c 2 + if a and b: 3 + c -4 | | note: This is an unsafe fix and may change runtime behavior @@ -33,17 +28,11 @@ SIM102 [*] Use a single `if` statement instead of nested `if` statements 10 | d | help: Combine `if` statements using `and` - | -6 | # SIM102 - - if a: - - if b: - - if c: - - d -7 + if a and b: -8 + if c: -9 + d -10 | - | + | +7 + if a and b: +8 + if c: +9 + d + | note: This is an unsafe fix and may change runtime behavior SIM102 [*] Use a single `if` statement instead of nested `if` statements @@ -57,15 +46,10 @@ SIM102 [*] Use a single `if` statement instead of nested `if` statements 10 | d | help: Combine `if` statements using `and` - | -7 | if a: - - if b: - - if c: - - d -8 + if b and c: -9 + d -10 | - | + | +8 + if b and c: +9 + d + | note: This is an unsafe fix and may change runtime behavior SIM102 [*] Use a single `if` statement instead of nested `if` statements @@ -80,13 +64,8 @@ SIM102 [*] Use a single `if` statement instead of nested `if` statements | help: Combine `if` statements using `and` | -14 | pass - - elif b: - - if c: - - d 15 + elif b and c: 16 + d -17 | | note: This is an unsafe fix and may change runtime behavior @@ -114,15 +93,9 @@ SIM102 [*] Use a single `if` statement instead of nested `if` statements | help: Combine `if` statements using `and` | -25 | # SIM102 - - if a: - - if b: - - # Fixable due to placement of this comment. - - c 26 + if a and b: 27 + # Fixable due to placement of this comment. 28 + c -29 | | note: This is an unsafe fix and may change runtime behavior @@ -139,25 +112,18 @@ SIM102 [*] Use a single `if` statement instead of nested `if` statements | help: Combine `if` statements using `and` | -50 | # SIM102 - - if y > 0: - - if z > 0: - - """this 51 + if y > 0 and z > 0: 52 + """this -53 | is valid""" -54 | - - """the indentation on +53 + is valid""" +54 + 55 + """the indentation on -56 | this line is significant""" -57 | - - "this is" \ +56 + this line is significant""" +57 + 58 + "this is" \ -59 | "allowed too" -60 | - - ("so is" +59 + "allowed too" +60 + 61 + ("so is" -62 | "this for some reason") +62 + "this for some reason") | note: This is an unsafe fix and may change runtime behavior @@ -173,25 +139,18 @@ SIM102 [*] Use a single `if` statement instead of nested `if` statements | help: Combine `if` statements using `and` | -66 | # SIM102 - - if x > 0: - - if y > 0: - - """this 67 + if x > 0 and y > 0: 68 + """this -69 | is valid""" -70 | - - """the indentation on +69 + is valid""" +70 + 71 + """the indentation on -72 | this line is significant""" -73 | - - "this is" \ +72 + this line is significant""" +73 + 74 + "this is" \ -75 | "allowed too" -76 | - - ("so is" +75 + "allowed too" +76 + 77 + ("so is" -78 | "this for some reason") +78 + "this for some reason") | note: This is an unsafe fix and may change runtime behavior @@ -209,17 +168,10 @@ SIM102 [*] Use a single `if` statement instead of nested `if` statements | help: Combine `if` statements using `and` | -82 | # SIM102 - - if node.module: - - if node.module == "multiprocessing" or node.module.startswith( - - "multiprocessing." - - ): - - print("Bad module!") 83 + if node.module and (node.module == "multiprocessing" or node.module.startswith( 84 + "multiprocessing." 85 + )): 86 + print("Bad module!") -87 | | note: This is an unsafe fix and may change runtime behavior @@ -236,17 +188,10 @@ SIM102 [*] Use a single `if` statement instead of nested `if` statements | help: Combine `if` statements using `and` | -89 | # SIM102 (auto-fixable) - - if node.module012345678: - - if node.module == "multiprocß9💣2ℝ" or node.module.startswith( - - "multiprocessing." - - ): - - print("Bad module!") -90 + if node.module012345678 and (node.module == "multiprocß9💣2ℝ" or node.module.startswith( +90 ~ if node.module012345678 and (node.module == "multiprocß9💣2ℝ" or node.module.startswith( 91 + "multiprocessing." 92 + )): 93 + print("Bad module!") -94 | | note: This is an unsafe fix and may change runtime behavior @@ -276,13 +221,8 @@ SIM102 [*] Use a single `if` statement instead of nested `if` statements | help: Combine `if` statements using `and` | -105 | if a: - - if b: - - if c: - - print("if") 106 + if b and c: 107 + print("if") -108 | elif d: | note: This is an unsafe fix and may change runtime behavior @@ -299,13 +239,8 @@ SIM102 [*] Use a single `if` statement instead of nested `if` statements | help: Combine `if` statements using `and` | -131 | # SIM 102 - - if b: - - if c: - - print("foo") 132 + if b and c: 133 + print("foo") -134 | else: | note: This is an unsafe fix and may change runtime behavior @@ -321,10 +256,6 @@ SIM102 [*] Use a single `if` statement instead of nested `if` statements | help: Combine `if` statements using `and` | -164 | pass - - elif b: - - if c: - - d 165 + elif b and c: 166 + d | diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM103_SIM103.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM103_SIM103.py.snap index 5ef3e5bca6b1d..8b0bfca33ecc5 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM103_SIM103.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM103_SIM103.py.snap @@ -13,13 +13,11 @@ SIM103 [*] Return the condition `bool(a)` directly | |____________________^ help: Replace with `return bool(a)` | -2 | # SIM103 - - if a: - - return True - - else: - - return False +3 - if a: +4 - return True +5 - else: +6 - return False 3 + return bool(a) -4 | | note: This is an unsafe fix and may change runtime behavior @@ -35,13 +33,11 @@ SIM103 [*] Return the condition `a == b` directly | |____________________^ help: Replace with `return a == b` | -10 | # SIM103 - - if a == b: - - return True - - else: - - return False +11 - if a == b: +12 - return True +13 - else: +14 - return False 11 + return a == b -12 | | note: This is an unsafe fix and may change runtime behavior @@ -57,13 +53,11 @@ SIM103 [*] Return the condition `bool(b)` directly | |____________________^ help: Replace with `return bool(b)` | -20 | return 1 - - elif b: - - return True - - else: - - return False +21 - elif b: +22 - return True +23 - else: +24 - return False 21 + return bool(b) -22 | | note: This is an unsafe fix and may change runtime behavior @@ -79,13 +73,11 @@ SIM103 [*] Return the condition `bool(b)` directly | |________________________^ help: Replace with `return bool(b)` | -31 | else: - - if b: - - return True - - else: - - return False +32 - if b: +33 - return True +34 - else: +35 - return False 32 + return bool(b) -33 | | note: This is an unsafe fix and may change runtime behavior @@ -101,13 +93,11 @@ SIM103 [*] Return the condition `not a` directly | |___________________^ help: Replace with `return not a` | -56 | # SIM103 - - if a: - - return False - - else: - - return True +57 - if a: +58 - return False +59 - else: +60 - return True 57 + return not a -58 | | note: This is an unsafe fix and may change runtime behavior @@ -135,13 +125,11 @@ SIM103 [*] Return the condition `not (keys is not None and notice.key not in key | |___________________^ help: Replace with `return not (keys is not None and notice.key not in keys)` | -90 | # SIM103 - - if keys is not None and notice.key not in keys: - - return False - - else: - - return True +91 - if keys is not None and notice.key not in keys: +92 - return False +93 - else: +94 - return True 91 + return not (keys is not None and notice.key not in keys) -92 | | note: This is an unsafe fix and may change runtime behavior @@ -156,12 +144,10 @@ SIM103 [*] Return the condition `bool(a)` directly | |________________^ help: Replace with `return bool(a)` | -103 | # SIM103 - - if a: - - return True - - return False +104 - if a: +105 - return True +106 - return False 104 + return bool(a) -105 | | note: This is an unsafe fix and may change runtime behavior @@ -176,12 +162,10 @@ SIM103 [*] Return the condition `not a` directly | |_______________^ help: Replace with `return not a` | -110 | # SIM103 - - if a: - - return False - - return True +111 - if a: +112 - return False +113 - return True 111 + return not a -112 | | note: This is an unsafe fix and may change runtime behavior @@ -195,12 +179,10 @@ SIM103 [*] Return the condition `10 < a` directly | |_______________^ help: Replace with `return 10 < a` | -116 | def f(): - - if not 10 < a: - - return False - - return True +117 - if not 10 < a: +118 - return False +119 - return True 117 + return 10 < a -118 | | note: This is an unsafe fix and may change runtime behavior @@ -214,12 +196,10 @@ SIM103 [*] Return the condition `not 10 < a` directly | |_______________^ help: Replace with `return not 10 < a` | -122 | def f(): - - if 10 < a: - - return False - - return True +123 - if 10 < a: +124 - return False +125 - return True 123 + return not 10 < a -124 | | note: This is an unsafe fix and may change runtime behavior @@ -233,12 +213,10 @@ SIM103 [*] Return the condition `10 not in a` directly | |_______________^ help: Replace with `return 10 not in a` | -128 | def f(): - - if 10 in a: - - return False - - return True +129 - if 10 in a: +130 - return False +131 - return True 129 + return 10 not in a -130 | | note: This is an unsafe fix and may change runtime behavior @@ -252,12 +230,10 @@ SIM103 [*] Return the condition `10 in a` directly | |_______________^ help: Replace with `return 10 in a` | -134 | def f(): - - if 10 not in a: - - return False - - return True +135 - if 10 not in a: +136 - return False +137 - return True 135 + return 10 in a -136 | | note: This is an unsafe fix and may change runtime behavior @@ -271,12 +247,10 @@ SIM103 [*] Return the condition `a is not 10` directly | |_______________^ help: Replace with `return a is not 10` | -140 | def f(): - - if a is 10: - - return False - - return True +141 - if a is 10: +142 - return False +143 - return True 141 + return a is not 10 -142 | | note: This is an unsafe fix and may change runtime behavior @@ -290,12 +264,10 @@ SIM103 [*] Return the condition `a is 10` directly | |_______________^ help: Replace with `return a is 10` | -146 | def f(): - - if a is not 10: - - return False - - return True +147 - if a is not 10: +148 - return False +149 - return True 147 + return a is 10 -148 | | note: This is an unsafe fix and may change runtime behavior @@ -309,12 +281,10 @@ SIM103 [*] Return the condition `a != 10` directly | |_______________^ help: Replace with `return a != 10` | -152 | def f(): - - if a == 10: - - return False - - return True +153 - if a == 10: +154 - return False +155 - return True 153 + return a != 10 -154 | | note: This is an unsafe fix and may change runtime behavior @@ -328,10 +298,9 @@ SIM103 [*] Return the condition `a == 10` directly | |_______________^ help: Replace with `return a == 10` | -158 | def f(): - - if a != 10: - - return False - - return True +159 - if a != 10: +160 - return False +161 - return True 159 + return a == 10 | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM105_SIM105_0.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM105_SIM105_0.py.snap index d4ed691c68c47..cc0af548bdf4b 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM105_SIM105_0.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM105_SIM105_0.py.snap @@ -14,14 +14,10 @@ help: Replace `try`-`except`-`pass` with `with contextlib.suppress(ValueError): | 1 + import contextlib 2 | def foo(): --------------------------------------------------------------------------------- +3 | pass +… 6 | # SIM105 - - try: -7 + with contextlib.suppress(ValueError): -8 | foo() - - except ValueError: - - pass -9 | +7 ~ with contextlib.suppress(ValueError): | note: This is an unsafe fix and may change runtime behavior @@ -39,16 +35,12 @@ SIM105 [*] Use `contextlib.suppress(ValueError, OSError)` instead of `try`-`exce | help: Replace `try`-`except`-`pass` with `with contextlib.suppress(ValueError, OSError): ...` | -1 + import contextlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import contextlib + 2 | def foo(): + 3 | pass + … 13 | # SIM105 - - try: -14 + with contextlib.suppress(ValueError, OSError): -15 | foo() - - except (ValueError, OSError): - - pass -16 | +14 ~ with contextlib.suppress(ValueError, OSError): | note: This is an unsafe fix and may change runtime behavior @@ -66,16 +58,12 @@ SIM105 [*] Use `contextlib.suppress(ValueError, OSError)` instead of `try`-`exce | help: Replace `try`-`except`-`pass` with `with contextlib.suppress(ValueError, OSError): ...` | -1 + import contextlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import contextlib + 2 | def foo(): + 3 | pass + … 19 | # SIM105 - - try: -20 + with contextlib.suppress(ValueError, OSError): -21 | foo() - - except (ValueError, OSError) as e: - - pass -22 | +20 ~ with contextlib.suppress(ValueError, OSError): | note: This is an unsafe fix and may change runtime behavior @@ -93,16 +81,12 @@ SIM105 [*] Use `contextlib.suppress(BaseException)` instead of `try`-`except`-`p | help: Replace `try`-`except`-`pass` with `with contextlib.suppress(BaseException): ...` | -1 + import contextlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import contextlib + 2 | def foo(): + 3 | pass + … 25 | # SIM105 - - try: -26 + with contextlib.suppress(BaseException): -27 | foo() - - except: - - pass -28 | +26 ~ with contextlib.suppress(BaseException): | note: This is an unsafe fix and may change runtime behavior @@ -120,16 +104,12 @@ SIM105 [*] Use `contextlib.suppress(a.Error, b.Error)` instead of `try`-`except` | help: Replace `try`-`except`-`pass` with `with contextlib.suppress(a.Error, b.Error): ...` | -1 + import contextlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import contextlib + 2 | def foo(): + 3 | pass + … 31 | # SIM105 - - try: -32 + with contextlib.suppress(a.Error, b.Error): -33 | foo() - - except (a.Error, b.Error): - - pass -34 | +32 ~ with contextlib.suppress(a.Error, b.Error): | note: This is an unsafe fix and may change runtime behavior @@ -145,16 +125,12 @@ SIM105 [*] Use `contextlib.suppress(ValueError)` instead of `try`-`except`-`pass | |___________^ help: Replace `try`-`except`-`pass` with `with contextlib.suppress(ValueError): ...` | -1 + import contextlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import contextlib + 2 | def foo(): + 3 | pass + … 85 | # OK - - try: -86 + with contextlib.suppress(ValueError): -87 | foo() - - except ValueError: - - ... -88 | +86 ~ with contextlib.suppress(ValueError): | note: This is an unsafe fix and may change runtime behavior @@ -187,16 +163,12 @@ SIM105 [*] Use `contextlib.suppress(OSError)` instead of `try`-`except`-`pass` | help: Replace `try`-`except`-`pass` with `with contextlib.suppress(OSError): ...` | -1 + import contextlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import contextlib + 2 | def foo(): + 3 | pass + … 117 | def write_models(directory, Models): - - try: -118 + with contextlib.suppress(OSError): -119 | os.makedirs(model_dir); - - except OSError: - - pass; -120 | +118 ~ with contextlib.suppress(OSError): | note: This is an unsafe fix and may change runtime behavior @@ -214,15 +186,12 @@ SIM105 [*] Use `contextlib.suppress(OSError)` instead of `try`-`except`-`pass` | help: Replace `try`-`except`-`pass` with `with contextlib.suppress(OSError): ...` | -1 + import contextlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import contextlib + 2 | def foo(): + 3 | pass + … 122 | - - try: os.makedirs(model_dir); - - except OSError: - - pass; -123 + with contextlib.suppress(OSError): os.makedirs(model_dir); -124 | +123 ~ with contextlib.suppress(OSError): os.makedirs(model_dir); | note: This is an unsafe fix and may change runtime behavior @@ -240,15 +209,12 @@ SIM105 [*] Use `contextlib.suppress(OSError)` instead of `try`-`except`-`pass` | help: Replace `try`-`except`-`pass` with `with contextlib.suppress(OSError): ...` | -1 + import contextlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import contextlib + 2 | def foo(): + 3 | pass + … 126 | - - try: os.makedirs(model_dir); - - except OSError: - - pass; \ -127 + with contextlib.suppress(OSError): os.makedirs(model_dir); -128 | \ +127 ~ with contextlib.suppress(OSError): os.makedirs(model_dir); | note: This is an unsafe fix and may change runtime behavior @@ -263,16 +229,12 @@ SIM105 [*] Use `contextlib.suppress()` instead of `try`-`except`-`pass` | |________^ help: Replace `try`-`except`-`pass` with `with contextlib.suppress(): ...` | -1 + import contextlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import contextlib + 2 | def foo(): + 3 | pass + … 133 | # Regression tests for: https://github.com/astral-sh/ruff/issues/18209 - - try: -134 + with contextlib.suppress(): -135 | 1 / 0 - - except (): - - pass -136 | +134 ~ with contextlib.suppress(): | note: This is an unsafe fix and may change runtime behavior @@ -287,14 +249,11 @@ SIM105 [*] Use `contextlib.suppress(BaseException)` instead of `try`-`except`-`p | |________^ help: Replace `try`-`except`-`pass` with `with contextlib.suppress(BaseException): ...` | -1 + import contextlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import contextlib + 2 | def foo(): + 3 | pass + … 140 | BaseException = ValueError - - try: -141 + with contextlib.suppress(BaseException): -142 | int("a") - - except BaseException: - - pass +141 ~ with contextlib.suppress(BaseException): | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM105_SIM105_1.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM105_SIM105_1.py.snap index aad14a968178b..cb0cc18a73a81 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM105_SIM105_1.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM105_SIM105_1.py.snap @@ -12,14 +12,9 @@ SIM105 [*] Use `contextlib.suppress(ValueError)` instead of `try`-`except`-`pass | |________^ help: Replace `try`-`except`-`pass` with `with contextlib.suppress(ValueError): ...` | -2 | import math 3 + import contextlib -4 | +4 + 5 | # SIM105 - - try: -6 + with contextlib.suppress(ValueError): -7 | math.sqrt(-1) - - except ValueError: - - pass +6 ~ with contextlib.suppress(ValueError): | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM105_SIM105_2.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM105_SIM105_2.py.snap index aa96b34644306..dc4326a04c0ca 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM105_SIM105_2.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM105_SIM105_2.py.snap @@ -12,11 +12,10 @@ SIM105 [*] Use `contextlib.suppress(ValueError)` instead of `try`-`except`-`pass | |________^ help: Replace `try`-`except`-`pass` with `with contextlib.suppress(ValueError): ...` | -9 | # SIM105 - - try: -10 + with contextlib.suppress(ValueError): -11 | foo() - - except ValueError: - - pass + 2 ~ import contextlib + 3 | + … + 9 | # SIM105 +10 ~ with contextlib.suppress(ValueError): | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM105_SIM105_4.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM105_SIM105_4.py.snap index 3443d5b709509..5909f7c8a9cb2 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM105_SIM105_4.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM105_SIM105_4.py.snap @@ -11,11 +11,7 @@ SIM105 [*] Use `contextlib.suppress(ImportError)` instead of `try`-`except`-`pas | |___________________________^ help: Replace `try`-`except`-`pass` with `with contextlib.suppress(ImportError): ...` | -1 | #!/usr/bin/env python - - try: 2 + import contextlib -3 + with contextlib.suppress(ImportError): -4 | from __builtin__ import bytes, str, open, super, range, zip, round, int, pow, object, input - - except ImportError: pass +3 ~ with contextlib.suppress(ImportError): | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM108_SIM108.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM108_SIM108.py.snap index d18fbf4152328..87338a8bc5212 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM108_SIM108.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM108_SIM108.py.snap @@ -15,13 +15,11 @@ SIM108 [*] Use ternary operator `b = c if a else d` instead of `if`-`else`-block | help: Replace `if`-`else`-block with `b = c if a else d` | -1 | # SIM108 - - if a: - - b = c - - else: - - b = d +2 - if a: +3 - b = c +4 - else: +5 - b = d 2 + b = c if a else d -3 | | note: This is an unsafe fix and may change runtime behavior @@ -37,13 +35,11 @@ SIM108 [*] Use ternary operator `b = 1 if a else 2` instead of `if`-`else`-block | |_____________^ help: Replace `if`-`else`-block with `b = 1 if a else 2` | -29 | else: - - if a: - - b = 1 - - else: - - b = 2 +30 - if a: +31 - b = 1 +32 - else: +33 - b = 2 30 + b = 1 if a else 2 -31 | | note: This is an unsafe fix and may change runtime behavior @@ -71,13 +67,11 @@ SIM108 [*] Use ternary operator `b = "cccccccccccccccccccccccccccccccccß" if a | |_____________________________________________^ help: Replace `if`-`else`-block with `b = "cccccccccccccccccccccccccccccccccß" if a else "ddddddddddddddddddddddddddddddddd💣"` | -81 | # SIM108 - - if a: - - b = "cccccccccccccccccccccccccccccccccß" - - else: - - b = "ddddddddddddddddddddddddddddddddd💣" +82 - if a: +83 - b = "cccccccccccccccccccccccccccccccccß" +84 - else: +85 - b = "ddddddddddddddddddddddddddddddddd💣" 82 + b = "cccccccccccccccccccccccccccccccccß" if a else "ddddddddddddddddddddddddddddddddd💣" -83 | | note: This is an unsafe fix and may change runtime behavior @@ -127,13 +121,11 @@ SIM108 [*] Use binary operator `z = cond or other_cond` instead of `if`-`else`-b | help: Replace `if`-`else`-block with `z = cond or other_cond` | -140 | # z = cond or other_cond - - if cond: - - z = cond - - else: - - z = other_cond +141 - if cond: +142 - z = cond +143 - else: +144 - z = other_cond 141 + z = cond or other_cond -142 | | note: This is an unsafe fix and may change runtime behavior @@ -152,13 +144,11 @@ SIM108 [*] Use binary operator `z = cond and other_cond` instead of `if`-`else`- | help: Replace `if`-`else`-block with `z = cond and other_cond` | -147 | # z = cond and other_cond - - if not cond: - - z = cond - - else: - - z = other_cond +148 - if not cond: +149 - z = cond +150 - else: +151 - z = other_cond 148 + z = cond and other_cond -149 | | note: This is an unsafe fix and may change runtime behavior @@ -177,13 +167,11 @@ SIM108 [*] Use binary operator `z = not cond and other_cond` instead of `if`-`el | help: Replace `if`-`else`-block with `z = not cond and other_cond` | -154 | # z = not cond and other_cond - - if cond: - - z = not cond - - else: - - z = other_cond +155 - if cond: +156 - z = not cond +157 - else: +158 - z = other_cond 155 + z = not cond and other_cond -156 | | note: This is an unsafe fix and may change runtime behavior @@ -202,13 +190,11 @@ SIM108 [*] Use ternary operator `z = 1 if True else other` instead of `if`-`else | help: Replace `if`-`else`-block with `z = 1 if True else other` | -166 | # should be simplified for other reasons...) - - if True: - - z = 1 - - else: - - z = other +167 - if True: +168 - z = 1 +169 - else: +170 - z = other 167 + z = 1 if True else other -168 | | note: This is an unsafe fix and may change runtime behavior @@ -227,13 +213,11 @@ SIM108 [*] Use ternary operator `z = 1 if False else other` instead of `if`-`els | help: Replace `if`-`else`-block with `z = 1 if False else other` | -171 | - - if False: - - z = 1 - - else: - - z = other +172 - if False: +173 - z = 1 +174 - else: +175 - z = other 172 + z = 1 if False else other -173 | | note: This is an unsafe fix and may change runtime behavior @@ -252,13 +236,11 @@ SIM108 [*] Use ternary operator `z = True if 1 else other` instead of `if`-`else | help: Replace `if`-`else`-block with `z = True if 1 else other` | -176 | - - if 1: - - z = True - - else: - - z = other +177 - if 1: +178 - z = True +179 - else: +180 - z = other 177 + z = True if 1 else other -178 | | note: This is an unsafe fix and may change runtime behavior @@ -277,13 +259,11 @@ SIM108 [*] Use ternary operator `z = foo() if foo() else other` instead of `if`- | help: Replace `if`-`else`-block with `z = foo() if foo() else other` | -184 | # from Two to one. - - if foo(): - - z = foo() - - else: - - z = other +185 - if foo(): +186 - z = foo() +187 - else: +188 - z = other 185 + z = foo() if foo() else other -186 | | note: This is an unsafe fix and may change runtime behavior @@ -299,13 +279,11 @@ SIM108 [*] Use ternary operator `z = not foo() if foo() else other` instead of ` | |_____________^ help: Replace `if`-`else`-block with `z = not foo() if foo() else other` | -192 | # from Two to one. - - if foo(): - - z = not foo() - - else: - - z = other +193 - if foo(): +194 - z = not foo() +195 - else: +196 - z = other 193 + z = not foo() if foo() else other -194 | | note: This is an unsafe fix and may change runtime behavior @@ -324,13 +302,11 @@ SIM108 [*] Use ternary operator `var = "str" if cond else f"{first}-{second}"` i | help: Replace `if`-`else`-block with `var = "str" if cond else f"{first}-{second}"` | -201 | # single quotes - - if cond: - - var = "str" - - else: - - var = f"{first}-{second}" +202 - if cond: +203 - var = "str" +204 - else: +205 - var = f"{first}-{second}" 202 + var = "str" if cond else f"{first}-{second}" -203 | | note: This is an unsafe fix and may change runtime behavior @@ -346,11 +322,10 @@ SIM108 [*] Use ternary operator `var = "str" if cond else f'{first}-{second}'` i | |_____________________________^ help: Replace `if`-`else`-block with `var = "str" if cond else f'{first}-{second}'` | -206 | - - if cond: - - var = "str" - - else: - - var = f'{first}-{second}' +207 - if cond: +208 - var = "str" +209 - else: +210 - var = f'{first}-{second}' 207 + var = "str" if cond else f'{first}-{second}' | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM109_SIM109.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM109_SIM109.py.snap index 85eb6a386912f..af39258971a1a 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM109_SIM109.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM109_SIM109.py.snap @@ -11,10 +11,8 @@ SIM109 [*] Use `a in (b, c)` instead of multiple equality comparisons | help: Replace with `a in (b, c)` | -1 | # SIM109 - - if a == b or a == c: +2 - if a == b or a == c: 2 + if a in (b, c): -3 | d | note: This is an unsafe fix and may change runtime behavior @@ -28,10 +26,8 @@ SIM109 [*] Use `a in (b, c)` instead of multiple equality comparisons | help: Replace with `a in (b, c)` | -5 | # SIM109 - - if (a == b or a == c) and None: +6 - if (a == b or a == c) and None: 6 + if (a in (b, c)) and None: -7 | d | note: This is an unsafe fix and may change runtime behavior @@ -45,10 +41,8 @@ SIM109 [*] Use `a in (b, c)` instead of multiple equality comparisons | help: Replace with `a in (b, c)` | -9 | # SIM109 - - if a == b or a == c or None: +10 - if a == b or a == c or None: 10 + if a in (b, c) or None: -11 | d | note: This is an unsafe fix and may change runtime behavior @@ -62,9 +56,7 @@ SIM109 [*] Use `a in (b, c)` instead of multiple equality comparisons | help: Replace with `a in (b, c)` | -13 | # SIM109 - - if a == b or None or a == c: +14 - if a == b or None or a == c: 14 + if a in (b, c) or None: -15 | d | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM110_SIM110.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM110_SIM110.py.snap index 240553f8cfaa7..e5d2f81ad9133 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM110_SIM110.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM110_SIM110.py.snap @@ -13,13 +13,11 @@ SIM110 [*] Use `return any(check(x) for x in iterable)` instead of `for` loop | |________________^ help: Replace with `return any(check(x) for x in iterable)` | -2 | # SIM110 - - for x in iterable: - - if check(x): - - return True - - return False +3 - for x in iterable: +4 - if check(x): +5 - return True +6 - return False 3 + return any(check(x) for x in iterable) -4 | | note: This is an unsafe fix and may change runtime behavior @@ -35,13 +33,11 @@ SIM110 [*] Use `return all(not check(x) for x in iterable)` instead of `for` loo | |_______________^ help: Replace with `return all(not check(x) for x in iterable)` | -24 | # SIM111 - - for x in iterable: - - if check(x): - - return False - - return True +25 - for x in iterable: +26 - if check(x): +27 - return False +28 - return True 25 + return all(not check(x) for x in iterable) -26 | | note: This is an unsafe fix and may change runtime behavior @@ -57,13 +53,11 @@ SIM110 [*] Use `return all(x.is_empty() for x in iterable)` instead of `for` loo | |_______________^ help: Replace with `return all(x.is_empty() for x in iterable)` | -32 | # SIM111 - - for x in iterable: - - if not x.is_empty(): - - return False - - return True +33 - for x in iterable: +34 - if not x.is_empty(): +35 - return False +36 - return True 33 + return all(x.is_empty() for x in iterable) -34 | | note: This is an unsafe fix and may change runtime behavior @@ -80,14 +74,12 @@ SIM110 [*] Use `return any(check(x) for x in iterable)` instead of `for` loop | |____________________^ help: Replace with `return any(check(x) for x in iterable)` | -54 | # SIM110 - - for x in iterable: - - if check(x): - - return True - - else: - - return False +55 - for x in iterable: +56 - if check(x): +57 - return True +58 - else: +59 - return False 55 + return any(check(x) for x in iterable) -56 | | note: This is an unsafe fix and may change runtime behavior @@ -104,14 +96,12 @@ SIM110 [*] Use `return all(not check(x) for x in iterable)` instead of `for` loo | |___________________^ help: Replace with `return all(not check(x) for x in iterable)` | -63 | # SIM111 - - for x in iterable: - - if check(x): - - return False - - else: - - return True +64 - for x in iterable: +65 - if check(x): +66 - return False +67 - else: +68 - return True 64 + return all(not check(x) for x in iterable) -65 | | note: This is an unsafe fix and may change runtime behavior @@ -130,14 +120,12 @@ SIM110 [*] Use `return any(check(x) for x in iterable)` instead of `for` loop | help: Replace with `return any(check(x) for x in iterable)` | -72 | # SIM110 - - for x in iterable: - - if check(x): - - return True - - else: - - return False +73 - for x in iterable: +74 - if check(x): +75 - return True +76 - else: +77 - return False 73 + return any(check(x) for x in iterable) -74 | return True | note: This is an unsafe fix and may change runtime behavior @@ -156,14 +144,12 @@ SIM110 [*] Use `return all(not check(x) for x in iterable)` instead of `for` loo | help: Replace with `return all(not check(x) for x in iterable)` | -82 | # SIM111 - - for x in iterable: - - if check(x): - - return False - - else: - - return True +83 - for x in iterable: +84 - if check(x): +85 - return False +86 - else: +87 - return True 83 + return all(not check(x) for x in iterable) -84 | return False | note: This is an unsafe fix and may change runtime behavior @@ -202,13 +188,11 @@ SIM110 [*] Use `return any(check(x) for x in iterable)` instead of `for` loop | |________________^ help: Replace with `return any(check(x) for x in iterable)` | -143 | # SIM110 - - for x in iterable: - - if check(x): - - return True - - return False +144 - for x in iterable: +145 - if check(x): +146 - return True +147 - return False 144 + return any(check(x) for x in iterable) -145 | | note: This is an unsafe fix and may change runtime behavior @@ -223,13 +207,11 @@ SIM110 [*] Use `return all(not check(x) for x in iterable)` instead of `for` loo | |_______________^ help: Replace with `return all(not check(x) for x in iterable)` | -153 | # SIM111 - - for x in iterable: - - if check(x): - - return False - - return True +154 - for x in iterable: +155 - if check(x): +156 - return False +157 - return True 154 + return all(not check(x) for x in iterable) -155 | | note: This is an unsafe fix and may change runtime behavior @@ -245,13 +227,11 @@ SIM110 [*] Use `return any(x.isdigit() for x in "012ß9💣2ℝ9012ß9💣2ℝ90 | |________________^ help: Replace with `return any(x.isdigit() for x in "012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ")` | -161 | # SIM110 - - for x in "012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ": - - if x.isdigit(): - - return True - - return False +162 - for x in "012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ": +163 - if x.isdigit(): +164 - return True +165 - return False 162 + return any(x.isdigit() for x in "012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ") -163 | | note: This is an unsafe fix and may change runtime behavior @@ -270,13 +250,11 @@ SIM110 [*] Use `return any(check(x) for x in iterable)` instead of `for` loop | help: Replace with `return any(check(x) for x in iterable)` | -183 | # SIM110 - - for x in iterable: - - if check(x): - - return True - - return False +184 - for x in iterable: +185 - if check(x): +186 - return True +187 - return False 184 + return any(check(x) for x in iterable) -185 | | note: This is an unsafe fix and may change runtime behavior @@ -295,12 +273,10 @@ SIM110 [*] Use `return any(check(x) for x in await iterable)` instead of `for` l | help: Replace with `return any(check(x) for x in await iterable)` | -190 | # SIM110 - - for x in await iterable: - - if check(x): - - return True - - return False +191 - for x in await iterable: +192 - if check(x): +193 - return True +194 - return False 191 + return any(check(x) for x in await iterable) -192 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM110_SIM111.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM110_SIM111.py.snap index d4093cc4edf72..27c7187389d3a 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM110_SIM111.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM110_SIM111.py.snap @@ -13,13 +13,11 @@ SIM110 [*] Use `return any(check(x) for x in iterable)` instead of `for` loop | |________________^ help: Replace with `return any(check(x) for x in iterable)` | -2 | # SIM110 - - for x in iterable: - - if check(x): - - return True - - return False +3 - for x in iterable: +4 - if check(x): +5 - return True +6 - return False 3 + return any(check(x) for x in iterable) -4 | | note: This is an unsafe fix and may change runtime behavior @@ -35,13 +33,11 @@ SIM110 [*] Use `return all(not check(x) for x in iterable)` instead of `for` loo | |_______________^ help: Replace with `return all(not check(x) for x in iterable)` | -24 | # SIM111 - - for x in iterable: - - if check(x): - - return False - - return True +25 - for x in iterable: +26 - if check(x): +27 - return False +28 - return True 25 + return all(not check(x) for x in iterable) -26 | | note: This is an unsafe fix and may change runtime behavior @@ -57,13 +53,11 @@ SIM110 [*] Use `return all(x.is_empty() for x in iterable)` instead of `for` loo | |_______________^ help: Replace with `return all(x.is_empty() for x in iterable)` | -32 | # SIM111 - - for x in iterable: - - if not x.is_empty(): - - return False - - return True +33 - for x in iterable: +34 - if not x.is_empty(): +35 - return False +36 - return True 33 + return all(x.is_empty() for x in iterable) -34 | | note: This is an unsafe fix and may change runtime behavior @@ -80,14 +74,12 @@ SIM110 [*] Use `return any(check(x) for x in iterable)` instead of `for` loop | |____________________^ help: Replace with `return any(check(x) for x in iterable)` | -54 | # SIM110 - - for x in iterable: - - if check(x): - - return True - - else: - - return False +55 - for x in iterable: +56 - if check(x): +57 - return True +58 - else: +59 - return False 55 + return any(check(x) for x in iterable) -56 | | note: This is an unsafe fix and may change runtime behavior @@ -104,14 +96,12 @@ SIM110 [*] Use `return all(not check(x) for x in iterable)` instead of `for` loo | |___________________^ help: Replace with `return all(not check(x) for x in iterable)` | -63 | # SIM111 - - for x in iterable: - - if check(x): - - return False - - else: - - return True +64 - for x in iterable: +65 - if check(x): +66 - return False +67 - else: +68 - return True 64 + return all(not check(x) for x in iterable) -65 | | note: This is an unsafe fix and may change runtime behavior @@ -130,14 +120,12 @@ SIM110 [*] Use `return any(check(x) for x in iterable)` instead of `for` loop | help: Replace with `return any(check(x) for x in iterable)` | -72 | # SIM110 - - for x in iterable: - - if check(x): - - return True - - else: - - return False +73 - for x in iterable: +74 - if check(x): +75 - return True +76 - else: +77 - return False 73 + return any(check(x) for x in iterable) -74 | return True | note: This is an unsafe fix and may change runtime behavior @@ -156,14 +144,12 @@ SIM110 [*] Use `return all(not check(x) for x in iterable)` instead of `for` loo | help: Replace with `return all(not check(x) for x in iterable)` | -82 | # SIM111 - - for x in iterable: - - if check(x): - - return False - - else: - - return True +83 - for x in iterable: +84 - if check(x): +85 - return False +86 - else: +87 - return True 83 + return all(not check(x) for x in iterable) -84 | return False | note: This is an unsafe fix and may change runtime behavior @@ -202,13 +188,11 @@ SIM110 [*] Use `return any(check(x) for x in iterable)` instead of `for` loop | |________________^ help: Replace with `return any(check(x) for x in iterable)` | -143 | # SIM110 - - for x in iterable: - - if check(x): - - return True - - return False +144 - for x in iterable: +145 - if check(x): +146 - return True +147 - return False 144 + return any(check(x) for x in iterable) -145 | | note: This is an unsafe fix and may change runtime behavior @@ -223,13 +207,11 @@ SIM110 [*] Use `return all(not check(x) for x in iterable)` instead of `for` loo | |_______________^ help: Replace with `return all(not check(x) for x in iterable)` | -153 | # SIM111 - - for x in iterable: - - if check(x): - - return False - - return True +154 - for x in iterable: +155 - if check(x): +156 - return False +157 - return True 154 + return all(not check(x) for x in iterable) -155 | | note: This is an unsafe fix and may change runtime behavior @@ -245,13 +227,11 @@ SIM110 [*] Use `return all(x in y for x in iterable)` instead of `for` loop | |_______________^ help: Replace with `return all(x in y for x in iterable)` | -161 | # SIM111 - - for x in iterable: - - if x not in y: - - return False - - return True +162 - for x in iterable: +163 - if x not in y: +164 - return False +165 - return True 162 + return all(x in y for x in iterable) -163 | | note: This is an unsafe fix and may change runtime behavior @@ -267,13 +247,11 @@ SIM110 [*] Use `return all(x <= y for x in iterable)` instead of `for` loop | |_______________^ help: Replace with `return all(x <= y for x in iterable)` | -169 | # SIM111 - - for x in iterable: - - if x > y: - - return False - - return True +170 - for x in iterable: +171 - if x > y: +172 - return False +173 - return True 170 + return all(x <= y for x in iterable) -171 | | note: This is an unsafe fix and may change runtime behavior @@ -289,12 +267,10 @@ SIM110 [*] Use `return all(not x.isdigit() for x in "012ß9💣2ℝ9012ß9💣2 | |_______________^ help: Replace with `return all(not x.isdigit() for x in "012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9")` | -177 | # SIM111 - - for x in "012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9": - - if x.isdigit(): - - return False - - return True +178 - for x in "012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9": +179 - if x.isdigit(): +180 - return False +181 - return True 178 + return all(not x.isdigit() for x in "012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9") -179 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM112_SIM112.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM112_SIM112.py.snap index 0f1692581a26e..49d5d9d21e57b 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM112_SIM112.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM112_SIM112.py.snap @@ -12,10 +12,8 @@ SIM112 [*] Use capitalized environment variable `FOO` instead of `foo` | help: Replace `foo` with `FOO` | -3 | # Bad - - os.environ['foo'] +4 - os.environ['foo'] 4 + os.environ['FOO'] -5 | | note: This is an unsafe fix and may change runtime behavior @@ -79,10 +77,8 @@ SIM112 [*] Use capitalized environment variable `FOO` instead of `foo` | help: Replace `foo` with `FOO` | -13 | - - env = os.environ['foo'] +14 - env = os.environ['foo'] 14 + env = os.environ['FOO'] -15 | | note: This is an unsafe fix and may change runtime behavior @@ -108,9 +104,7 @@ SIM112 [*] Use capitalized environment variable `FOO` instead of `foo` | help: Replace `foo` with `FOO` | -18 | - - if env := os.environ['foo']: +19 - if env := os.environ['foo']: 19 + if env := os.environ['FOO']: -20 | pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM114_SIM114.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM114_SIM114.py.snap index 73bd00c13417c..ba13cc52e46e5 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM114_SIM114.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM114_SIM114.py.snap @@ -15,12 +15,7 @@ SIM114 [*] Combine `if` branches using logical `or` operator | help: Combine `if` branches | -1 | # Errors - - if a: - - b - - elif c: -2 + if a or c: -3 | b +2 ~ if a or c: | SIM114 [*] Combine `if` branches using logical `or` operator @@ -38,12 +33,7 @@ SIM114 [*] Combine `if` branches using logical `or` operator | help: Combine `if` branches | -6 | - - if a: # we preserve comments, too! - - b - - elif c: # but not on the second branch -7 + if a or c: # we preserve comments, too! -8 | b +7 ~ if a or c: # we preserve comments, too! | SIM114 [*] Combine `if` branches using logical `or` operator @@ -63,13 +53,7 @@ SIM114 [*] Combine `if` branches using logical `or` operator | help: Combine `if` branches | -11 | - - if x == 1: - - for _ in range(20): - - print("hello") - - elif x == 2: -12 + if x == 1 or x == 2: -13 | for _ in range(20): +12 ~ if x == 1 or x == 2: | SIM114 [*] Combine `if` branches using logical `or` operator @@ -91,14 +75,7 @@ SIM114 [*] Combine `if` branches using logical `or` operator | help: Combine `if` branches | -18 | - - if x == 1: - - if True: - - for _ in range(20): - - print("hello") - - elif x == 2: -19 + if x == 1 or x == 2: -20 | if True: +19 ~ if x == 1 or x == 2: | SIM114 [*] Combine `if` branches using logical `or` operator @@ -126,17 +103,7 @@ SIM114 [*] Combine `if` branches using logical `or` operator | help: Combine `if` branches | -27 | - - if x == 1: - - if True: - - for _ in range(20): - - print("hello") - - elif False: - - for _ in range(20): - - print("hello") - - elif x == 2: -28 + if x == 1 or x == 2: -29 | if True: +28 ~ if x == 1 or x == 2: | SIM114 [*] Combine `if` branches using logical `or` operator @@ -155,13 +122,7 @@ SIM114 [*] Combine `if` branches using logical `or` operator | help: Combine `if` branches | -28 | if x == 1: - - if True: - - for _ in range(20): - - print("hello") - - elif False: -29 + if True or False: -30 | for _ in range(20): +29 ~ if True or False: | SIM114 [*] Combine `if` branches using logical `or` operator @@ -181,13 +142,7 @@ SIM114 [*] Combine `if` branches using logical `or` operator | help: Combine `if` branches | -35 | elif x == 2: - - if True: - - for _ in range(20): - - print("hello") - - elif False: -36 + if True or False: -37 | for _ in range(20): +36 ~ if True or False: | SIM114 [*] Combine `if` branches using logical `or` operator @@ -220,12 +175,7 @@ SIM114 [*] Combine `if` branches using logical `or` operator | help: Combine `if` branches | -57 | and k == 14 - - ): - - pass - - elif 1 == 2: -58 + ) or 1 == 2: -59 | pass +58 ~ ) or 1 == 2: | SIM114 [*] Combine `if` branches using logical `or` operator @@ -243,12 +193,7 @@ SIM114 [*] Combine `if` branches using logical `or` operator | help: Combine `if` branches | -66 | skipped = 1 - - elif result.eofs == "F": - - errors = 1 - - elif result.eofs == "E": -67 + elif result.eofs == "F" or result.eofs == "E": -68 | errors = 1 +67 ~ elif result.eofs == "F" or result.eofs == "E": | SIM114 [*] Combine `if` branches using logical `or` operator @@ -266,12 +211,7 @@ SIM114 [*] Combine `if` branches using logical `or` operator | help: Combine `if` branches | -68 | errors = 1 - - elif result.eofs == "E": - - errors = 1 - - elif result.eofs == "X": -69 + elif result.eofs == "E" or result.eofs == "X": -70 | errors = 1 +69 ~ elif result.eofs == "E" or result.eofs == "X": | SIM114 [*] Combine `if` branches using logical `or` operator @@ -286,12 +226,7 @@ SIM114 [*] Combine `if` branches using logical `or` operator | |______________^ help: Combine `if` branches | -70 | errors = 1 - - elif result.eofs == "X": - - errors = 1 - - elif result.eofs == "C": -71 + elif result.eofs == "X" or result.eofs == "C": -72 | errors = 1 +71 ~ elif result.eofs == "X" or result.eofs == "C": | SIM114 [*] Combine `if` branches using logical `or` operator @@ -309,12 +244,7 @@ SIM114 [*] Combine `if` branches using logical `or` operator | help: Combine `if` branches | -117 | b = False - - if a > b: # end-of-line - - return 3 - - elif a == b: -118 + if a > b or a == b: # end-of-line -119 | return 3 +118 ~ if a > b or a == b: # end-of-line | SIM114 [*] Combine `if` branches using logical `or` operator @@ -329,12 +259,7 @@ SIM114 [*] Combine `if` branches using logical `or` operator | |________________^ help: Combine `if` branches | -121 | return 3 - - elif a < b: # end-of-line - - return 4 - - elif b is None: -122 + elif a < b or b is None: # end-of-line -123 | return 4 +122 ~ elif a < b or b is None: # end-of-line | SIM114 [*] Combine `if` branches using logical `or` operator @@ -349,12 +274,7 @@ SIM114 [*] Combine `if` branches using logical `or` operator | |________________^ help: Combine `if` branches | -131 | b = False - - if a > b: # end-of-line - - return 3 - - elif a := 1: -132 + if a > b or (a := 1): # end-of-line -133 | return 3 +132 ~ if a > b or (a := 1): # end-of-line | SIM114 [*] Combine `if` branches using logical `or` operator @@ -367,12 +287,7 @@ SIM114 [*] Combine `if` branches using logical `or` operator | |_____^ help: Combine `if` branches | -137 | - - if a: # we preserve comments, too! - - b - - elif c: # but not on the second branch -138 + if a or c: # we preserve comments, too! -139 | b +138 ~ if a or c: # we preserve comments, too! | SIM114 [*] Combine `if` branches using logical `or` operator @@ -383,11 +298,10 @@ SIM114 [*] Combine `if` branches using logical `or` operator | |_________^ help: Combine `if` branches | -143 | - - if a: b # here's a comment - - elif c: b +144 - if a: b # here's a comment +145 - elif c: b +146 - 144 + if a or c: b # here's a comment -145 | | SIM114 [*] Combine `if` branches using logical `or` operator @@ -399,12 +313,11 @@ SIM114 [*] Combine `if` branches using logical `or` operator | |________^ help: Combine `if` branches | -147 | - - if(x > 200): pass - - elif(100 < x and x < 200 and 300 < y and y < 800): - - pass +148 - if(x > 200): pass +149 - elif(100 < x and x < 200 and 300 < y and y < 800): +150 - pass +151 - 148 + if(x > 200) or (100 < x and x < 200 and 300 < y and y < 800): pass -149 | | SIM114 [*] Combine `if` branches using logical `or` operator @@ -421,10 +334,5 @@ SIM114 [*] Combine `if` branches using logical `or` operator | help: Combine `if` branches | -153 | # See: https://github.com/astral-sh/ruff/issues/12732 - - if False if True else False: - - print(1) - - elif True: -154 + if (False if True else False) or True: -155 | print(1) +154 ~ if (False if True else False) or True: | diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM117_SIM117.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM117_SIM117.py.snap index 20cad3e67fa30..88cc11adeab64 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM117_SIM117.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM117_SIM117.py.snap @@ -12,13 +12,8 @@ SIM117 [*] Use a single `with` statement with multiple contexts instead of neste | help: Combine `with` statements | -1 | # SIM117 - - with A() as a: - - with B() as b: - - print("hello") 2 + with A() as a, B() as b: 3 + print("hello") -4 | | SIM117 [*] Use a single `with` statement with multiple contexts instead of nested `with` statements @@ -32,17 +27,11 @@ SIM117 [*] Use a single `with` statement with multiple contexts instead of neste 10 | print("hello") | help: Combine `with` statements - | -6 | # SIM117 - - with A(): - - with B(): - - with C(): - - print("hello") -7 + with A(), B(): -8 + with C(): -9 + print("hello") -10 | - | + | +7 + with A(), B(): +8 + with C(): +9 + print("hello") + | SIM117 Use a single `with` statement with multiple contexts instead of nested `with` statements --> SIM117.py:13:1 @@ -68,15 +57,9 @@ SIM117 [*] Use a single `with` statement with multiple contexts instead of neste | help: Combine `with` statements | -18 | # SIM117 - - with A() as a: - - with B() as b: - - # Fixable due to placement of this comment. - - print("hello") 19 + with A() as a, B() as b: 20 + # Fixable due to placement of this comment. 21 + print("hello") -22 | | SIM117 [*] Use a single `with` statement with multiple contexts instead of nested `with` statements @@ -90,13 +73,8 @@ SIM117 [*] Use a single `with` statement with multiple contexts instead of neste | help: Combine `with` statements | -46 | # SIM117 - - async with A() as a: - - async with B() as b: - - print("hello") 47 + async with A() as a, B() as b: 48 + print("hello") -49 | | SIM117 [*] Use a single `with` statement with multiple contexts instead of nested `with` statements @@ -112,25 +90,18 @@ SIM117 [*] Use a single `with` statement with multiple contexts instead of neste | help: Combine `with` statements | -52 | # SIM117 - - with A() as a: - - with B() as b: - - """this 53 + with A() as a, B() as b: 54 + """this -55 | is valid""" -56 | - - """the indentation on +55 + is valid""" +56 + 57 + """the indentation on -58 | this line is significant""" -59 | - - "this is" \ +58 + this line is significant""" +59 + 60 + "this is" \ -61 | "allowed too" -62 | - - ("so is" +61 + "allowed too" +62 + 63 + ("so is" -64 | "this for some reason") +64 + "this for some reason") | SIM117 [*] Use a single `with` statement with multiple contexts instead of nested `with` statements @@ -147,14 +118,11 @@ SIM117 [*] Use a single `with` statement with multiple contexts instead of neste | help: Combine `with` statements | -69 | A() as a, - - B() as b, +68 + with ( +69 + A() as a, 70 + B() as b,C() as c -71 | ): - - with C() as c: - - print("hello") +71 + ): 72 + print("hello") -73 | | SIM117 [*] Use a single `with` statement with multiple contexts instead of nested `with` statements @@ -171,19 +139,11 @@ SIM117 [*] Use a single `with` statement with multiple contexts instead of neste | help: Combine `with` statements | -75 | # SIM117 - - with A() as a: - - with ( - - B() as b, - - C() as c, - - ): - - print("hello") 76 + with ( 77 + A() as a, B() as b, 78 + C() as c, 79 + ): 80 + print("hello") -81 | | SIM117 [*] Use a single `with` statement with multiple contexts instead of nested `with` statements @@ -203,18 +163,12 @@ SIM117 [*] Use a single `with` statement with multiple contexts instead of neste | help: Combine `with` statements | -85 | A() as a, - - B() as b, +84 + with ( +85 + A() as a, 86 + B() as b,C() as c, 87 + D() as d, -88 | ): - - with ( - - C() as c, - - D() as d, - - ): - - print("hello") +88 + ): 89 + print("hello") -90 | | SIM117 [*] Use a single `with` statement with multiple contexts instead of nested `with` statements @@ -228,13 +182,8 @@ SIM117 [*] Use a single `with` statement with multiple contexts instead of neste | help: Combine `with` statements | -94 | # SIM117 (auto-fixable) - - with A("01ß9💣2ℝ8901ß9💣2ℝ8901ß9💣2ℝ89") as a: - - with B("01ß9💣2ℝ8901ß9💣2ℝ8901ß9💣2ℝ89") as b: - - print("hello") -95 + with A("01ß9💣2ℝ8901ß9💣2ℝ8901ß9💣2ℝ89") as a, B("01ß9💣2ℝ8901ß9💣2ℝ8901ß9💣2ℝ89") as b: +95 ~ with A("01ß9💣2ℝ8901ß9💣2ℝ8901ß9💣2ℝ89") as a, B("01ß9💣2ℝ8901ß9💣2ℝ8901ß9💣2ℝ89") as b: 96 + print("hello") -97 | | SIM117 Use a single `with` statement with multiple contexts instead of nested `with` statements @@ -271,26 +220,16 @@ SIM117 [*] Use a single `with` statement with multiple contexts instead of neste | help: Combine `with` statements | -125 | # SIM117 - - with A() as a: - - with B() as b: - - type ListOrSet[T] = list[T] | set[T] 126 + with A() as a, B() as b: 127 + type ListOrSet[T] = list[T] | set[T] -128 | - - class ClassA[T: str]: - - def method1(self) -> T: - - ... +128 + 129 + class ClassA[T: str]: 130 + def method1(self) -> T: 131 + ... -132 | - - f" something { my_dict["key"] } something else " +132 + 133 + f" something { my_dict["key"] } something else " -134 | - - f"foo {f"bar {x}"} baz" +134 + 135 + f"foo {f"bar {x}"} baz" -136 | | SIM117 [*] Use a single `with` statement with multiple contexts instead of nested `with` statements @@ -304,10 +243,6 @@ SIM117 [*] Use a single `with` statement with multiple contexts instead of neste | help: Combine `with` statements | -162 | # Do not suppress combination, if a context manager is already combined with another. - - async with asyncio.timeout(1), A(): - - async with B(): - - pass 163 + async with asyncio.timeout(1), A(), B(): 164 + pass | diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM118_SIM118.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM118_SIM118.py.snap index 9edee0fda8c79..896056c60b6f8 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM118_SIM118.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM118_SIM118.py.snap @@ -13,10 +13,8 @@ SIM118 [*] Use `key in dict` instead of `key in dict.keys()` | help: Remove `.keys()` | -2 | - - key in obj.keys() # SIM118 +3 - key in obj.keys() # SIM118 3 + key in obj # SIM118 -4 | | SIM118 [*] Use `key not in dict` instead of `key not in dict.keys()` @@ -31,10 +29,8 @@ SIM118 [*] Use `key not in dict` instead of `key not in dict.keys()` | help: Remove `.keys()` | -4 | - - key not in obj.keys() # SIM118 +5 - key not in obj.keys() # SIM118 5 + key not in obj # SIM118 -6 | | SIM118 [*] Use `key in dict` instead of `key in dict.keys()` @@ -49,10 +45,8 @@ SIM118 [*] Use `key in dict` instead of `key in dict.keys()` | help: Remove `.keys()` | -6 | - - foo["bar"] in obj.keys() # SIM118 +7 - foo["bar"] in obj.keys() # SIM118 7 + foo["bar"] in obj # SIM118 -8 | | SIM118 [*] Use `key not in dict` instead of `key not in dict.keys()` @@ -66,12 +60,10 @@ SIM118 [*] Use `key not in dict` instead of `key not in dict.keys()` 11 | foo['bar'] in obj.keys() # SIM118 | help: Remove `.keys()` - | -8 | - - foo["bar"] not in obj.keys() # SIM118 -9 + foo["bar"] not in obj # SIM118 -10 | - | + | +9 - foo["bar"] not in obj.keys() # SIM118 +9 + foo["bar"] not in obj # SIM118 + | SIM118 [*] Use `key in dict` instead of `key in dict.keys()` --> SIM118.py:11:1 @@ -85,10 +77,8 @@ SIM118 [*] Use `key in dict` instead of `key in dict.keys()` | help: Remove `.keys()` | -10 | - - foo['bar'] in obj.keys() # SIM118 +11 - foo['bar'] in obj.keys() # SIM118 11 + foo['bar'] in obj # SIM118 -12 | | SIM118 [*] Use `key not in dict` instead of `key not in dict.keys()` @@ -103,10 +93,8 @@ SIM118 [*] Use `key not in dict` instead of `key not in dict.keys()` | help: Remove `.keys()` | -12 | - - foo['bar'] not in obj.keys() # SIM118 +13 - foo['bar'] not in obj.keys() # SIM118 13 + foo['bar'] not in obj # SIM118 -14 | | SIM118 [*] Use `key in dict` instead of `key in dict.keys()` @@ -121,10 +109,8 @@ SIM118 [*] Use `key in dict` instead of `key in dict.keys()` | help: Remove `.keys()` | -14 | - - foo() in obj.keys() # SIM118 +15 - foo() in obj.keys() # SIM118 15 + foo() in obj # SIM118 -16 | | SIM118 [*] Use `key not in dict` instead of `key not in dict.keys()` @@ -139,10 +125,8 @@ SIM118 [*] Use `key not in dict` instead of `key not in dict.keys()` | help: Remove `.keys()` | -16 | - - foo() not in obj.keys() # SIM118 +17 - foo() not in obj.keys() # SIM118 17 + foo() not in obj # SIM118 -18 | | SIM118 [*] Use `key in dict` instead of `key in dict.keys()` @@ -156,10 +140,8 @@ SIM118 [*] Use `key in dict` instead of `key in dict.keys()` | help: Remove `.keys()` | -18 | - - for key in obj.keys(): # SIM118 +19 - for key in obj.keys(): # SIM118 19 + for key in obj: # SIM118 -20 | pass | SIM118 [*] Use `key in dict` instead of `key in dict.keys()` @@ -174,10 +156,8 @@ SIM118 [*] Use `key in dict` instead of `key in dict.keys()` | help: Remove `.keys()` | -25 | - - [k for k in obj.keys()] # SIM118 +26 - [k for k in obj.keys()] # SIM118 26 + [k for k in obj] # SIM118 -27 | | SIM118 [*] Use `key in dict` instead of `key in dict.keys()` @@ -192,10 +172,8 @@ SIM118 [*] Use `key in dict` instead of `key in dict.keys()` | help: Remove `.keys()` | -27 | - - {k for k in obj.keys()} # SIM118 +28 - {k for k in obj.keys()} # SIM118 28 + {k for k in obj} # SIM118 -29 | | SIM118 [*] Use `key in dict` instead of `key in dict.keys()` @@ -210,10 +188,8 @@ SIM118 [*] Use `key in dict` instead of `key in dict.keys()` | help: Remove `.keys()` | -29 | - - {k: k for k in obj.keys()} # SIM118 +30 - {k: k for k in obj.keys()} # SIM118 30 + {k: k for k in obj} # SIM118 -31 | | SIM118 [*] Use `key in dict` instead of `key in dict.keys()` @@ -228,10 +204,8 @@ SIM118 [*] Use `key in dict` instead of `key in dict.keys()` | help: Remove `.keys()` | -31 | - - (k for k in obj.keys()) # SIM118 +32 - (k for k in obj.keys()) # SIM118 32 + (k for k in obj) # SIM118 -33 | | SIM118 [*] Use `key in dict` instead of `key in dict.keys()` @@ -246,10 +220,8 @@ SIM118 [*] Use `key in dict` instead of `key in dict.keys()` | help: Remove `.keys()` | -33 | - - key in (obj or {}).keys() # SIM118 +34 - key in (obj or {}).keys() # SIM118 34 + key in (obj or {}) # SIM118 -35 | | note: This is an unsafe fix and may change runtime behavior @@ -265,10 +237,8 @@ SIM118 [*] Use `key in dict` instead of `key in dict.keys()` | help: Remove `.keys()` | -35 | - - (key) in (obj or {}).keys() # SIM118 +36 - (key) in (obj or {}).keys() # SIM118 36 + (key) in (obj or {}) # SIM118 -37 | | note: This is an unsafe fix and may change runtime behavior @@ -283,10 +253,8 @@ SIM118 [*] Use `key in dict` instead of `key in dict.keys()` | help: Remove `.keys()` | -49 | # Regression test for: https://github.com/astral-sh/ruff/issues/7124 - - key in obj.keys()and foo +50 - key in obj.keys()and foo 50 + key in obj and foo -51 | (key in obj.keys())and foo | SIM118 [*] Use `key in dict` instead of `key in dict.keys()` @@ -300,10 +268,8 @@ SIM118 [*] Use `key in dict` instead of `key in dict.keys()` | help: Remove `.keys()` | -50 | key in obj.keys()and foo - - (key in obj.keys())and foo +51 - (key in obj.keys())and foo 51 + (key in obj)and foo -52 | key in (obj.keys())and foo | SIM118 [*] Use `key in dict` instead of `key in dict.keys()` @@ -318,10 +284,8 @@ SIM118 [*] Use `key in dict` instead of `key in dict.keys()` | help: Remove `.keys()` | -51 | (key in obj.keys())and foo - - key in (obj.keys())and foo +52 - key in (obj.keys())and foo 52 + key in (obj)and foo -53 | | SIM118 [*] Use `key in dict` instead of `key in dict.keys()` @@ -339,10 +303,7 @@ SIM118 [*] Use `key in dict` instead of `key in dict.keys()` | help: Remove `.keys()` | -57 | .stations[0] - - .keys() -58 + -59 | ): +58 - .keys() | note: This is an unsafe fix and may change runtime behavior @@ -354,7 +315,6 @@ SIM118 [*] Use `key in dict` instead of `key in dict.keys()` | ^^^^^^^^^^^^^^^ help: Remove `.keys()` | -64 | d = SneakyDict() - - key in d.keys() # SIM118 +65 - key in d.keys() # SIM118 65 + key in d # SIM118 | diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM201_SIM201.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM201_SIM201.py.snap index a5001003504a8..808fe819b098f 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM201_SIM201.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM201_SIM201.py.snap @@ -11,10 +11,8 @@ SIM201 [*] Use `a != b` instead of `not a == b` | help: Replace with `!=` operator | -1 | # SIM201 - - if not a == b: +2 - if not a == b: 2 + if a != b: -3 | pass | note: This is an unsafe fix and may change runtime behavior @@ -28,10 +26,8 @@ SIM201 [*] Use `a != b + c` instead of `not a == b + c` | help: Replace with `!=` operator | -5 | # SIM201 - - if not a == (b + c): +6 - if not a == (b + c): 6 + if a != b + c: -7 | pass | note: This is an unsafe fix and may change runtime behavior @@ -45,9 +41,7 @@ SIM201 [*] Use `a + b != c` instead of `not a + b == c` | help: Replace with `!=` operator | -9 | # SIM201 - - if not (a + b) == c: +10 - if not (a + b) == c: 10 + if a + b != c: -11 | pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM202_SIM202.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM202_SIM202.py.snap index 3e5c9259de366..6492839229bc7 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM202_SIM202.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM202_SIM202.py.snap @@ -11,10 +11,8 @@ SIM202 [*] Use `a == b` instead of `not a != b` | help: Replace with `==` operator | -1 | # SIM202 - - if not a != b: +2 - if not a != b: 2 + if a == b: -3 | pass | note: This is an unsafe fix and may change runtime behavior @@ -28,10 +26,8 @@ SIM202 [*] Use `a == b + c` instead of `not a != b + c` | help: Replace with `==` operator | -5 | # SIM202 - - if not a != (b + c): +6 - if not a != (b + c): 6 + if a == b + c: -7 | pass | note: This is an unsafe fix and may change runtime behavior @@ -45,9 +41,7 @@ SIM202 [*] Use `a + b == c` instead of `not a + b != c` | help: Replace with `==` operator | -9 | # SIM202 - - if not (a + b) != c: +10 - if not (a + b) != c: 10 + if a + b == c: -11 | pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM208_SIM208.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM208_SIM208.py.snap index 2afc79efa2244..b94f6063cb778 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM208_SIM208.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM208_SIM208.py.snap @@ -10,9 +10,8 @@ SIM208 [*] Use `a` instead of `not (not a)` | help: Replace with `a` | - - if not (not a): # SIM208 +1 - if not (not a): # SIM208 1 + if a: # SIM208 -2 | pass | SIM208 [*] Use `a == b` instead of `not (not a == b)` @@ -26,10 +25,8 @@ SIM208 [*] Use `a == b` instead of `not (not a == b)` | help: Replace with `a == b` | -3 | - - if not (not (a == b)): # SIM208 +4 - if not (not (a == b)): # SIM208 4 + if a == b: # SIM208 -5 | pass | SIM208 [*] Use `b` instead of `not (not b)` @@ -44,10 +41,8 @@ SIM208 [*] Use `b` instead of `not (not b)` | help: Replace with `b` | -15 | - - a = not not b # SIM208 +16 - a = not not b # SIM208 16 + a = bool(b) # SIM208 -17 | | SIM208 [*] Use `a` instead of `not (not a)` @@ -62,10 +57,8 @@ SIM208 [*] Use `a` instead of `not (not a)` | help: Replace with `a` | -17 | - - f(not not a) # SIM208 +18 - f(not not a) # SIM208 18 + f(bool(a)) # SIM208 -19 | | SIM208 [*] Use `a` instead of `not (not a)` @@ -79,8 +72,6 @@ SIM208 [*] Use `a` instead of `not (not a)` | help: Replace with `a` | -19 | - - if 1 + (not (not a)): # SIM208 +20 - if 1 + (not (not a)): # SIM208 20 + if 1 + (bool(a)): # SIM208 -21 | pass | diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM210_SIM210.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM210_SIM210.py.snap index 072f7aac6ec87..9b57b23fe5d3e 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM210_SIM210.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM210_SIM210.py.snap @@ -11,9 +11,8 @@ SIM210 [*] Use `bool(...)` instead of `True if ... else False` | help: Replace with `bool(...) | - - a = True if b else False # SIM210 +1 - a = True if b else False # SIM210 1 + a = bool(b) # SIM210 -2 | | note: This is an unsafe fix and may change runtime behavior @@ -29,10 +28,8 @@ SIM210 [*] Remove unnecessary `True if ... else False` | help: Remove unnecessary `True if ... else False` | -2 | - - a = True if b != c else False # SIM210 +3 - a = True if b != c else False # SIM210 3 + a = b != c # SIM210 -4 | | note: This is an unsafe fix and may change runtime behavior @@ -48,10 +45,8 @@ SIM210 [*] Use `bool(...)` instead of `True if ... else False` | help: Replace with `bool(...) | -4 | - - a = True if b + c else False # SIM210 +5 - a = True if b + c else False # SIM210 5 + a = bool(b + c) # SIM210 -6 | | note: This is an unsafe fix and may change runtime behavior @@ -74,10 +69,7 @@ SIM210 [*] Remove unnecessary `True if ... else False` | |____________________________________________________________________________^ help: Remove unnecessary `True if ... else False` | -18 | # Regression test for: https://github.com/astral-sh/ruff/issues/7076 - - samesld = True if (psl.privatesuffix(urlparse(response.url).netloc) == - - psl.privatesuffix(src.netloc)) else False -19 + samesld = (psl.privatesuffix(urlparse(response.url).netloc) == +19 ~ samesld = (psl.privatesuffix(urlparse(response.url).netloc) == 20 + psl.privatesuffix(src.netloc)) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM211_SIM211.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM211_SIM211.py.snap index b76b2b807a907..d7b3c58956372 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM211_SIM211.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM211_SIM211.py.snap @@ -11,9 +11,8 @@ SIM211 [*] Use `not ...` instead of `False if ... else True` | help: Replace with `not ...` | - - a = False if b else True # SIM211 +1 - a = False if b else True # SIM211 1 + a = not b # SIM211 -2 | | note: This is an unsafe fix and may change runtime behavior @@ -29,10 +28,8 @@ SIM211 [*] Use `not ...` instead of `False if ... else True` | help: Replace with `not ...` | -2 | - - a = False if b != c else True # SIM211 +3 - a = False if b != c else True # SIM211 3 + a = not b != c # SIM211 -4 | | note: This is an unsafe fix and may change runtime behavior @@ -48,9 +45,7 @@ SIM211 [*] Use `not ...` instead of `False if ... else True` | help: Replace with `not ...` | -4 | - - a = False if b + c else True # SIM211 +5 - a = False if b + c else True # SIM211 5 + a = not b + c # SIM211 -6 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM212_SIM212.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM212_SIM212.py.snap index dec39c765c53c..5a3ad00647277 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM212_SIM212.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM212_SIM212.py.snap @@ -11,9 +11,8 @@ SIM212 [*] Use `a if a else b` instead of `b if not a else a` | help: Replace with `a if a else b` | - - c = b if not a else a # SIM212 +1 - c = b if not a else a # SIM212 1 + c = a if a else b # SIM212 -2 | | note: This is an unsafe fix and may change runtime behavior @@ -29,9 +28,7 @@ SIM212 [*] Use `a if a else b + c` instead of `b + c if not a else a` | help: Replace with `a if a else b + c` | -2 | - - c = b + c if not a else a # SIM212 +3 - c = b + c if not a else a # SIM212 3 + c = a if a else b + c # SIM212 -4 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM220_SIM220.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM220_SIM220.py.snap index 48725bfb4e28a..12374f35ae042 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM220_SIM220.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM220_SIM220.py.snap @@ -10,9 +10,8 @@ SIM220 [*] Use `False` instead of `a and not a` | help: Replace with `False` | - - if a and not a: +1 - if a and not a: 1 + if False: -2 | pass | note: This is an unsafe fix and may change runtime behavior @@ -27,10 +26,8 @@ SIM220 [*] Use `False` instead of `a and not a` | help: Replace with `False` | -3 | - - if (a and not a) and b: +4 - if (a and not a) and b: 4 + if (False) and b: -5 | pass | note: This is an unsafe fix and may change runtime behavior @@ -45,9 +42,7 @@ SIM220 [*] Use `False` instead of `a and not a` | help: Replace with `False` | -6 | - - if (a and not a) or b: +7 - if (a and not a) or b: 7 + if (False) or b: -8 | pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM221_SIM221.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM221_SIM221.py.snap index 688289abd46eb..b08b4f0e47044 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM221_SIM221.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM221_SIM221.py.snap @@ -10,9 +10,8 @@ SIM221 [*] Use `True` instead of `a or not a` | help: Replace with `True` | - - if a or not a: +1 - if a or not a: 1 + if True: -2 | pass | note: This is an unsafe fix and may change runtime behavior @@ -27,10 +26,8 @@ SIM221 [*] Use `True` instead of `a or not a` | help: Replace with `True` | -3 | - - if (a or not a) or b: +4 - if (a or not a) or b: 4 + if (True) or b: -5 | pass | note: This is an unsafe fix and may change runtime behavior @@ -45,9 +42,7 @@ SIM221 [*] Use `True` instead of `a or not a` | help: Replace with `True` | -6 | - - if (a or not a) and b: +7 - if (a or not a) and b: 7 + if (True) and b: -8 | pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM222_SIM222.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM222_SIM222.py.snap index 70c8050097236..2b8bcf7a21386 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM222_SIM222.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM222_SIM222.py.snap @@ -10,9 +10,8 @@ SIM222 [*] Use `True` instead of `... or True` | help: Replace with `True` | - - if a or True: # SIM222 +1 - if a or True: # SIM222 1 + if True: # SIM222 -2 | pass | note: This is an unsafe fix and may change runtime behavior @@ -27,10 +26,8 @@ SIM222 [*] Use `True` instead of `... or True` | help: Replace with `True` | -3 | - - if (a or b) or True: # SIM222 +4 - if (a or b) or True: # SIM222 4 + if True: # SIM222 -5 | pass | note: This is an unsafe fix and may change runtime behavior @@ -45,10 +42,8 @@ SIM222 [*] Use `True` instead of `... or True` | help: Replace with `True` | -6 | - - if a or (b or True): # SIM222 +7 - if a or (b or True): # SIM222 7 + if a or (True): # SIM222 -8 | pass | note: This is an unsafe fix and may change runtime behavior @@ -63,10 +58,8 @@ SIM222 [*] Use `True` instead of `True or ...` | help: Replace with `True` | -23 | - - if a or f() or True or g() or b: # SIM222 +24 - if a or f() or True or g() or b: # SIM222 24 + if a or f() or True: # SIM222 -25 | pass | note: This is an unsafe fix and may change runtime behavior @@ -81,10 +74,8 @@ SIM222 [*] Use `True` instead of `True or ...` | help: Replace with `True` | -26 | - - if True or f() or a or g() or b: # SIM222 +27 - if True or f() or a or g() or b: # SIM222 27 + if True: # SIM222 -28 | pass | note: This is an unsafe fix and may change runtime behavior @@ -99,10 +90,8 @@ SIM222 [*] Use `True` instead of `... or True or ...` | help: Replace with `True` | -29 | - - if a or True or f() or b or g(): # SIM222 +30 - if a or True or f() or b or g(): # SIM222 30 + if True: # SIM222 -31 | pass | note: This is an unsafe fix and may change runtime behavior @@ -116,10 +105,8 @@ SIM222 [*] Use `True` instead of `... or True` | help: Replace with `True` | -46 | - - a or "" or True # SIM222 +47 - a or "" or True # SIM222 47 + a or True # SIM222 -48 | | note: This is an unsafe fix and may change runtime behavior @@ -135,10 +122,8 @@ SIM222 [*] Use `"foo"` instead of `"foo" or ...` | help: Replace with `"foo"` | -48 | - - a or "foo" or True or "bar" # SIM222 +49 - a or "foo" or True or "bar" # SIM222 49 + a or "foo" # SIM222 -50 | | note: This is an unsafe fix and may change runtime behavior @@ -154,10 +139,8 @@ SIM222 [*] Use `True` instead of `... or True` | help: Replace with `True` | -50 | - - a or 0 or True # SIM222 +51 - a or 0 or True # SIM222 51 + a or True # SIM222 -52 | | note: This is an unsafe fix and may change runtime behavior @@ -173,10 +156,8 @@ SIM222 [*] Use `1` instead of `1 or ...` | help: Replace with `1` | -52 | - - a or 1 or True or 2 # SIM222 +53 - a or 1 or True or 2 # SIM222 53 + a or 1 # SIM222 -54 | | note: This is an unsafe fix and may change runtime behavior @@ -192,10 +173,8 @@ SIM222 [*] Use `True` instead of `... or True` | help: Replace with `True` | -54 | - - a or 0.0 or True # SIM222 +55 - a or 0.0 or True # SIM222 55 + a or True # SIM222 -56 | | note: This is an unsafe fix and may change runtime behavior @@ -211,10 +190,8 @@ SIM222 [*] Use `0.1` instead of `0.1 or ...` | help: Replace with `0.1` | -56 | - - a or 0.1 or True or 0.2 # SIM222 +57 - a or 0.1 or True or 0.2 # SIM222 57 + a or 0.1 # SIM222 -58 | | note: This is an unsafe fix and may change runtime behavior @@ -230,10 +207,8 @@ SIM222 [*] Use `True` instead of `... or True` | help: Replace with `True` | -58 | - - a or [] or True # SIM222 +59 - a or [] or True # SIM222 59 + a or True # SIM222 -60 | | note: This is an unsafe fix and may change runtime behavior @@ -249,10 +224,8 @@ SIM222 [*] Use `True` instead of `... or True` | help: Replace with `True` | -60 | - - a or list([]) or True # SIM222 +61 - a or list([]) or True # SIM222 61 + a or True # SIM222 -62 | | note: This is an unsafe fix and may change runtime behavior @@ -268,10 +241,8 @@ SIM222 [*] Use `[1]` instead of `[1] or ...` | help: Replace with `[1]` | -62 | - - a or [1] or True or [2] # SIM222 +63 - a or [1] or True or [2] # SIM222 63 + a or [1] # SIM222 -64 | | note: This is an unsafe fix and may change runtime behavior @@ -287,10 +258,8 @@ SIM222 [*] Use `list([1])` instead of `list([1]) or ...` | help: Replace with `list([1])` | -64 | - - a or list([1]) or True or list([2]) # SIM222 +65 - a or list([1]) or True or list([2]) # SIM222 65 + a or list([1]) # SIM222 -66 | | note: This is an unsafe fix and may change runtime behavior @@ -306,10 +275,8 @@ SIM222 [*] Use `True` instead of `... or True` | help: Replace with `True` | -66 | - - a or {} or True # SIM222 +67 - a or {} or True # SIM222 67 + a or True # SIM222 -68 | | note: This is an unsafe fix and may change runtime behavior @@ -325,10 +292,8 @@ SIM222 [*] Use `True` instead of `... or True` | help: Replace with `True` | -68 | - - a or dict() or True # SIM222 +69 - a or dict() or True # SIM222 69 + a or True # SIM222 -70 | | note: This is an unsafe fix and may change runtime behavior @@ -344,10 +309,8 @@ SIM222 [*] Use `{1: 1}` instead of `{1: 1} or ...` | help: Replace with `{1: 1}` | -70 | - - a or {1: 1} or True or {2: 2} # SIM222 +71 - a or {1: 1} or True or {2: 2} # SIM222 71 + a or {1: 1} # SIM222 -72 | | note: This is an unsafe fix and may change runtime behavior @@ -363,10 +326,8 @@ SIM222 [*] Use `dict({1: 1})` instead of `dict({1: 1}) or ...` | help: Replace with `dict({1: 1})` | -72 | - - a or dict({1: 1}) or True or dict({2: 2}) # SIM222 +73 - a or dict({1: 1}) or True or dict({2: 2}) # SIM222 73 + a or dict({1: 1}) # SIM222 -74 | | note: This is an unsafe fix and may change runtime behavior @@ -382,10 +343,8 @@ SIM222 [*] Use `True` instead of `... or True` | help: Replace with `True` | -74 | - - a or set() or True # SIM222 +75 - a or set() or True # SIM222 75 + a or True # SIM222 -76 | | note: This is an unsafe fix and may change runtime behavior @@ -401,10 +360,8 @@ SIM222 [*] Use `True` instead of `... or True` | help: Replace with `True` | -76 | - - a or set(set()) or True # SIM222 +77 - a or set(set()) or True # SIM222 77 + a or True # SIM222 -78 | | note: This is an unsafe fix and may change runtime behavior @@ -420,10 +377,8 @@ SIM222 [*] Use `{1}` instead of `{1} or ...` | help: Replace with `{1}` | -78 | - - a or {1} or True or {2} # SIM222 +79 - a or {1} or True or {2} # SIM222 79 + a or {1} # SIM222 -80 | | note: This is an unsafe fix and may change runtime behavior @@ -439,10 +394,8 @@ SIM222 [*] Use `set({1})` instead of `set({1}) or ...` | help: Replace with `set({1})` | -80 | - - a or set({1}) or True or set({2}) # SIM222 +81 - a or set({1}) or True or set({2}) # SIM222 81 + a or set({1}) # SIM222 -82 | | note: This is an unsafe fix and may change runtime behavior @@ -458,10 +411,8 @@ SIM222 [*] Use `True` instead of `... or True` | help: Replace with `True` | -82 | - - a or () or True # SIM222 +83 - a or () or True # SIM222 83 + a or True # SIM222 -84 | | note: This is an unsafe fix and may change runtime behavior @@ -477,10 +428,8 @@ SIM222 [*] Use `True` instead of `... or True` | help: Replace with `True` | -84 | - - a or tuple(()) or True # SIM222 +85 - a or tuple(()) or True # SIM222 85 + a or True # SIM222 -86 | | note: This is an unsafe fix and may change runtime behavior @@ -496,10 +445,8 @@ SIM222 [*] Use `(1,)` instead of `(1,) or ...` | help: Replace with `(1,)` | -86 | - - a or (1,) or True or (2,) # SIM222 +87 - a or (1,) or True or (2,) # SIM222 87 + a or (1,) # SIM222 -88 | | note: This is an unsafe fix and may change runtime behavior @@ -515,10 +462,8 @@ SIM222 [*] Use `tuple((1,))` instead of `tuple((1,)) or ...` | help: Replace with `tuple((1,))` | -88 | - - a or tuple((1,)) or True or tuple((2,)) # SIM222 +89 - a or tuple((1,)) or True or tuple((2,)) # SIM222 89 + a or tuple((1,)) # SIM222 -90 | | note: This is an unsafe fix and may change runtime behavior @@ -534,10 +479,8 @@ SIM222 [*] Use `True` instead of `... or True` | help: Replace with `True` | -90 | - - a or frozenset() or True # SIM222 +91 - a or frozenset() or True # SIM222 91 + a or True # SIM222 -92 | | note: This is an unsafe fix and may change runtime behavior @@ -553,10 +496,8 @@ SIM222 [*] Use `True` instead of `... or True` | help: Replace with `True` | -92 | - - a or frozenset(frozenset()) or True # SIM222 +93 - a or frozenset(frozenset()) or True # SIM222 93 + a or True # SIM222 -94 | | note: This is an unsafe fix and may change runtime behavior @@ -572,10 +513,8 @@ SIM222 [*] Use `frozenset({1})` instead of `frozenset({1}) or ...` | help: Replace with `frozenset({1})` | -94 | - - a or frozenset({1}) or True or frozenset({2}) # SIM222 +95 - a or frozenset({1}) or True or frozenset({2}) # SIM222 95 + a or frozenset({1}) # SIM222 -96 | | note: This is an unsafe fix and may change runtime behavior @@ -588,10 +527,8 @@ SIM222 [*] Use `frozenset(frozenset({1}))` instead of `frozenset(frozenset({1})) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `frozenset(frozenset({1}))` | -96 | - - a or frozenset(frozenset({1})) or True or frozenset(frozenset({2})) # SIM222 +97 - a or frozenset(frozenset({1})) or True or frozenset(frozenset({2})) # SIM222 97 + a or frozenset(frozenset({1})) # SIM222 -98 | | note: This is an unsafe fix and may change runtime behavior @@ -607,10 +544,8 @@ SIM222 [*] Use `True` instead of `... or True or ...` | help: Replace with `True` | -101 | - - bool(a or [1] or True or [2]) # SIM222 +102 - bool(a or [1] or True or [2]) # SIM222 102 + bool(True) # SIM222 -103 | | note: This is an unsafe fix and may change runtime behavior @@ -626,10 +561,8 @@ SIM222 [*] Use `True` instead of `... or True or ...` | help: Replace with `True` | -103 | - - assert a or [1] or True or [2] # SIM222 +104 - assert a or [1] or True or [2] # SIM222 104 + assert True # SIM222 -105 | | note: This is an unsafe fix and may change runtime behavior @@ -644,10 +577,8 @@ SIM222 [*] Use `True` instead of `... or True or ...` | help: Replace with `True` | -105 | - - if (a or [1] or True or [2]) and (a or [1] or True or [2]): # SIM222 +106 - if (a or [1] or True or [2]) and (a or [1] or True or [2]): # SIM222 106 + if (True) and (a or [1] or True or [2]): # SIM222 -107 | pass | note: This is an unsafe fix and may change runtime behavior @@ -662,10 +593,8 @@ SIM222 [*] Use `True` instead of `... or True or ...` | help: Replace with `True` | -105 | - - if (a or [1] or True or [2]) and (a or [1] or True or [2]): # SIM222 +106 - if (a or [1] or True or [2]) and (a or [1] or True or [2]): # SIM222 106 + if (a or [1] or True or [2]) and (True): # SIM222 -107 | pass | note: This is an unsafe fix and may change runtime behavior @@ -681,10 +610,8 @@ SIM222 [*] Use `True` instead of `... or True or ...` | help: Replace with `True` | -108 | - - 0 if a or [1] or True or [2] else 1 # SIM222 +109 - 0 if a or [1] or True or [2] else 1 # SIM222 109 + 0 if True else 1 # SIM222 -110 | | note: This is an unsafe fix and may change runtime behavior @@ -699,10 +626,8 @@ SIM222 [*] Use `True` instead of `... or True or ...` | help: Replace with `True` | -110 | - - while a or [1] or True or [2]: # SIM222 +111 - while a or [1] or True or [2]: # SIM222 111 + while True: # SIM222 -112 | pass | note: This is an unsafe fix and may change runtime behavior @@ -718,10 +643,8 @@ SIM222 [*] Use `True` instead of `... or True or ...` | help: Replace with `True` | -117 | for b in range(10) - - if a or [1] or True or [2] # SIM222 +118 - if a or [1] or True or [2] # SIM222 118 + if True # SIM222 -119 | if b or [1] or True or [2] # SIM222 | note: This is an unsafe fix and may change runtime behavior @@ -736,10 +659,8 @@ SIM222 [*] Use `True` instead of `... or True or ...` | help: Replace with `True` | -118 | if a or [1] or True or [2] # SIM222 - - if b or [1] or True or [2] # SIM222 +119 - if b or [1] or True or [2] # SIM222 119 + if True # SIM222 -120 | ] | note: This is an unsafe fix and may change runtime behavior @@ -755,10 +676,8 @@ SIM222 [*] Use `True` instead of `... or True or ...` | help: Replace with `True` | -125 | for b in range(10) - - if a or [1] or True or [2] # SIM222 +126 - if a or [1] or True or [2] # SIM222 126 + if True # SIM222 -127 | if b or [1] or True or [2] # SIM222 | note: This is an unsafe fix and may change runtime behavior @@ -773,10 +692,8 @@ SIM222 [*] Use `True` instead of `... or True or ...` | help: Replace with `True` | -126 | if a or [1] or True or [2] # SIM222 - - if b or [1] or True or [2] # SIM222 +127 - if b or [1] or True or [2] # SIM222 127 + if True # SIM222 -128 | } | note: This is an unsafe fix and may change runtime behavior @@ -792,10 +709,8 @@ SIM222 [*] Use `True` instead of `... or True or ...` | help: Replace with `True` | -133 | for b in range(10) - - if a or [1] or True or [2] # SIM222 +134 - if a or [1] or True or [2] # SIM222 134 + if True # SIM222 -135 | if b or [1] or True or [2] # SIM222 | note: This is an unsafe fix and may change runtime behavior @@ -810,10 +725,8 @@ SIM222 [*] Use `True` instead of `... or True or ...` | help: Replace with `True` | -134 | if a or [1] or True or [2] # SIM222 - - if b or [1] or True or [2] # SIM222 +135 - if b or [1] or True or [2] # SIM222 135 + if True # SIM222 -136 | } | note: This is an unsafe fix and may change runtime behavior @@ -829,10 +742,8 @@ SIM222 [*] Use `True` instead of `... or True or ...` | help: Replace with `True` | -141 | for b in range(10) - - if a or [1] or True or [2] # SIM222 +142 - if a or [1] or True or [2] # SIM222 142 + if True # SIM222 -143 | if b or [1] or True or [2] # SIM222 | note: This is an unsafe fix and may change runtime behavior @@ -847,10 +758,8 @@ SIM222 [*] Use `True` instead of `... or True or ...` | help: Replace with `True` | -142 | if a or [1] or True or [2] # SIM222 - - if b or [1] or True or [2] # SIM222 +143 - if b or [1] or True or [2] # SIM222 143 + if True # SIM222 -144 | ) | note: This is an unsafe fix and may change runtime behavior @@ -866,10 +775,8 @@ SIM222 [*] Use `[1]` instead of `[1] or ...` | help: Replace with `[1]` | -147 | - - a or [1] or True or [2] # SIM222 +148 - a or [1] or True or [2] # SIM222 148 + a or [1] # SIM222 -149 | | note: This is an unsafe fix and may change runtime behavior @@ -884,10 +791,8 @@ SIM222 [*] Use `[1]` instead of `[1] or ...` | help: Replace with `[1]` | -149 | - - if (a or [1] or True or [2]) == (a or [1]): # SIM222 +150 - if (a or [1] or True or [2]) == (a or [1]): # SIM222 150 + if (a or [1]) == (a or [1]): # SIM222 -151 | pass | note: This is an unsafe fix and may change runtime behavior @@ -902,10 +807,8 @@ SIM222 [*] Use `[1]` instead of `[1] or ...` | help: Replace with `[1]` | -152 | - - if f(a or [1] or True or [2]): # SIM222 +153 - if f(a or [1] or True or [2]): # SIM222 153 + if f(a or [1]): # SIM222 -154 | pass | note: This is an unsafe fix and may change runtime behavior @@ -919,10 +822,8 @@ SIM222 [*] Use `(int, int, int)` instead of `(int, int, int) or ...` | help: Replace with `(int, int, int)` | -156 | # Regression test for: https://github.com/astral-sh/ruff/issues/7099 - - def secondToTime(s0: int) -> (int, int, int) or str: +157 - def secondToTime(s0: int) -> (int, int, int) or str: 157 + def secondToTime(s0: int) -> (int, int, int): -158 | m, s = divmod(s0, 60) | note: This is an unsafe fix and may change runtime behavior @@ -935,10 +836,8 @@ SIM222 [*] Use `(int, int, int)` instead of `(int, int, int) or ...` | help: Replace with `(int, int, int)` | -160 | - - def secondToTime(s0: int) -> ((int, int, int) or str): +161 - def secondToTime(s0: int) -> ((int, int, int) or str): 161 + def secondToTime(s0: int) -> ((int, int, int)): -162 | m, s = divmod(s0, 60) | note: This is an unsafe fix and may change runtime behavior @@ -953,10 +852,8 @@ SIM222 [*] Use `"bar"` instead of `... or "bar"` | help: Replace with `"bar"` | -167 | print(f"{a}{''}" or "bar") - - print(f"{''}{''}" or "bar") +168 - print(f"{''}{''}" or "bar") 168 + print("bar") -169 | print(f"{1}{''}" or "bar") | note: This is an unsafe fix and may change runtime behavior @@ -969,10 +866,8 @@ SIM222 [*] Use `f"{1}{''}"` instead of `f"{1}{''}" or ...` | ^^^^^^^^^^^^^^^^^^^ help: Replace with `f"{1}{''}"` | -168 | print(f"{''}{''}" or "bar") - - print(f"{1}{''}" or "bar") +169 - print(f"{1}{''}" or "bar") 169 + print(f"{1}{''}") -170 | | note: This is an unsafe fix and may change runtime behavior @@ -987,10 +882,8 @@ SIM222 [*] Use `f"{b''}"` instead of `f"{b''}" or ...` | help: Replace with `f"{b''}"` | -201 | # https://github.com/astral-sh/ruff/issues/20703 - - print(f"{b''}" or "bar") # SIM222 +202 - print(f"{b''}" or "bar") # SIM222 202 + print(f"{b''}") # SIM222 -203 | x = 1 | note: This is an unsafe fix and may change runtime behavior @@ -1006,10 +899,8 @@ SIM222 [*] Use `f"{x=}"` instead of `f"{x=}" or ...` | help: Replace with `f"{x=}"` | -203 | x = 1 - - print(f"{x=}" or "bar") # SIM222 +204 - print(f"{x=}" or "bar") # SIM222 204 + print(f"{x=}") # SIM222 -205 | (lambda: 1) or True # SIM222 | note: This is an unsafe fix and may change runtime behavior @@ -1024,10 +915,8 @@ SIM222 [*] Use `lambda: 1` instead of `lambda: 1 or ...` | help: Replace with `lambda: 1` | -204 | print(f"{x=}" or "bar") # SIM222 - - (lambda: 1) or True # SIM222 +205 - (lambda: 1) or True # SIM222 205 + lambda: 1 # SIM222 -206 | (i for i in range(1)) or "bar" # SIM222 | note: This is an unsafe fix and may change runtime behavior @@ -1043,10 +932,8 @@ SIM222 [*] Use `(i for i in range(1))` instead of `(i for i in range(1)) or ...` | help: Replace with `(i for i in range(1))` | -205 | (lambda: 1) or True # SIM222 - - (i for i in range(1)) or "bar" # SIM222 +206 - (i for i in range(1)) or "bar" # SIM222 206 + (i for i in range(1)) # SIM222 -207 | | note: This is an unsafe fix and may change runtime behavior @@ -1061,10 +948,8 @@ SIM222 [*] Use `True` instead of `... or True` | help: Replace with `True` | -221 | # https://github.com/astral-sh/ruff/issues/21473 - - tuple("") or True # SIM222 +222 - tuple("") or True # SIM222 222 + True # SIM222 -223 | tuple(t"") or True # OK | note: This is an unsafe fix and may change runtime behavior @@ -1079,9 +964,7 @@ SIM222 [*] Use `f"{x}abc"` instead of `f"{x}abc" or ...` | help: Replace with `f"{x}abc"` | -232 | # An f-string is guaranteed non-empty if any element is non-empty, even if others are indeterminate - - print(f"{x}abc" or "bar") # SIM222 +233 - print(f"{x}abc" or "bar") # SIM222 233 + print(f"{x}abc") # SIM222 -234 | # An empty f-string part in an implicit concatenation guarantees nothing | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM223_SIM223.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM223_SIM223.py.snap index 31886dd5a0e8d..0d6250947db40 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM223_SIM223.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM223_SIM223.py.snap @@ -10,9 +10,8 @@ SIM223 [*] Use `False` instead of `... and False` | help: Replace with `False` | - - if a and False: # SIM223 +1 - if a and False: # SIM223 1 + if False: # SIM223 -2 | pass | note: This is an unsafe fix and may change runtime behavior @@ -27,10 +26,8 @@ SIM223 [*] Use `False` instead of `... and False` | help: Replace with `False` | -3 | - - if (a or b) and False: # SIM223 +4 - if (a or b) and False: # SIM223 4 + if False: # SIM223 -5 | pass | note: This is an unsafe fix and may change runtime behavior @@ -45,10 +42,8 @@ SIM223 [*] Use `False` instead of `... and False` | help: Replace with `False` | -6 | - - if a or (b and False): # SIM223 +7 - if a or (b and False): # SIM223 7 + if a or (False): # SIM223 -8 | pass | note: This is an unsafe fix and may change runtime behavior @@ -63,10 +58,8 @@ SIM223 [*] Use `False` instead of `False and ...` | help: Replace with `False` | -18 | - - if a and f() and False and g() and b: # SIM223 +19 - if a and f() and False and g() and b: # SIM223 19 + if a and f() and False: # SIM223 -20 | pass | note: This is an unsafe fix and may change runtime behavior @@ -81,10 +74,8 @@ SIM223 [*] Use `False` instead of `False and ...` | help: Replace with `False` | -21 | - - if False and f() and a and g() and b: # SIM223 +22 - if False and f() and a and g() and b: # SIM223 22 + if False: # SIM223 -23 | pass | note: This is an unsafe fix and may change runtime behavior @@ -99,10 +90,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -24 | - - if a and False and f() and b and g(): # SIM223 +25 - if a and False and f() and b and g(): # SIM223 25 + if False: # SIM223 -26 | pass | note: This is an unsafe fix and may change runtime behavior @@ -116,10 +105,8 @@ SIM223 [*] Use `""` instead of `"" and ...` | help: Replace with `""` | -41 | - - a and "" and False # SIM223 +42 - a and "" and False # SIM223 42 + a and "" # SIM223 -43 | | note: This is an unsafe fix and may change runtime behavior @@ -135,10 +122,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -43 | - - a and "foo" and False and "bar" # SIM223 +44 - a and "foo" and False and "bar" # SIM223 44 + a and False # SIM223 -45 | | note: This is an unsafe fix and may change runtime behavior @@ -154,10 +139,8 @@ SIM223 [*] Use `0` instead of `0 and ...` | help: Replace with `0` | -45 | - - a and 0 and False # SIM223 +46 - a and 0 and False # SIM223 46 + a and 0 # SIM223 -47 | | note: This is an unsafe fix and may change runtime behavior @@ -173,10 +156,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -47 | - - a and 1 and False and 2 # SIM223 +48 - a and 1 and False and 2 # SIM223 48 + a and False # SIM223 -49 | | note: This is an unsafe fix and may change runtime behavior @@ -192,10 +173,8 @@ SIM223 [*] Use `0.0` instead of `0.0 and ...` | help: Replace with `0.0` | -49 | - - a and 0.0 and False # SIM223 +50 - a and 0.0 and False # SIM223 50 + a and 0.0 # SIM223 -51 | | note: This is an unsafe fix and may change runtime behavior @@ -211,10 +190,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -51 | - - a and 0.1 and False and 0.2 # SIM223 +52 - a and 0.1 and False and 0.2 # SIM223 52 + a and False # SIM223 -53 | | note: This is an unsafe fix and may change runtime behavior @@ -230,10 +207,8 @@ SIM223 [*] Use `[]` instead of `[] and ...` | help: Replace with `[]` | -53 | - - a and [] and False # SIM223 +54 - a and [] and False # SIM223 54 + a and [] # SIM223 -55 | | note: This is an unsafe fix and may change runtime behavior @@ -249,10 +224,8 @@ SIM223 [*] Use `list([])` instead of `list([]) and ...` | help: Replace with `list([])` | -55 | - - a and list([]) and False # SIM223 +56 - a and list([]) and False # SIM223 56 + a and list([]) # SIM223 -57 | | note: This is an unsafe fix and may change runtime behavior @@ -268,10 +241,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -57 | - - a and [1] and False and [2] # SIM223 +58 - a and [1] and False and [2] # SIM223 58 + a and False # SIM223 -59 | | note: This is an unsafe fix and may change runtime behavior @@ -287,10 +258,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -59 | - - a and list([1]) and False and list([2]) # SIM223 +60 - a and list([1]) and False and list([2]) # SIM223 60 + a and False # SIM223 -61 | | note: This is an unsafe fix and may change runtime behavior @@ -306,10 +275,8 @@ SIM223 [*] Use `{}` instead of `{} and ...` | help: Replace with `{}` | -61 | - - a and {} and False # SIM223 +62 - a and {} and False # SIM223 62 + a and {} # SIM223 -63 | | note: This is an unsafe fix and may change runtime behavior @@ -325,10 +292,8 @@ SIM223 [*] Use `dict()` instead of `dict() and ...` | help: Replace with `dict()` | -63 | - - a and dict() and False # SIM223 +64 - a and dict() and False # SIM223 64 + a and dict() # SIM223 -65 | | note: This is an unsafe fix and may change runtime behavior @@ -344,10 +309,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -65 | - - a and {1: 1} and False and {2: 2} # SIM223 +66 - a and {1: 1} and False and {2: 2} # SIM223 66 + a and False # SIM223 -67 | | note: This is an unsafe fix and may change runtime behavior @@ -363,10 +326,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -67 | - - a and dict({1: 1}) and False and dict({2: 2}) # SIM223 +68 - a and dict({1: 1}) and False and dict({2: 2}) # SIM223 68 + a and False # SIM223 -69 | | note: This is an unsafe fix and may change runtime behavior @@ -382,10 +343,8 @@ SIM223 [*] Use `set()` instead of `set() and ...` | help: Replace with `set()` | -69 | - - a and set() and False # SIM223 +70 - a and set() and False # SIM223 70 + a and set() # SIM223 -71 | | note: This is an unsafe fix and may change runtime behavior @@ -401,10 +360,8 @@ SIM223 [*] Use `set(set())` instead of `set(set()) and ...` | help: Replace with `set(set())` | -71 | - - a and set(set()) and False # SIM223 +72 - a and set(set()) and False # SIM223 72 + a and set(set()) # SIM223 -73 | | note: This is an unsafe fix and may change runtime behavior @@ -420,10 +377,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -73 | - - a and {1} and False and {2} # SIM223 +74 - a and {1} and False and {2} # SIM223 74 + a and False # SIM223 -75 | | note: This is an unsafe fix and may change runtime behavior @@ -439,10 +394,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -75 | - - a and set({1}) and False and set({2}) # SIM223 +76 - a and set({1}) and False and set({2}) # SIM223 76 + a and False # SIM223 -77 | | note: This is an unsafe fix and may change runtime behavior @@ -458,10 +411,8 @@ SIM223 [*] Use `()` instead of `() and ...` | help: Replace with `()` | -77 | - - a and () and False # SIM222 +78 - a and () and False # SIM222 78 + a and () # SIM222 -79 | | note: This is an unsafe fix and may change runtime behavior @@ -477,10 +428,8 @@ SIM223 [*] Use `tuple(())` instead of `tuple(()) and ...` | help: Replace with `tuple(())` | -79 | - - a and tuple(()) and False # SIM222 +80 - a and tuple(()) and False # SIM222 80 + a and tuple(()) # SIM222 -81 | | note: This is an unsafe fix and may change runtime behavior @@ -496,10 +445,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -81 | - - a and (1,) and False and (2,) # SIM222 +82 - a and (1,) and False and (2,) # SIM222 82 + a and False # SIM222 -83 | | note: This is an unsafe fix and may change runtime behavior @@ -515,10 +462,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -83 | - - a and tuple((1,)) and False and tuple((2,)) # SIM222 +84 - a and tuple((1,)) and False and tuple((2,)) # SIM222 84 + a and False # SIM222 -85 | | note: This is an unsafe fix and may change runtime behavior @@ -534,10 +479,8 @@ SIM223 [*] Use `frozenset()` instead of `frozenset() and ...` | help: Replace with `frozenset()` | -85 | - - a and frozenset() and False # SIM222 +86 - a and frozenset() and False # SIM222 86 + a and frozenset() # SIM222 -87 | | note: This is an unsafe fix and may change runtime behavior @@ -553,10 +496,8 @@ SIM223 [*] Use `frozenset(frozenset())` instead of `frozenset(frozenset()) and . | help: Replace with `frozenset(frozenset())` | -87 | - - a and frozenset(frozenset()) and False # SIM222 +88 - a and frozenset(frozenset()) and False # SIM222 88 + a and frozenset(frozenset()) # SIM222 -89 | | note: This is an unsafe fix and may change runtime behavior @@ -572,10 +513,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -89 | - - a and frozenset({1}) and False and frozenset({2}) # SIM222 +90 - a and frozenset({1}) and False and frozenset({2}) # SIM222 90 + a and False # SIM222 -91 | | note: This is an unsafe fix and may change runtime behavior @@ -588,10 +527,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `False` | -91 | - - a and frozenset(frozenset({1})) and False and frozenset(frozenset({2})) # SIM222 +92 - a and frozenset(frozenset({1})) and False and frozenset(frozenset({2})) # SIM222 92 + a and False # SIM222 -93 | | note: This is an unsafe fix and may change runtime behavior @@ -607,10 +544,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -96 | - - bool(a and [] and False and []) # SIM223 +97 - bool(a and [] and False and []) # SIM223 97 + bool(False) # SIM223 -98 | | note: This is an unsafe fix and may change runtime behavior @@ -625,12 +560,10 @@ SIM223 [*] Use `False` instead of `... and False and ...` 101 | if (a and [] and False and []) or (a and [] and False and []): # SIM223 | help: Replace with `False` - | -98 | - - assert a and [] and False and [] # SIM223 -99 + assert False # SIM223 -100 | - | + | +99 - assert a and [] and False and [] # SIM223 +99 + assert False # SIM223 + | note: This is an unsafe fix and may change runtime behavior SIM223 [*] Use `False` instead of `... and False and ...` @@ -644,10 +577,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -100 | - - if (a and [] and False and []) or (a and [] and False and []): # SIM223 +101 - if (a and [] and False and []) or (a and [] and False and []): # SIM223 101 + if (False) or (a and [] and False and []): # SIM223 -102 | pass | note: This is an unsafe fix and may change runtime behavior @@ -662,10 +593,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -100 | - - if (a and [] and False and []) or (a and [] and False and []): # SIM223 +101 - if (a and [] and False and []) or (a and [] and False and []): # SIM223 101 + if (a and [] and False and []) or (False): # SIM223 -102 | pass | note: This is an unsafe fix and may change runtime behavior @@ -681,10 +610,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -103 | - - 0 if a and [] and False and [] else 1 # SIM222 +104 - 0 if a and [] and False and [] else 1 # SIM222 104 + 0 if False else 1 # SIM222 -105 | | note: This is an unsafe fix and may change runtime behavior @@ -699,10 +626,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -105 | - - while a and [] and False and []: # SIM223 +106 - while a and [] and False and []: # SIM223 106 + while False: # SIM223 -107 | pass | note: This is an unsafe fix and may change runtime behavior @@ -718,10 +643,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -112 | for b in range(10) - - if a and [] and False and [] # SIM223 +113 - if a and [] and False and [] # SIM223 113 + if False # SIM223 -114 | if b and [] and False and [] # SIM223 | note: This is an unsafe fix and may change runtime behavior @@ -736,10 +659,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -113 | if a and [] and False and [] # SIM223 - - if b and [] and False and [] # SIM223 +114 - if b and [] and False and [] # SIM223 114 + if False # SIM223 -115 | ] | note: This is an unsafe fix and may change runtime behavior @@ -755,10 +676,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -120 | for b in range(10) - - if a and [] and False and [] # SIM223 +121 - if a and [] and False and [] # SIM223 121 + if False # SIM223 -122 | if b and [] and False and [] # SIM223 | note: This is an unsafe fix and may change runtime behavior @@ -773,10 +692,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -121 | if a and [] and False and [] # SIM223 - - if b and [] and False and [] # SIM223 +122 - if b and [] and False and [] # SIM223 122 + if False # SIM223 -123 | } | note: This is an unsafe fix and may change runtime behavior @@ -792,10 +709,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -128 | for b in range(10) - - if a and [] and False and [] # SIM223 +129 - if a and [] and False and [] # SIM223 129 + if False # SIM223 -130 | if b and [] and False and [] # SIM223 | note: This is an unsafe fix and may change runtime behavior @@ -810,10 +725,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -129 | if a and [] and False and [] # SIM223 - - if b and [] and False and [] # SIM223 +130 - if b and [] and False and [] # SIM223 130 + if False # SIM223 -131 | } | note: This is an unsafe fix and may change runtime behavior @@ -829,10 +742,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -136 | for b in range(10) - - if a and [] and False and [] # SIM223 +137 - if a and [] and False and [] # SIM223 137 + if False # SIM223 -138 | if b and [] and False and [] # SIM223 | note: This is an unsafe fix and may change runtime behavior @@ -847,10 +758,8 @@ SIM223 [*] Use `False` instead of `... and False and ...` | help: Replace with `False` | -137 | if a and [] and False and [] # SIM223 - - if b and [] and False and [] # SIM223 +138 - if b and [] and False and [] # SIM223 138 + if False # SIM223 -139 | ) | note: This is an unsafe fix and may change runtime behavior @@ -866,10 +775,8 @@ SIM223 [*] Use `[]` instead of `[] and ...` | help: Replace with `[]` | -142 | - - a and [] and False and [] # SIM223 +143 - a and [] and False and [] # SIM223 143 + a and [] # SIM223 -144 | | note: This is an unsafe fix and may change runtime behavior @@ -884,10 +791,8 @@ SIM223 [*] Use `[]` instead of `[] and ...` | help: Replace with `[]` | -144 | - - if (a and [] and False and []) == (a and []): # SIM223 +145 - if (a and [] and False and []) == (a and []): # SIM223 145 + if (a and []) == (a and []): # SIM223 -146 | pass | note: This is an unsafe fix and may change runtime behavior @@ -902,10 +807,8 @@ SIM223 [*] Use `[]` instead of `[] and ...` | help: Replace with `[]` | -147 | - - if f(a and [] and False and []): # SIM223 +148 - if f(a and [] and False and []): # SIM223 148 + if f(a and []): # SIM223 -149 | pass | note: This is an unsafe fix and may change runtime behavior @@ -920,10 +823,8 @@ SIM223 [*] Use `f"{''}{''}"` instead of `f"{''}{''}" and ...` | help: Replace with `f"{''}{''}"` | -153 | print(f"{a}{''}" and "bar") - - print(f"{''}{''}" and "bar") +154 - print(f"{''}{''}" and "bar") 154 + print(f"{''}{''}") -155 | print(f"{1}{''}" and "bar") | note: This is an unsafe fix and may change runtime behavior @@ -938,9 +839,7 @@ SIM223 [*] Use `tuple("")` instead of `tuple("") and ...` | help: Replace with `tuple("")` | -162 | # https://github.com/astral-sh/ruff/issues/21473 - - tuple("") and False # SIM223 +163 - tuple("") and False # SIM223 163 + tuple("") # SIM223 -164 | tuple(t"") and False # OK | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM300_SIM300.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM300_SIM300.py.snap index 93dcbd79f866d..5d4e2903a3382 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM300_SIM300.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM300_SIM300.py.snap @@ -12,10 +12,8 @@ SIM300 [*] Yoda condition detected | help: Rewrite as `compare == "yoda"` | -1 | # Errors - - "yoda" == compare # SIM300 +2 - "yoda" == compare # SIM300 2 + compare == "yoda" # SIM300 -3 | 42 == age # SIM300 | SIM300 [*] Yoda condition detected @@ -30,10 +28,8 @@ SIM300 [*] Yoda condition detected | help: Rewrite as `age == 42` | -2 | "yoda" == compare # SIM300 - - 42 == age # SIM300 +3 - 42 == age # SIM300 3 + age == 42 # SIM300 -4 | ("a", "b") == compare # SIM300 | SIM300 [*] Yoda condition detected @@ -48,10 +44,8 @@ SIM300 [*] Yoda condition detected | help: Rewrite as `compare == ("a", "b")` | -3 | 42 == age # SIM300 - - ("a", "b") == compare # SIM300 +4 - ("a", "b") == compare # SIM300 4 + compare == ("a", "b") # SIM300 -5 | "yoda" <= compare # SIM300 | SIM300 [*] Yoda condition detected @@ -66,10 +60,8 @@ SIM300 [*] Yoda condition detected | help: Rewrite as `compare >= "yoda"` | -4 | ("a", "b") == compare # SIM300 - - "yoda" <= compare # SIM300 +5 - "yoda" <= compare # SIM300 5 + compare >= "yoda" # SIM300 -6 | "yoda" < compare # SIM300 | SIM300 [*] Yoda condition detected @@ -84,10 +76,8 @@ SIM300 [*] Yoda condition detected | help: Rewrite as `compare > "yoda"` | -5 | "yoda" <= compare # SIM300 - - "yoda" < compare # SIM300 +6 - "yoda" < compare # SIM300 6 + compare > "yoda" # SIM300 -7 | 42 > age # SIM300 | SIM300 [*] Yoda condition detected @@ -102,10 +92,8 @@ SIM300 [*] Yoda condition detected | help: Rewrite as `age < 42` | -6 | "yoda" < compare # SIM300 - - 42 > age # SIM300 +7 - 42 > age # SIM300 7 + age < 42 # SIM300 -8 | -42 > age # SIM300 | SIM300 [*] Yoda condition detected @@ -120,10 +108,8 @@ SIM300 [*] Yoda condition detected | help: Rewrite as `age < -42` | -7 | 42 > age # SIM300 - - -42 > age # SIM300 +8 - -42 > age # SIM300 8 + age < -42 # SIM300 -9 | +42 > age # SIM300 | SIM300 [*] Yoda condition detected @@ -137,12 +123,10 @@ SIM300 [*] Yoda condition detected 11 | YODA > age # SIM300 | help: Rewrite as `age < +42` - | -8 | -42 > age # SIM300 - - +42 > age # SIM300 -9 + age < +42 # SIM300 -10 | YODA == age # SIM300 - | + | +9 - +42 > age # SIM300 +9 + age < +42 # SIM300 + | SIM300 [*] Yoda condition detected --> SIM300.py:10:1 @@ -156,10 +140,8 @@ SIM300 [*] Yoda condition detected | help: Rewrite as `age == YODA` | -9 | +42 > age # SIM300 - - YODA == age # SIM300 +10 - YODA == age # SIM300 10 + age == YODA # SIM300 -11 | YODA > age # SIM300 | SIM300 [*] Yoda condition detected @@ -174,10 +156,8 @@ SIM300 [*] Yoda condition detected | help: Rewrite as `age < YODA` | -10 | YODA == age # SIM300 - - YODA > age # SIM300 +11 - YODA > age # SIM300 11 + age < YODA # SIM300 -12 | YODA >= age # SIM300 | SIM300 [*] Yoda condition detected @@ -192,10 +172,8 @@ SIM300 [*] Yoda condition detected | help: Rewrite as `age <= YODA` | -11 | YODA > age # SIM300 - - YODA >= age # SIM300 +12 - YODA >= age # SIM300 12 + age <= YODA # SIM300 -13 | JediOrder.YODA == age # SIM300 | SIM300 [*] Yoda condition detected @@ -210,10 +188,8 @@ SIM300 [*] Yoda condition detected | help: Rewrite as `age == JediOrder.YODA` | -12 | YODA >= age # SIM300 - - JediOrder.YODA == age # SIM300 +13 - JediOrder.YODA == age # SIM300 13 + age == JediOrder.YODA # SIM300 -14 | 0 < (number - 100) # SIM300 | SIM300 [*] Yoda condition detected @@ -228,10 +204,8 @@ SIM300 [*] Yoda condition detected | help: Rewrite as `(number - 100) > 0` | -13 | JediOrder.YODA == age # SIM300 - - 0 < (number - 100) # SIM300 +14 - 0 < (number - 100) # SIM300 14 + (number - 100) > 0 # SIM300 -15 | B B` | -14 | 0 < (number - 100) # SIM300 - - B B or B -16 | B or(B) (B)` | -15 | B (B) -17 | {"non-empty-dict": "is-ok"} == DummyHandler.CONFIG | SIM300 [*] Yoda condition detected @@ -281,10 +251,8 @@ SIM300 [*] Yoda condition detected | help: Rewrite as `DummyHandler.CONFIG == {"non-empty-dict": "is-ok"}` | -16 | B or(B) SIM905.py:12:1 @@ -38,10 +36,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -11 | - - "a,b,c,d".split(",") +12 - "a,b,c,d".split(",") 12 + ["a", "b", "c", "d"] -13 | "a,b,c,d".split(None) | SIM905 [*] Consider using a list literal instead of `str.split` @@ -55,10 +51,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -12 | "a,b,c,d".split(",") - - "a,b,c,d".split(None) +13 - "a,b,c,d".split(None) 13 + ["a,b,c,d"] -14 | "a,b,c,d".split(",", 1) | SIM905 [*] Consider using a list literal instead of `str.split` @@ -73,10 +67,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -13 | "a,b,c,d".split(None) - - "a,b,c,d".split(",", 1) +14 - "a,b,c,d".split(",", 1) 14 + ["a", "b,c,d"] -15 | "a,b,c,d".split(None, 1) | SIM905 [*] Consider using a list literal instead of `str.split` @@ -91,10 +83,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -14 | "a,b,c,d".split(",", 1) - - "a,b,c,d".split(None, 1) +15 - "a,b,c,d".split(None, 1) 15 + ["a,b,c,d"] -16 | "a,b,c,d".split(sep=",") | SIM905 [*] Consider using a list literal instead of `str.split` @@ -109,10 +99,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -15 | "a,b,c,d".split(None, 1) - - "a,b,c,d".split(sep=",") +16 - "a,b,c,d".split(sep=",") 16 + ["a", "b", "c", "d"] -17 | "a,b,c,d".split(sep=None) | SIM905 [*] Consider using a list literal instead of `str.split` @@ -127,10 +115,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -16 | "a,b,c,d".split(sep=",") - - "a,b,c,d".split(sep=None) +17 - "a,b,c,d".split(sep=None) 17 + ["a,b,c,d"] -18 | "a,b,c,d".split(sep=",", maxsplit=1) | SIM905 [*] Consider using a list literal instead of `str.split` @@ -145,10 +131,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -17 | "a,b,c,d".split(sep=None) - - "a,b,c,d".split(sep=",", maxsplit=1) +18 - "a,b,c,d".split(sep=",", maxsplit=1) 18 + ["a", "b,c,d"] -19 | "a,b,c,d".split(sep=None, maxsplit=1) | SIM905 [*] Consider using a list literal instead of `str.split` @@ -163,10 +147,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -18 | "a,b,c,d".split(sep=",", maxsplit=1) - - "a,b,c,d".split(sep=None, maxsplit=1) +19 - "a,b,c,d".split(sep=None, maxsplit=1) 19 + ["a,b,c,d"] -20 | "a,b,c,d".split(maxsplit=1, sep=",") | SIM905 [*] Consider using a list literal instead of `str.split` @@ -181,10 +163,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -19 | "a,b,c,d".split(sep=None, maxsplit=1) - - "a,b,c,d".split(maxsplit=1, sep=",") +20 - "a,b,c,d".split(maxsplit=1, sep=",") 20 + ["a", "b,c,d"] -21 | "a,b,c,d".split(maxsplit=1, sep=None) | SIM905 [*] Consider using a list literal instead of `str.split` @@ -199,10 +179,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -20 | "a,b,c,d".split(maxsplit=1, sep=",") - - "a,b,c,d".split(maxsplit=1, sep=None) +21 - "a,b,c,d".split(maxsplit=1, sep=None) 21 + ["a,b,c,d"] -22 | "a,b,c,d".split(",", maxsplit=1) | SIM905 [*] Consider using a list literal instead of `str.split` @@ -217,10 +195,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -21 | "a,b,c,d".split(maxsplit=1, sep=None) - - "a,b,c,d".split(",", maxsplit=1) +22 - "a,b,c,d".split(",", maxsplit=1) 22 + ["a", "b,c,d"] -23 | "a,b,c,d".split(None, maxsplit=1) | SIM905 [*] Consider using a list literal instead of `str.split` @@ -235,10 +211,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -22 | "a,b,c,d".split(",", maxsplit=1) - - "a,b,c,d".split(None, maxsplit=1) +23 - "a,b,c,d".split(None, maxsplit=1) 23 + ["a,b,c,d"] -24 | "a,b,c,d".split(maxsplit=1) | SIM905 [*] Consider using a list literal instead of `str.split` @@ -253,10 +227,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -23 | "a,b,c,d".split(None, maxsplit=1) - - "a,b,c,d".split(maxsplit=1) +24 - "a,b,c,d".split(maxsplit=1) 24 + ["a,b,c,d"] -25 | "a,b,c,d".split(maxsplit=1.0) | SIM905 [*] Consider using a list literal instead of `str.split` @@ -271,10 +243,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -25 | "a,b,c,d".split(maxsplit=1.0) - - "a,b,c,d".split(maxsplit=1) +26 - "a,b,c,d".split(maxsplit=1) 26 + ["a,b,c,d"] -27 | "a,b,c,d".split(maxsplit=0) | SIM905 [*] Consider using a list literal instead of `str.split` @@ -289,10 +259,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -26 | "a,b,c,d".split(maxsplit=1) - - "a,b,c,d".split(maxsplit=0) +27 - "a,b,c,d".split(maxsplit=0) 27 + ["a,b,c,d"] -28 | "VERB AUX PRON ADP DET".split(" ") | SIM905 [*] Consider using a list literal instead of `str.split` @@ -307,10 +275,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -27 | "a,b,c,d".split(maxsplit=0) - - "VERB AUX PRON ADP DET".split(" ") +28 - "VERB AUX PRON ADP DET".split(" ") 28 + ["VERB", "AUX", "PRON", "ADP", "DET"] -29 | ' 1 2 3 '.split() | SIM905 [*] Consider using a list literal instead of `str.split` @@ -324,10 +290,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -28 | "VERB AUX PRON ADP DET".split(" ") - - ' 1 2 3 '.split() +29 - ' 1 2 3 '.split() 29 + ['1', '2', '3'] -30 | '1<>2<>3<4'.split('<>') | SIM905 [*] Consider using a list literal instead of `str.split` @@ -342,10 +306,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -29 | ' 1 2 3 '.split() - - '1<>2<>3<4'.split('<>') +30 - '1<>2<>3<4'.split('<>') 30 + ['1', '2', '3<4'] -31 | | SIM905 [*] Consider using a list literal instead of `str.split` @@ -360,10 +322,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -31 | - - " a*a a*a a ".split("*", -1) # [" a", "a a", "a a "] +32 - " a*a a*a a ".split("*", -1) # [" a", "a a", "a a "] 32 + [" a", "a a", "a a "] # [" a", "a a", "a a "] -33 | "".split() # [] | SIM905 [*] Consider using a list literal instead of `str.split` @@ -377,10 +337,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -32 | " a*a a*a a ".split("*", -1) # [" a", "a a", "a a "] - - "".split() # [] +33 - "".split() # [] 33 + [] # [] -34 | """ | SIM905 [*] Consider using a list literal instead of `str.split` @@ -396,11 +354,9 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -33 | "".split() # [] - - """ - - """.split() # [] +34 - """ +35 - """.split() # [] 34 + [] # [] -35 | " ".split() # [] | SIM905 [*] Consider using a list literal instead of `str.split` @@ -415,10 +371,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -35 | """.split() # [] - - " ".split() # [] +36 - " ".split() # [] 36 + [] # [] -37 | "/abc/".split() # ["/abc/"] | SIM905 [*] Consider using a list literal instead of `str.split` @@ -433,10 +387,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -36 | " ".split() # [] - - "/abc/".split() # ["/abc/"] +37 - "/abc/".split() # ["/abc/"] 37 + ["/abc/"] # ["/abc/"] -38 | ("a,b,c" | SIM905 [*] Consider using a list literal instead of `str.split` @@ -454,12 +406,10 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -37 | "/abc/".split() # ["/abc/"] - - ("a,b,c" - - # comment - - .split() +38 - ("a,b,c" +39 - # comment +40 - .split() 38 + (["a,b,c"] -39 | ) # ["a,b,c"] | note: This is an unsafe fix and may change runtime behavior @@ -478,12 +428,10 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -41 | ) # ["a,b,c"] - - ("a,b,c" - - # comment1 - - .split(",") +42 - ("a,b,c" +43 - # comment1 +44 - .split(",") 42 + (["a", "b", "c"] -43 | ) # ["a", "b", "c"] | note: This is an unsafe fix and may change runtime behavior @@ -503,14 +451,12 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -45 | ) # ["a", "b", "c"] - - ("a," - - # comment - - "b," - - "c" - - .split(",") +46 - ("a," +47 - # comment +48 - "b," +49 - "c" +50 - .split(",") 46 + (["a", "b", "c"] -47 | ) # ["a", "b", "c"] | note: This is an unsafe fix and may change runtime behavior @@ -526,11 +472,9 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -52 | - - "hello "\ - - "world".split() +53 - "hello "\ +54 - "world".split() 53 + ["hello", "world"] -54 | # ["hello", "world"] | SIM905 [*] Consider using a list literal instead of `str.split` @@ -544,10 +488,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -57 | # prefixes and isc - - u"a b".split() # [u"a", u"b"] +58 - u"a b".split() # [u"a", u"b"] 58 + [u"a", u"b"] # [u"a", u"b"] -59 | r"a \n b".split() # [r"a", r"\n", r"b"] | SIM905 [*] Consider using a list literal instead of `str.split` @@ -562,10 +504,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -58 | u"a b".split() # [u"a", u"b"] - - r"a \n b".split() # [r"a", r"\n", r"b"] +59 - r"a \n b".split() # [r"a", r"\n", r"b"] 59 + [r"a", r"\n", r"b"] # [r"a", r"\n", r"b"] -60 | ("a " "b").split() # ["a", "b"] | SIM905 [*] Consider using a list literal instead of `str.split` @@ -580,10 +520,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -59 | r"a \n b".split() # [r"a", r"\n", r"b"] - - ("a " "b").split() # ["a", "b"] +60 - ("a " "b").split() # ["a", "b"] 60 + ["a", "b"] # ["a", "b"] -61 | "a " "b".split() # ["a", "b"] | SIM905 [*] Consider using a list literal instead of `str.split` @@ -598,10 +536,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -60 | ("a " "b").split() # ["a", "b"] - - "a " "b".split() # ["a", "b"] +61 - "a " "b".split() # ["a", "b"] 61 + ["a", "b"] # ["a", "b"] -62 | u"a " "b".split() # [u"a", u"b"] | SIM905 [*] Consider using a list literal instead of `str.split` @@ -616,10 +552,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -61 | "a " "b".split() # ["a", "b"] - - u"a " "b".split() # [u"a", u"b"] +62 - u"a " "b".split() # [u"a", u"b"] 62 + [u"a", u"b"] # [u"a", u"b"] -63 | "a " u"b".split() # ["a", "b"] | SIM905 [*] Consider using a list literal instead of `str.split` @@ -634,10 +568,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -62 | u"a " "b".split() # [u"a", u"b"] - - "a " u"b".split() # ["a", "b"] +63 - "a " u"b".split() # ["a", "b"] 63 + ["a", "b"] # ["a", "b"] -64 | u"a " r"\n".split() # [u"a", u"\\n"] | SIM905 [*] Consider using a list literal instead of `str.split` @@ -652,10 +584,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -63 | "a " u"b".split() # ["a", "b"] - - u"a " r"\n".split() # [u"a", u"\\n"] +64 - u"a " r"\n".split() # [u"a", u"\\n"] 64 + [u"a", u"\\n"] # [u"a", u"\\n"] -65 | r"\n " u"\n".split() # [r"\n"] | SIM905 [*] Consider using a list literal instead of `str.split` @@ -670,10 +600,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -64 | u"a " r"\n".split() # [u"a", u"\\n"] - - r"\n " u"\n".split() # [r"\n"] +65 - r"\n " u"\n".split() # [r"\n"] 65 + [r"\n"] # [r"\n"] -66 | r"\n " "\n".split() # [r"\n"] | SIM905 [*] Consider using a list literal instead of `str.split` @@ -687,10 +615,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -65 | r"\n " u"\n".split() # [r"\n"] - - r"\n " "\n".split() # [r"\n"] +66 - r"\n " "\n".split() # [r"\n"] 66 + [r"\n"] # [r"\n"] -67 | "a " r"\n".split() # ["a", "\\n"] | SIM905 [*] Consider using a list literal instead of `str.split` @@ -705,10 +631,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -66 | r"\n " "\n".split() # [r"\n"] - - "a " r"\n".split() # ["a", "\\n"] +67 - "a " r"\n".split() # ["a", "\\n"] 67 + ["a", "\\n"] # ["a", "\\n"] -68 | | SIM905 [*] Consider using a list literal instead of `str.split` @@ -723,10 +647,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -68 | - - "a,b,c".split(',', maxsplit=0) # ["a,b,c"] +69 - "a,b,c".split(',', maxsplit=0) # ["a,b,c"] 69 + ["a,b,c"] # ["a,b,c"] -70 | "a,b,c".split(',', maxsplit=-1) # ["a", "b", "c"] | SIM905 [*] Consider using a list literal instead of `str.split` @@ -740,10 +662,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -69 | "a,b,c".split(',', maxsplit=0) # ["a,b,c"] - - "a,b,c".split(',', maxsplit=-1) # ["a", "b", "c"] +70 - "a,b,c".split(',', maxsplit=-1) # ["a", "b", "c"] 70 + ["a", "b", "c"] # ["a", "b", "c"] -71 | "a,b,c".split(',', maxsplit=-2) # ["a", "b", "c"] | SIM905 [*] Consider using a list literal instead of `str.split` @@ -757,10 +677,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -70 | "a,b,c".split(',', maxsplit=-1) # ["a", "b", "c"] - - "a,b,c".split(',', maxsplit=-2) # ["a", "b", "c"] +71 - "a,b,c".split(',', maxsplit=-2) # ["a", "b", "c"] 71 + ["a", "b", "c"] # ["a", "b", "c"] -72 | "a,b,c".split(',', maxsplit=-0) # ["a,b,c"] | SIM905 [*] Consider using a list literal instead of `str.split` @@ -775,10 +693,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -71 | "a,b,c".split(',', maxsplit=-2) # ["a", "b", "c"] - - "a,b,c".split(',', maxsplit=-0) # ["a,b,c"] +72 - "a,b,c".split(',', maxsplit=-0) # ["a,b,c"] 72 + ["a,b,c"] # ["a,b,c"] -73 | | SIM905 [*] Consider using a list literal instead of `str.split` @@ -797,15 +713,13 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -102 | # another positive demonstrating quote preservation - - """ - - "itemA" - - 'itemB' - - '''itemC''' - - "'itemD'" - - """.split() +103 - """ +104 - "itemA" +105 - 'itemB' +106 - '''itemC''' +107 - "'itemD'" +108 - """.split() 103 + ['"itemA"', "'itemB'", "'''itemC'''", "\"'itemD'\""] -104 | | SIM905 [*] Consider using a list literal instead of `str.rsplit` @@ -818,10 +732,8 @@ SIM905 [*] Consider using a list literal instead of `str.rsplit` | help: Replace with list literal | -110 | # https://github.com/astral-sh/ruff/issues/18042 - - print("a,b".rsplit(",")) +111 - print("a,b".rsplit(",")) 111 + print(["a", "b"]) -112 | print("a,b,c".rsplit(",", 1)) | SIM905 [*] Consider using a list literal instead of `str.rsplit` @@ -836,10 +748,8 @@ SIM905 [*] Consider using a list literal instead of `str.rsplit` | help: Replace with list literal | -111 | print("a,b".rsplit(",")) - - print("a,b,c".rsplit(",", 1)) +112 - print("a,b,c".rsplit(",", 1)) 112 + print(["a,b", "c"]) -113 | | SIM905 [*] Consider using a list literal instead of `str.split` @@ -854,10 +764,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -115 | - - print("".split(maxsplit=0)) +116 - print("".split(maxsplit=0)) 116 + print([]) -117 | print("".split(sep=None, maxsplit=0)) | SIM905 [*] Consider using a list literal instead of `str.split` @@ -871,10 +779,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -116 | print("".split(maxsplit=0)) - - print("".split(sep=None, maxsplit=0)) +117 - print("".split(sep=None, maxsplit=0)) 117 + print([]) -118 | print(" ".split(maxsplit=0)) | SIM905 [*] Consider using a list literal instead of `str.split` @@ -889,10 +795,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -117 | print("".split(sep=None, maxsplit=0)) - - print(" ".split(maxsplit=0)) +118 - print(" ".split(maxsplit=0)) 118 + print([]) -119 | print(" ".split(sep=None, maxsplit=0)) | SIM905 [*] Consider using a list literal instead of `str.split` @@ -907,10 +811,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -118 | print(" ".split(maxsplit=0)) - - print(" ".split(sep=None, maxsplit=0)) +119 - print(" ".split(sep=None, maxsplit=0)) 119 + print([]) -120 | print(" x ".split(maxsplit=0)) | SIM905 [*] Consider using a list literal instead of `str.split` @@ -925,10 +827,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -119 | print(" ".split(sep=None, maxsplit=0)) - - print(" x ".split(maxsplit=0)) +120 - print(" x ".split(maxsplit=0)) 120 + print(["x "]) -121 | print(" x ".split(sep=None, maxsplit=0)) | SIM905 [*] Consider using a list literal instead of `str.split` @@ -943,10 +843,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -120 | print(" x ".split(maxsplit=0)) - - print(" x ".split(sep=None, maxsplit=0)) +121 - print(" x ".split(sep=None, maxsplit=0)) 121 + print(["x "]) -122 | print(" x ".split(maxsplit=0)) | SIM905 [*] Consider using a list literal instead of `str.split` @@ -961,10 +859,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -121 | print(" x ".split(sep=None, maxsplit=0)) - - print(" x ".split(maxsplit=0)) +122 - print(" x ".split(maxsplit=0)) 122 + print(["x "]) -123 | print(" x ".split(sep=None, maxsplit=0)) | SIM905 [*] Consider using a list literal instead of `str.split` @@ -979,10 +875,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -122 | print(" x ".split(maxsplit=0)) - - print(" x ".split(sep=None, maxsplit=0)) +123 - print(" x ".split(sep=None, maxsplit=0)) 123 + print(["x "]) -124 | print("".rsplit(maxsplit=0)) | SIM905 [*] Consider using a list literal instead of `str.rsplit` @@ -997,10 +891,8 @@ SIM905 [*] Consider using a list literal instead of `str.rsplit` | help: Replace with list literal | -123 | print(" x ".split(sep=None, maxsplit=0)) - - print("".rsplit(maxsplit=0)) +124 - print("".rsplit(maxsplit=0)) 124 + print([]) -125 | print("".rsplit(sep=None, maxsplit=0)) | SIM905 [*] Consider using a list literal instead of `str.rsplit` @@ -1015,10 +907,8 @@ SIM905 [*] Consider using a list literal instead of `str.rsplit` | help: Replace with list literal | -124 | print("".rsplit(maxsplit=0)) - - print("".rsplit(sep=None, maxsplit=0)) +125 - print("".rsplit(sep=None, maxsplit=0)) 125 + print([]) -126 | print(" ".rsplit(maxsplit=0)) | SIM905 [*] Consider using a list literal instead of `str.rsplit` @@ -1033,10 +923,8 @@ SIM905 [*] Consider using a list literal instead of `str.rsplit` | help: Replace with list literal | -125 | print("".rsplit(sep=None, maxsplit=0)) - - print(" ".rsplit(maxsplit=0)) +126 - print(" ".rsplit(maxsplit=0)) 126 + print([]) -127 | print(" ".rsplit(sep=None, maxsplit=0)) | SIM905 [*] Consider using a list literal instead of `str.rsplit` @@ -1051,10 +939,8 @@ SIM905 [*] Consider using a list literal instead of `str.rsplit` | help: Replace with list literal | -126 | print(" ".rsplit(maxsplit=0)) - - print(" ".rsplit(sep=None, maxsplit=0)) +127 - print(" ".rsplit(sep=None, maxsplit=0)) 127 + print([]) -128 | print(" x ".rsplit(maxsplit=0)) | SIM905 [*] Consider using a list literal instead of `str.rsplit` @@ -1069,10 +955,8 @@ SIM905 [*] Consider using a list literal instead of `str.rsplit` | help: Replace with list literal | -127 | print(" ".rsplit(sep=None, maxsplit=0)) - - print(" x ".rsplit(maxsplit=0)) +128 - print(" x ".rsplit(maxsplit=0)) 128 + print([" x"]) -129 | print(" x ".rsplit(maxsplit=0)) | SIM905 [*] Consider using a list literal instead of `str.rsplit` @@ -1087,10 +971,8 @@ SIM905 [*] Consider using a list literal instead of `str.rsplit` | help: Replace with list literal | -128 | print(" x ".rsplit(maxsplit=0)) - - print(" x ".rsplit(maxsplit=0)) +129 - print(" x ".rsplit(maxsplit=0)) 129 + print([" x"]) -130 | print(" x ".rsplit(sep=None, maxsplit=0)) | SIM905 [*] Consider using a list literal instead of `str.rsplit` @@ -1105,10 +987,8 @@ SIM905 [*] Consider using a list literal instead of `str.rsplit` | help: Replace with list literal | -129 | print(" x ".rsplit(maxsplit=0)) - - print(" x ".rsplit(sep=None, maxsplit=0)) +130 - print(" x ".rsplit(sep=None, maxsplit=0)) 130 + print([" x"]) -131 | print(" x ".rsplit(maxsplit=0)) | SIM905 [*] Consider using a list literal instead of `str.rsplit` @@ -1122,10 +1002,8 @@ SIM905 [*] Consider using a list literal instead of `str.rsplit` | help: Replace with list literal | -130 | print(" x ".rsplit(sep=None, maxsplit=0)) - - print(" x ".rsplit(maxsplit=0)) +131 - print(" x ".rsplit(maxsplit=0)) 131 + print([" x"]) -132 | print(" x ".rsplit(sep=None, maxsplit=0)) | SIM905 [*] Consider using a list literal instead of `str.rsplit` @@ -1140,10 +1018,8 @@ SIM905 [*] Consider using a list literal instead of `str.rsplit` | help: Replace with list literal | -131 | print(" x ".rsplit(maxsplit=0)) - - print(" x ".rsplit(sep=None, maxsplit=0)) +132 - print(" x ".rsplit(sep=None, maxsplit=0)) 132 + print([" x"]) -133 | | SIM905 [*] Consider using a list literal instead of `str.split` @@ -1176,32 +1052,30 @@ SIM905 [*] Consider using a list literal instead of `str.split` | |_______________________________________^ help: Replace with list literal | -134 | # https://github.com/astral-sh/ruff/issues/19581 - embedded quotes in raw strings - - r"""simple@example.com - - very.common@example.com - - FirstName.LastName@EasierReading.org - - x@example.com - - long.email-address-with-hyphens@and.subdomains.example.com - - user.name+tag+sorting@example.com - - name/surname@example.com - - xample@s.example - - " "@example.org - - "john..doe"@example.org - - mailhost!username@example.org - - "very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com - - user%example.com@example.org - - user-@example.org - - I❤️CHOCOLATE@example.com - - this\ still\"not\\allowed@example.com - - stellyamburrr985@example.com - - Abc.123@example.com - - user+mailbox/department=shipping@example.com - - !#$%&'*+-/=?^_`.{|}~@example.com - - "Abc@def"@example.com - - "Fred\ Bloggs"@example.com - - "Joe.\\Blow"@example.com""".split("\n") +135 - r"""simple@example.com +136 - very.common@example.com +137 - FirstName.LastName@EasierReading.org +138 - x@example.com +139 - long.email-address-with-hyphens@and.subdomains.example.com +140 - user.name+tag+sorting@example.com +141 - name/surname@example.com +142 - xample@s.example +143 - " "@example.org +144 - "john..doe"@example.org +145 - mailhost!username@example.org +146 - "very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com +147 - user%example.com@example.org +148 - user-@example.org +149 - I❤️CHOCOLATE@example.com +150 - this\ still\"not\\allowed@example.com +151 - stellyamburrr985@example.com +152 - Abc.123@example.com +153 - user+mailbox/department=shipping@example.com +154 - !#$%&'*+-/=?^_`.{|}~@example.com +155 - "Abc@def"@example.com +156 - "Fred\ Bloggs"@example.com +157 - "Joe.\\Blow"@example.com""".split("\n") 135 + [r"simple@example.com", r"very.common@example.com", r"FirstName.LastName@EasierReading.org", r"x@example.com", r"long.email-address-with-hyphens@and.subdomains.example.com", r"user.name+tag+sorting@example.com", r"name/surname@example.com", r"xample@s.example", r'" "@example.org', r'"john..doe"@example.org', r"mailhost!username@example.org", r'"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com', r"user%example.com@example.org", r"user-@example.org", r"I❤️CHOCOLATE@example.com", r'this\ still\"not\\allowed@example.com', r"stellyamburrr985@example.com", r"Abc.123@example.com", r"user+mailbox/department=shipping@example.com", r"!#$%&'*+-/=?^_`.{|}~@example.com", r'"Abc@def"@example.com', r'"Fred\ Bloggs"@example.com', r'"Joe.\\Blow"@example.com'] -136 | | SIM905 [*] Consider using a list literal instead of `str.split` @@ -1217,13 +1091,11 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -159 | - - r"""first - - 'no need' to escape - - "swap" quote style - - "use' ugly triple quotes""".split("\n") +160 - r"""first +161 - 'no need' to escape +162 - "swap" quote style +163 - "use' ugly triple quotes""".split("\n") 160 + [r"first", r"'no need' to escape", r'"swap" quote style', r""""use' ugly triple quotes"""] -161 | | SIM905 [*] Consider using a list literal instead of `str.split` @@ -1237,10 +1109,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -165 | # https://github.com/astral-sh/ruff/issues/19845 - - print("S\x1cP\x1dL\x1eI\x1fT".split()) +166 - print("S\x1cP\x1dL\x1eI\x1fT".split()) 166 + print(["S", "P", "L", "I", "T"]) -167 | print("\x1c\x1d\x1e\x1f>".split(maxsplit=0)) | SIM905 [*] Consider using a list literal instead of `str.split` @@ -1254,10 +1124,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -166 | print("S\x1cP\x1dL\x1eI\x1fT".split()) - - print("\x1c\x1d\x1e\x1f>".split(maxsplit=0)) +167 - print("\x1c\x1d\x1e\x1f>".split(maxsplit=0)) 167 + print([">"]) -168 | print("<\x1c\x1d\x1e\x1f".rsplit(maxsplit=0)) | SIM905 [*] Consider using a list literal instead of `str.rsplit` @@ -1272,10 +1140,8 @@ SIM905 [*] Consider using a list literal instead of `str.rsplit` | help: Replace with list literal | -167 | print("\x1c\x1d\x1e\x1f>".split(maxsplit=0)) - - print("<\x1c\x1d\x1e\x1f".rsplit(maxsplit=0)) +168 - print("<\x1c\x1d\x1e\x1f".rsplit(maxsplit=0)) 168 + print(["<"]) -169 | | SIM905 [*] Consider using a list literal instead of `str.split` @@ -1289,10 +1155,8 @@ SIM905 [*] Consider using a list literal instead of `str.split` | help: Replace with list literal | -170 | # leading/trailing whitespace should not count towards maxsplit - - " a b c d ".split(maxsplit=2) # ["a", "b", "c d "] +171 - " a b c d ".split(maxsplit=2) # ["a", "b", "c d "] 171 + ["a", "b", "c d "] # ["a", "b", "c d "] -172 | " a b c d ".rsplit(maxsplit=2) # [" a b", "c", "d"] | SIM905 [*] Consider using a list literal instead of `str.rsplit` @@ -1306,10 +1170,8 @@ SIM905 [*] Consider using a list literal instead of `str.rsplit` | help: Replace with list literal | -171 | " a b c d ".split(maxsplit=2) # ["a", "b", "c d "] - - " a b c d ".rsplit(maxsplit=2) # [" a b", "c", "d"] +172 - " a b c d ".rsplit(maxsplit=2) # [" a b", "c", "d"] 172 + [" a b", "c", "d"] # [" a b", "c", "d"] -173 | "a b".split(maxsplit=1) # ["a", "b"] | SIM905 [*] Consider using a list literal instead of `str.split` @@ -1321,7 +1183,6 @@ SIM905 [*] Consider using a list literal instead of `str.split` | ^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with list literal | -172 | " a b c d ".rsplit(maxsplit=2) # [" a b", "c", "d"] - - "a b".split(maxsplit=1) # ["a", "b"] +173 - "a b".split(maxsplit=1) # ["a", "b"] 173 + ["a", "b"] # ["a", "b"] | diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM910_SIM910.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM910_SIM910.py.snap index e73560d633fe9..8febc63417b3f 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM910_SIM910.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM910_SIM910.py.snap @@ -12,10 +12,8 @@ SIM910 [*] Use `{}.get(key)` instead of `{}.get(key, None)` | help: Replace `{}.get(key, None)` with `{}.get(key)` | -1 | # SIM910 - - {}.get(key, None) +2 - {}.get(key, None) 2 + {}.get(key) -3 | | SIM910 [*] Use `{}.get("key")` instead of `{}.get("key", None)` @@ -29,10 +27,8 @@ SIM910 [*] Use `{}.get("key")` instead of `{}.get("key", None)` | help: Replace `{}.get("key", None)` with `{}.get("key")` | -4 | # SIM910 - - {}.get("key", None) +5 - {}.get("key", None) 5 + {}.get("key") -6 | | SIM910 [*] Use `{}.get(key)` instead of `{}.get(key, None)` @@ -45,10 +41,8 @@ SIM910 [*] Use `{}.get(key)` instead of `{}.get(key, None)` | help: Replace `{}.get(key, None)` with `{}.get(key)` | -19 | # SIM910 - - if a := {}.get(key, None): +20 - if a := {}.get(key, None): 20 + if a := {}.get(key): -21 | pass | SIM910 [*] Use `{}.get(key)` instead of `{}.get(key, None)` @@ -62,10 +56,8 @@ SIM910 [*] Use `{}.get(key)` instead of `{}.get(key, None)` | help: Replace `{}.get(key, None)` with `{}.get(key)` | -23 | # SIM910 - - a = {}.get(key, None) +24 - a = {}.get(key, None) 24 + a = {}.get(key) -25 | | SIM910 [*] Use `({}).get(key)` instead of `({}).get(key, None)` @@ -79,10 +71,8 @@ SIM910 [*] Use `({}).get(key)` instead of `({}).get(key, None)` | help: Replace `({}).get(key, None)` with `({}).get(key)` | -26 | # SIM910 - - ({}).get(key, None) +27 - ({}).get(key, None) 27 + ({}).get(key) -28 | | SIM910 [*] Use `ages.get("Cat")` instead of `ages.get("Cat", None)` @@ -97,10 +87,8 @@ SIM910 [*] Use `ages.get("Cat")` instead of `ages.get("Cat", None)` | help: Replace `ages.get("Cat", None)` with `ages.get("Cat")` | -30 | ages = {"Tom": 23, "Maria": 23, "Dog": 11} - - age = ages.get("Cat", None) +31 - age = ages.get("Cat", None) 31 + age = ages.get("Cat") -32 | | SIM910 [*] Use `kwargs.get('a')` instead of `kwargs.get('a', None)` @@ -115,10 +103,8 @@ SIM910 [*] Use `kwargs.get('a')` instead of `kwargs.get('a', None)` | help: Replace `kwargs.get('a', None)` with `kwargs.get('a')` | -38 | def foo(**kwargs): - - a = kwargs.get('a', None) +39 - a = kwargs.get('a', None) 39 + a = kwargs.get('a') -40 | | SIM910 [*] Use `some_dict.get('a')` instead of `some_dict.get('a', None)` @@ -133,10 +119,8 @@ SIM910 [*] Use `some_dict.get('a')` instead of `some_dict.get('a', None)` | help: Replace `some_dict.get('a', None)` with `some_dict.get('a')` | -42 | def foo(some_dict: dict): - - a = some_dict.get('a', None) +43 - a = some_dict.get('a', None) 43 + a = some_dict.get('a') -44 | | SIM910 [*] Use `dict.get("Cat")` instead of `dict.get("Cat", None)` @@ -148,10 +132,8 @@ SIM910 [*] Use `dict.get("Cat")` instead of `dict.get("Cat", None)` | ^^^^^^^^^^^^^^^^^^^^^ help: Replace `dict.get("Cat", None)` with `dict.get("Cat")` | -56 | dict = {"Tom": 23, "Maria": 23, "Dog": 11} - - age = dict.get("Cat", None) +57 - age = dict.get("Cat", None) 57 + age = dict.get("Cat") -58 | | SIM910 [*] Use `ages.get(key_source.get("Thomas", "Tom"))` instead of `ages.get(key_source.get("Thomas", "Tom"), None)` @@ -166,10 +148,8 @@ SIM910 [*] Use `ages.get(key_source.get("Thomas", "Tom"))` instead of `ages.get( | help: Replace `ages.get(key_source.get("Thomas", "Tom"), None)` with `ages.get(key_source.get("Thomas", "Tom"))` | -63 | key_source = {"Thomas": "Tom"} - - age = ages.get(key_source.get("Thomas", "Tom"), None) +64 - age = ages.get(key_source.get("Thomas", "Tom"), None) 64 + age = ages.get(key_source.get("Thomas", "Tom")) -65 | | SIM910 [*] Use `ages.get(data.name)` instead of `ages.get(data.name, None)` @@ -184,10 +164,8 @@ SIM910 [*] Use `ages.get(data.name)` instead of `ages.get(data.name, None)` | help: Replace `ages.get(data.name, None)` with `ages.get(data.name)` | -72 | ages = {"Tom": 23, "Maria": 23, "Dog": 11} - - age = ages.get(data.name, None) +73 - age = ages.get(data.name, None) 73 + age = ages.get(data.name) -74 | | SIM910 [*] Use `ages.get("Tom" if True else "Maria")` instead of `ages.get("Tom" if True else "Maria", None)` @@ -202,10 +180,8 @@ SIM910 [*] Use `ages.get("Tom" if True else "Maria")` instead of `ages.get("Tom" | help: Replace `ages.get("Tom" if True else "Maria", None)` with `ages.get("Tom" if True else "Maria")` | -76 | ages = {"Tom": 23, "Maria": 23, "Dog": 11} - - age = ages.get("Tom" if True else "Maria", None) +77 - age = ages.get("Tom" if True else "Maria", None) 77 + age = ages.get("Tom" if True else "Maria") -78 | | SIM910 [*] Use `ages.get(get_key())` instead of `ages.get(get_key(), None)` @@ -216,10 +192,8 @@ SIM910 [*] Use `ages.get(get_key())` instead of `ages.get(get_key(), None)` | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace `ages.get(get_key(), None)` with `ages.get(get_key())` | -83 | ages = {"Tom": 23, "Maria": 23, "Dog": 11} - - age = ages.get(get_key(), None) +84 - age = ages.get(get_key(), None) 84 + age = ages.get(get_key()) -85 | | SIM910 [*] Use `dict.get()` without default value @@ -234,12 +208,11 @@ SIM910 [*] Use `dict.get()` without default value | |_^ help: Remove default value | -86 | - - age = ages.get( - - "Cat", - - # text - - None, - - ) +87 - age = ages.get( +88 - "Cat", +89 - # text +90 - None, +91 - ) 87 + age = ages.get("Cat") | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM911_SIM911.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM911_SIM911.py.snap index 6c319656ce69c..41f3355323d1a 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM911_SIM911.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__SIM911_SIM911.py.snap @@ -11,10 +11,8 @@ SIM911 [*] Use `d.items()` instead of `zip(d.keys(), d.values())` | help: Replace `zip(d.keys(), d.values())` with `d.items()` | -1 | def foo(d: dict[str, str]) -> None: - - for k, v in zip(d.keys(), d.values()): # SIM911 +2 - for k, v in zip(d.keys(), d.values()): # SIM911 2 + for k, v in d.items(): # SIM911 -3 | ... | SIM911 [*] Use `d.items()` instead of `zip(d.keys(), d.values(), strict=True)` @@ -28,10 +26,8 @@ SIM911 [*] Use `d.items()` instead of `zip(d.keys(), d.values(), strict=True)` | help: Replace `zip(d.keys(), d.values(), strict=True)` with `d.items()` | -4 | - - for k, v in zip(d.keys(), d.values(), strict=True): # SIM911 +5 - for k, v in zip(d.keys(), d.values(), strict=True): # SIM911 5 + for k, v in d.items(): # SIM911 -6 | ... | SIM911 [*] Use `d2.items()` instead of `zip(d2.keys(), d2.values())` @@ -45,10 +41,8 @@ SIM911 [*] Use `d2.items()` instead of `zip(d2.keys(), d2.values())` | help: Replace `zip(d2.keys(), d2.values())` with `d2.items()` | -19 | - - for k, v in zip(d2.keys(), d2.values()): # SIM911 +20 - for k, v in zip(d2.keys(), d2.values()): # SIM911 20 + for k, v in d2.items(): # SIM911 -21 | ... | SIM911 [*] Use `dict.items()` instead of `zip(dict.keys(), dict.values())` @@ -62,10 +56,8 @@ SIM911 [*] Use `dict.items()` instead of `zip(dict.keys(), dict.values())` | help: Replace `zip(dict.keys(), dict.values())` with `dict.items()` | -29 | dict = {} - - for country, stars in zip(dict.keys(), dict.values()): +30 - for country, stars in zip(dict.keys(), dict.values()): 30 + for country, stars in dict.items(): -31 | ... | SIM911 [*] Use ` flag_stars.items()` instead of `(zip)(flag_stars.keys(), flag_stars.values())` @@ -80,10 +72,8 @@ SIM911 [*] Use ` flag_stars.items()` instead of `(zip)(flag_stars.keys(), flag_s | help: Replace `(zip)(flag_stars.keys(), flag_stars.values())` with ` flag_stars.items()` | -35 | flag_stars = {} - - for country, stars in(zip)(flag_stars.keys(), flag_stars.values()):... +36 - for country, stars in(zip)(flag_stars.keys(), flag_stars.values()):... 36 + for country, stars in flag_stars.items():... -37 | | SIM911 [*] Use `dict.items()` instead of `zip(dict.keys(), dict.values())` @@ -102,13 +92,11 @@ SIM911 [*] Use `dict.items()` instead of `zip(dict.keys(), dict.values())` | help: Replace `zip(dict.keys(), dict.values())` with `dict.items()` | -44 | - - for country, stars in zip( - - flag_stars.keys(), - - # text - - flag_stars.values(), - - ): +45 - for country, stars in zip( +46 - flag_stars.keys(), +47 - # text +48 - flag_stars.values(), +49 - ): 45 + for country, stars in flag_stars.items(): -46 | print(f"{country}'s flag has {stars} stars.") | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__diff_SIM105_SIM105_5.py.snap b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__diff_SIM105_SIM105_5.py.snap index 03f454d2bf658..6d377971c1ba6 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__diff_SIM105_SIM105_5.py.snap +++ b/crates/ruff_linter/src/rules/flake8_simplify/snapshots/ruff_linter__rules__flake8_simplify__tests__diff_SIM105_SIM105_5.py.snap @@ -24,12 +24,7 @@ SIM105 [*] Use `contextlib.suppress(ValueError)` instead of `try`-`except`-`pass | help: Replace `try`-`except`-`pass` with `with contextlib.suppress(ValueError): ...` | -3 | # SIM105 - - try: - - pass - - except* ValueError: 4 + import contextlib -5 + with contextlib.suppress(ValueError): -6 | pass +5 ~ with contextlib.suppress(ValueError): | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_tidy_imports/snapshots/ruff_linter__rules__flake8_tidy_imports__tests__ban_parent_imports_package.snap b/crates/ruff_linter/src/rules/flake8_tidy_imports/snapshots/ruff_linter__rules__flake8_tidy_imports__tests__ban_parent_imports_package.snap index d608a98dcae0f..1d13b655f0094 100644 --- a/crates/ruff_linter/src/rules/flake8_tidy_imports/snapshots/ruff_linter__rules__flake8_tidy_imports__tests__ban_parent_imports_package.snap +++ b/crates/ruff_linter/src/rules/flake8_tidy_imports/snapshots/ruff_linter__rules__flake8_tidy_imports__tests__ban_parent_imports_package.snap @@ -24,10 +24,8 @@ TID252 [*] Prefer absolute imports over relative imports from parent modules | help: Replace relative imports from parent modules with absolute imports | -5 | from ....import unknown - - from ..protocol import commands, definitions, responses +6 - from ..protocol import commands, definitions, responses 6 + from my_package.sublib.protocol import commands, definitions, responses -7 | from ..server import example | note: This is an unsafe fix and may change runtime behavior @@ -42,10 +40,8 @@ TID252 [*] Prefer absolute imports over relative imports from parent modules | help: Replace relative imports from parent modules with absolute imports | -5 | from ....import unknown - - from ..protocol import commands, definitions, responses +6 - from ..protocol import commands, definitions, responses 6 + from my_package.sublib.protocol import commands, definitions, responses -7 | from ..server import example | note: This is an unsafe fix and may change runtime behavior @@ -60,10 +56,8 @@ TID252 [*] Prefer absolute imports over relative imports from parent modules | help: Replace relative imports from parent modules with absolute imports | -5 | from ....import unknown - - from ..protocol import commands, definitions, responses +6 - from ..protocol import commands, definitions, responses 6 + from my_package.sublib.protocol import commands, definitions, responses -7 | from ..server import example | note: This is an unsafe fix and may change runtime behavior @@ -79,10 +73,8 @@ TID252 [*] Prefer absolute imports over relative imports from parent modules | help: Replace relative imports from parent modules with absolute imports | -6 | from ..protocol import commands, definitions, responses - - from ..server import example +7 - from ..server import example 7 + from my_package.sublib.server import example -8 | from .. import server | note: This is an unsafe fix and may change runtime behavior @@ -98,10 +90,8 @@ TID252 [*] Prefer absolute imports over relative imports from parent modules | help: Replace relative imports from parent modules with absolute imports | -7 | from ..server import example - - from .. import server +8 - from .. import server 8 + from my_package.sublib import server -9 | from . import logger, models | note: This is an unsafe fix and may change runtime behavior @@ -114,8 +104,7 @@ TID252 [*] Prefer absolute imports over relative imports from parent modules | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace relative imports from parent modules with absolute imports | -9 | from . import logger, models - - from ..protocol.UpperCaseModule import some_function +10 - from ..protocol.UpperCaseModule import some_function 10 + from my_package.sublib.protocol.UpperCaseModule import some_function | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_tidy_imports/snapshots/ruff_linter__rules__flake8_tidy_imports__tests__preview_lazy_import_immediately_resolved.snap b/crates/ruff_linter/src/rules/flake8_tidy_imports/snapshots/ruff_linter__rules__flake8_tidy_imports__tests__preview_lazy_import_immediately_resolved.snap index 35cf23fe73517..ec05449785f37 100644 --- a/crates/ruff_linter/src/rules/flake8_tidy_imports/snapshots/ruff_linter__rules__flake8_tidy_imports__tests__preview_lazy_import_immediately_resolved.snap +++ b/crates/ruff_linter/src/rules/flake8_tidy_imports/snapshots/ruff_linter__rules__flake8_tidy_imports__tests__preview_lazy_import_immediately_resolved.snap @@ -13,9 +13,8 @@ TID255 [*] Lazy import `foo` is resolved immediately | help: Convert to an eager import | - - lazy import foo +1 - lazy import foo 1 + import foo -2 | lazy import package.submodule | note: This is an unsafe fix and may change runtime behavior @@ -30,10 +29,8 @@ TID255 [*] Lazy import `Component` is resolved immediately | help: Convert to an eager import | -3 | lazy import aliased as alias - - lazy from library import Component +4 - lazy from library import Component 4 + from library import Component -5 | lazy from library import Other as Renamed | note: This is an unsafe fix and may change runtime behavior @@ -49,10 +46,8 @@ TID255 [*] Lazy import `alias` is resolved immediately | help: Convert to an eager import | -2 | lazy import package.submodule - - lazy import aliased as alias +3 - lazy import aliased as alias 3 + import aliased as alias -4 | lazy from library import Component | note: This is an unsafe fix and may change runtime behavior @@ -67,10 +62,8 @@ TID255 [*] Lazy import `package` is resolved immediately | help: Convert to an eager import | -1 | lazy import foo - - lazy import package.submodule +2 - lazy import package.submodule 2 + import package.submodule -3 | lazy import aliased as alias | note: This is an unsafe fix and may change runtime behavior @@ -96,9 +89,8 @@ TID255 [*] Lazy import `foo` is resolved immediately | help: Convert to an eager import | - - lazy import foo +1 - lazy import foo 1 + import foo -2 | lazy import package.submodule | note: This is an unsafe fix and may change runtime behavior @@ -113,10 +105,8 @@ TID255 [*] Lazy import `Component` is resolved immediately | help: Convert to an eager import | -3 | lazy import aliased as alias - - lazy from library import Component +4 - lazy from library import Component 4 + from library import Component -5 | lazy from library import Other as Renamed | note: This is an unsafe fix and may change runtime behavior @@ -129,9 +119,8 @@ TID255 [*] Lazy import `foo` is resolved immediately | help: Convert to an eager import | - - lazy import foo +1 - lazy import foo 1 + import foo -2 | lazy import package.submodule | note: This is an unsafe fix and may change runtime behavior @@ -146,10 +135,8 @@ TID255 [*] Lazy import `Component` is resolved immediately | help: Convert to an eager import | -3 | lazy import aliased as alias - - lazy from library import Component +4 - lazy from library import Component 4 + from library import Component -5 | lazy from library import Other as Renamed | note: This is an unsafe fix and may change runtime behavior @@ -162,10 +149,8 @@ TID255 [*] Lazy import `Renamed` is resolved immediately | help: Convert to an eager import | -4 | lazy from library import Component - - lazy from library import Other as Renamed +5 - lazy from library import Other as Renamed 5 + from library import Other as Renamed -6 | lazy import multi_one, multi_two | note: This is an unsafe fix and may change runtime behavior @@ -181,9 +166,8 @@ TID255 [*] Lazy import `foo` is resolved immediately | help: Convert to an eager import | - - lazy import foo +1 - lazy import foo 1 + import foo -2 | lazy import package.submodule | note: This is an unsafe fix and may change runtime behavior @@ -198,10 +182,8 @@ TID255 [*] Lazy import `Component` is resolved immediately | help: Convert to an eager import | -3 | lazy import aliased as alias - - lazy from library import Component +4 - lazy from library import Component 4 + from library import Component -5 | lazy from library import Other as Renamed | note: This is an unsafe fix and may change runtime behavior @@ -216,9 +198,8 @@ TID255 [*] Lazy import `foo` is resolved immediately | help: Convert to an eager import | - - lazy import foo +1 - lazy import foo 1 + import foo -2 | lazy import package.submodule | note: This is an unsafe fix and may change runtime behavior @@ -233,10 +214,8 @@ TID255 [*] Lazy import `Component` is resolved immediately | help: Convert to an eager import | -3 | lazy import aliased as alias - - lazy from library import Component +4 - lazy from library import Component 4 + from library import Component -5 | lazy from library import Other as Renamed | note: This is an unsafe fix and may change runtime behavior @@ -250,9 +229,8 @@ TID255 [*] Lazy import `foo` is resolved immediately | help: Convert to an eager import | - - lazy import foo +1 - lazy import foo 1 + import foo -2 | lazy import package.submodule | note: This is an unsafe fix and may change runtime behavior @@ -268,8 +246,7 @@ TID255 [*] Lazy import `foo` is resolved immediately | help: Convert to an eager import | - - lazy import foo +1 - lazy import foo 1 + import foo -2 | lazy import package.submodule | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_tidy_imports/snapshots/ruff_linter__rules__flake8_tidy_imports__tests__preview_lazy_import_mismatch.snap b/crates/ruff_linter/src/rules/flake8_tidy_imports/snapshots/ruff_linter__rules__flake8_tidy_imports__tests__preview_lazy_import_mismatch.snap index d88842a4de635..4311c73563967 100644 --- a/crates/ruff_linter/src/rules/flake8_tidy_imports/snapshots/ruff_linter__rules__flake8_tidy_imports__tests__preview_lazy_import_mismatch.snap +++ b/crates/ruff_linter/src/rules/flake8_tidy_imports/snapshots/ruff_linter__rules__flake8_tidy_imports__tests__preview_lazy_import_mismatch.snap @@ -11,11 +11,8 @@ TID254 [*] `typing` should be imported lazily | help: Convert to a lazy import | -3 | import os - - import typing as t -4 + lazy import typing as t -5 | lazy import pathlib - | +4 | lazy import typing as t + | ++++ note: This is an unsafe fix and may change runtime behavior TID254 [*] `foo` should be imported lazily @@ -30,11 +27,8 @@ TID254 [*] `foo` should be imported lazily | help: Convert to a lazy import | -6 | - - from foo import bar -7 + lazy from foo import bar -8 | lazy from foo import baz - | +7 | lazy from foo import bar + | ++++ note: This is an unsafe fix and may change runtime behavior TID254 [*] `email` should be imported lazily @@ -48,11 +42,8 @@ TID254 [*] `email` should be imported lazily | help: Convert to a lazy import | -11 | with manager(): - - import email -12 + lazy import email -13 | - | +12 | lazy import email + | ++++ note: This is an unsafe fix and may change runtime behavior TID254 [*] `bar` should be imported lazily @@ -66,11 +57,8 @@ TID254 [*] `bar` should be imported lazily | help: Convert to a lazy import | -14 | if True: - - from bar import qux -15 + lazy from bar import qux -16 | - | +15 | lazy from bar import qux + | ++++ note: This is an unsafe fix and may change runtime behavior TID254 [*] `pkg` should be imported lazily @@ -82,8 +70,6 @@ TID254 [*] `pkg` should be imported lazily | ^^^^^^^^^^^^^ help: Convert to a lazy import | -27 | - - x = 1; import pkg.submodule -28 + x = 1; lazy import pkg.submodule - | +28 | x = 1; lazy import pkg.submodule + | ++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_tidy_imports/snapshots/ruff_linter__rules__flake8_tidy_imports__tests__preview_lazy_import_mismatch_all.snap b/crates/ruff_linter/src/rules/flake8_tidy_imports/snapshots/ruff_linter__rules__flake8_tidy_imports__tests__preview_lazy_import_mismatch_all.snap index cbf1915ed79a1..1e67124e106d6 100644 --- a/crates/ruff_linter/src/rules/flake8_tidy_imports/snapshots/ruff_linter__rules__flake8_tidy_imports__tests__preview_lazy_import_mismatch_all.snap +++ b/crates/ruff_linter/src/rules/flake8_tidy_imports/snapshots/ruff_linter__rules__flake8_tidy_imports__tests__preview_lazy_import_mismatch_all.snap @@ -13,11 +13,8 @@ TID254 [*] Use a `lazy` import instead of an eager import | help: Convert to a lazy import | -2 | - - import os -3 + lazy import os -4 | import typing as t - | +3 | lazy import os + | ++++ note: This is an unsafe fix and may change runtime behavior TID254 [*] Use a `lazy` import instead of an eager import @@ -30,11 +27,8 @@ TID254 [*] Use a `lazy` import instead of an eager import | help: Convert to a lazy import | -3 | import os - - import typing as t -4 + lazy import typing as t -5 | lazy import pathlib - | +4 | lazy import typing as t + | ++++ note: This is an unsafe fix and may change runtime behavior TID254 [*] Use a `lazy` import instead of an eager import @@ -49,11 +43,8 @@ TID254 [*] Use a `lazy` import instead of an eager import | help: Convert to a lazy import | -6 | - - from foo import bar -7 + lazy from foo import bar -8 | lazy from foo import baz - | +7 | lazy from foo import bar + | ++++ note: This is an unsafe fix and may change runtime behavior TID254 [*] Use a `lazy` import instead of an eager import @@ -67,11 +58,8 @@ TID254 [*] Use a `lazy` import instead of an eager import | help: Convert to a lazy import | -11 | with manager(): - - import email -12 + lazy import email -13 | - | +12 | lazy import email + | ++++ note: This is an unsafe fix and may change runtime behavior TID254 [*] Use a `lazy` import instead of an eager import @@ -85,11 +73,8 @@ TID254 [*] Use a `lazy` import instead of an eager import | help: Convert to a lazy import | -14 | if True: - - from bar import qux -15 + lazy from bar import qux -16 | - | +15 | lazy from bar import qux + | ++++ note: This is an unsafe fix and may change runtime behavior TID254 [*] Use a `lazy` import instead of an eager import @@ -101,8 +86,6 @@ TID254 [*] Use a `lazy` import instead of an eager import | ^^^^^^^^^^^^^ help: Convert to a lazy import | -27 | - - x = 1; import pkg.submodule -28 + x = 1; lazy import pkg.submodule - | +28 | x = 1; lazy import pkg.submodule + | ++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_todos/snapshots/ruff_linter__rules__flake8_todos__tests__invalid-todo-capitalization_TD006.py.snap b/crates/ruff_linter/src/rules/flake8_todos/snapshots/ruff_linter__rules__flake8_todos__tests__invalid-todo-capitalization_TD006.py.snap index b6e38a7191a96..2895ccc391691 100644 --- a/crates/ruff_linter/src/rules/flake8_todos/snapshots/ruff_linter__rules__flake8_todos__tests__invalid-todo-capitalization_TD006.py.snap +++ b/crates/ruff_linter/src/rules/flake8_todos/snapshots/ruff_linter__rules__flake8_todos__tests__invalid-todo-capitalization_TD006.py.snap @@ -13,10 +13,8 @@ TD006 [*] Invalid TODO capitalization: `ToDo` should be `TODO` | help: Replace `ToDo` with `TODO` | -4 | # TDO006 - error - - # ToDo (evanrittenhouse): invalid capitalization +5 - # ToDo (evanrittenhouse): invalid capitalization 5 + # TODO (evanrittenhouse): invalid capitalization -6 | # todo (evanrittenhouse): another invalid capitalization | TD006 [*] Invalid TODO capitalization: `todo` should be `TODO` @@ -30,10 +28,8 @@ TD006 [*] Invalid TODO capitalization: `todo` should be `TODO` | help: Replace `todo` with `TODO` | -5 | # ToDo (evanrittenhouse): invalid capitalization - - # todo (evanrittenhouse): another invalid capitalization +6 - # todo (evanrittenhouse): another invalid capitalization 6 + # TODO (evanrittenhouse): another invalid capitalization -7 | # foo # todo: invalid capitalization | TD006 [*] Invalid TODO capitalization: `todo` should be `TODO` @@ -45,7 +41,6 @@ TD006 [*] Invalid TODO capitalization: `todo` should be `TODO` | ^^^^ help: Replace `todo` with `TODO` | -6 | # todo (evanrittenhouse): another invalid capitalization - - # foo # todo: invalid capitalization +7 - # foo # todo: invalid capitalization 7 + # foo # TODO: invalid capitalization | diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC001-TC002-TC003_TC001-3_future.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC001-TC002-TC003_TC001-3_future.py.snap index 2e3272a28e6c9..dc2558ae6d5fe 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC001-TC002-TC003_TC001-3_future.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC001-TC002-TC003_TC001-3_future.py.snap @@ -11,16 +11,14 @@ TC003 [*] Move standard library import `collections.Counter` into a type-checkin | help: Move into type-checking block | - - from collections import Counter -1 | -2 | from elsewhere import third_party -3 | -4 | from . import first_party -5 + from typing import TYPE_CHECKING -6 + -7 + if TYPE_CHECKING: -8 + from collections import Counter -9 | +1 + +2 | +… +5 | from . import first_party +6 + from typing import TYPE_CHECKING +7 ~ +8 + if TYPE_CHECKING: +9 + from collections import Counter | note: This is an unsafe fix and may change runtime behavior @@ -36,15 +34,13 @@ TC002 [*] Move third-party import `elsewhere.third_party` into a type-checking b | help: Move into type-checking block | -2 | - - from elsewhere import third_party -3 | -4 | from . import first_party -5 + from typing import TYPE_CHECKING -6 + -7 + if TYPE_CHECKING: -8 + from elsewhere import third_party -9 | +3 + +4 | +5 | from . import first_party +6 + from typing import TYPE_CHECKING +7 ~ +8 + if TYPE_CHECKING: +9 + from elsewhere import third_party | note: This is an unsafe fix and may change runtime behavior @@ -57,12 +53,10 @@ TC001 [*] Move application import `.first_party` into a type-checking block | ^^^^^^^^^^^ help: Move into type-checking block | -4 | - - from . import first_party -5 + from typing import TYPE_CHECKING -6 + -7 + if TYPE_CHECKING: -8 + from . import first_party -9 | +5 + +6 + from typing import TYPE_CHECKING +7 ~ +8 + if TYPE_CHECKING: +9 + from . import first_party | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC001_TC001.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC001_TC001.py.snap index 97cb90654f6e4..ff2c30e188009 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC001_TC001.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC001_TC001.py.snap @@ -12,15 +12,10 @@ TC001 [*] Move application import `.TYP001` into a type-checking block | help: Move into type-checking block | -4 | """ -5 + from typing import TYPE_CHECKING -6 + -7 + if TYPE_CHECKING: -8 + from . import TYP001 -9 | --------------------------------------------------------------------------------- -23 | def f(): - - from . import TYP001 -24 | + 5 + from typing import TYPE_CHECKING + 6 ~ + 7 + if TYPE_CHECKING: + 8 + from . import TYP001 + 9 + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC001_TC001_future.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC001_TC001_future.py.snap index 688f10b1a0246..a67432014369c 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC001_TC001_future.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC001_TC001_future.py.snap @@ -12,13 +12,11 @@ TC001 [*] Move application import `.first_party` into a type-checking block | help: Move into type-checking block | - - def f(): 1 + from typing import TYPE_CHECKING -2 + +2 ~ 3 + if TYPE_CHECKING: -4 | from . import first_party -5 + def f(): -6 | +4 + from . import first_party +5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -33,16 +31,10 @@ TC001 [*] Move application import `.foo` into a type-checking block | help: Move into type-checking block | -52 | # unions - - from typing import Union -53 + from typing import Union, TYPE_CHECKING -54 + +53 ~ from typing import Union, TYPE_CHECKING +54 + 55 + if TYPE_CHECKING: 56 + from . import foo -57 | -58 | -59 | def n(): - - from . import foo -60 | +57 + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC001_TC001_future_present.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC001_TC001_future_present.py.snap index acc284395cb39..a2725b2fbb151 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC001_TC001_future_present.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC001_TC001_future_present.py.snap @@ -10,12 +10,10 @@ TC001 [*] Move application import `.first_party` into a type-checking block | ^^^^^^^^^^^ help: Move into type-checking block | -2 | - - from . import first_party -3 + from typing import TYPE_CHECKING -4 + -5 + if TYPE_CHECKING: -6 + from . import first_party -7 | +3 + +4 + from typing import TYPE_CHECKING +5 ~ +6 + if TYPE_CHECKING: +7 + from . import first_party | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC002_TC002.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC002_TC002.py.snap index 10e3d78153466..30d3902e5bc29 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC002_TC002.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC002_TC002.py.snap @@ -12,16 +12,11 @@ TC002 [*] Move third-party import `pandas` into a type-checking block | help: Move into type-checking block | -1 | """Tests to determine accurate detection of typing-only imports.""" 2 + from typing import TYPE_CHECKING -3 + +3 ~ 4 + if TYPE_CHECKING: 5 + import pandas as pd -6 | -7 | -8 | def f(): - - import pandas as pd # TC002 -9 | +6 + | note: This is an unsafe fix and may change runtime behavior @@ -36,16 +31,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -1 | """Tests to determine accurate detection of typing-only imports.""" -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + from pandas import DataFrame -6 | --------------------------------------------------------------------------------- -14 | def f(): - - from pandas import DataFrame # TC002 -15 | + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + from pandas import DataFrame + 6 + | note: This is an unsafe fix and may change runtime behavior @@ -60,16 +50,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -1 | """Tests to determine accurate detection of typing-only imports.""" -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + from pandas import DataFrame as df -6 | --------------------------------------------------------------------------------- -20 | def f(): - - from pandas import DataFrame as df # TC002 -21 | + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + from pandas import DataFrame as df + 6 + | note: This is an unsafe fix and may change runtime behavior @@ -84,16 +69,11 @@ TC002 [*] Move third-party import `pandas` into a type-checking block | help: Move into type-checking block | -1 | """Tests to determine accurate detection of typing-only imports.""" -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + import pandas as pd -6 | --------------------------------------------------------------------------------- -26 | def f(): - - import pandas as pd # TC002 -27 | + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + import pandas as pd + 6 + | note: This is an unsafe fix and may change runtime behavior @@ -108,16 +88,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -1 | """Tests to determine accurate detection of typing-only imports.""" -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + from pandas import DataFrame -6 | --------------------------------------------------------------------------------- -32 | def f(): - - from pandas import DataFrame # TC002 -33 | + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + from pandas import DataFrame + 6 + | note: This is an unsafe fix and may change runtime behavior @@ -132,16 +107,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -1 | """Tests to determine accurate detection of typing-only imports.""" -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + from pandas import DataFrame as df -6 | --------------------------------------------------------------------------------- -38 | def f(): - - from pandas import DataFrame as df # TC002 -39 | + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + from pandas import DataFrame as df + 6 + | note: This is an unsafe fix and may change runtime behavior @@ -156,16 +126,11 @@ TC002 [*] Move third-party import `pandas` into a type-checking block | help: Move into type-checking block | -1 | """Tests to determine accurate detection of typing-only imports.""" -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + import pandas as pd -6 | --------------------------------------------------------------------------------- -44 | def f(): - - import pandas as pd # TC002 -45 | + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + import pandas as pd + 6 + | note: This is an unsafe fix and may change runtime behavior @@ -180,15 +145,10 @@ TC002 [*] Move third-party import `pandas` into a type-checking block | help: Move into type-checking block | -1 | """Tests to determine accurate detection of typing-only imports.""" -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + import pandas as pd -6 | --------------------------------------------------------------------------------- -50 | def f(): - - import pandas as pd # TC002 -51 | + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + import pandas as pd + 6 + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC003_TC003.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC003_TC003.py.snap index 38053965d3f47..9592f14b4776d 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC003_TC003.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import__TC003_TC003.py.snap @@ -12,15 +12,10 @@ TC003 [*] Move standard library import `os` into a type-checking block | help: Move into type-checking block | -4 | """ -5 + from typing import TYPE_CHECKING -6 + -7 + if TYPE_CHECKING: -8 + import os -9 | -10 | -11 | def f(): - - import os -12 | + 5 + from typing import TYPE_CHECKING + 6 ~ + 7 + if TYPE_CHECKING: + 8 + import os + 9 + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import_kw_only__TC003_TC003.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import_kw_only__TC003_TC003.py.snap index 38053965d3f47..9592f14b4776d 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import_kw_only__TC003_TC003.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__add_future_import_kw_only__TC003_TC003.py.snap @@ -12,15 +12,10 @@ TC003 [*] Move standard library import `os` into a type-checking block | help: Move into type-checking block | -4 | """ -5 + from typing import TYPE_CHECKING -6 + -7 + if TYPE_CHECKING: -8 + import os -9 | -10 | -11 | def f(): - - import os -12 | + 5 + from typing import TYPE_CHECKING + 6 ~ + 7 + if TYPE_CHECKING: + 8 + import os + 9 + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__empty-type-checking-block_TC005.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__empty-type-checking-block_TC005.py.snap index 4a34254f48407..c5fda4ceff514 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__empty-type-checking-block_TC005.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__empty-type-checking-block_TC005.py.snap @@ -9,10 +9,8 @@ TC005 [*] Found empty type-checking block | ^^^^ help: Delete empty type-checking block | -2 | - - if TYPE_CHECKING: - - pass # TC005 -3 | +3 - if TYPE_CHECKING: +4 - pass # TC005 | TC005 [*] Found empty type-checking block @@ -25,12 +23,10 @@ TC005 [*] Found empty type-checking block 10 | return | help: Delete empty type-checking block - | -7 | def example(): - - if TYPE_CHECKING: - - pass # TC005 -8 | return - | + | + 8 - if TYPE_CHECKING: + 9 - pass # TC005 + | TC005 [*] Found empty type-checking block --> TC005.py:15:9 @@ -43,10 +39,8 @@ TC005 [*] Found empty type-checking block | help: Delete empty type-checking block | -13 | class Test: - - if TYPE_CHECKING: - - pass # TC005 -14 | x = 2 +14 - if TYPE_CHECKING: +15 - pass # TC005 | TC005 [*] Found empty type-checking block @@ -60,8 +54,6 @@ TC005 [*] Found empty type-checking block | help: Delete empty type-checking block | -29 | - - if TYPE_CHECKING: - - pass # TC005 -30 | +30 - if TYPE_CHECKING: +31 - pass # TC005 | diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__exempt_modules.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__exempt_modules.snap index f0e3ea2608a3b..773b40b8220f8 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__exempt_modules.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__exempt_modules.snap @@ -12,14 +12,10 @@ TC002 [*] Move third-party import `flask` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + import flask -5 | def f(): --------------------------------------------------------------------------------- -17 | def f(): - - import flask -18 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + import flask + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__github_issue_15681_fix_test.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__github_issue_15681_fix_test.snap index c02d0dbbca3ce..855b9594b4444 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__github_issue_15681_fix_test.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__github_issue_15681_fix_test.snap @@ -13,12 +13,10 @@ TC003 [*] Move standard library import `pathlib` into a type-checking block | help: Move into type-checking block | -3 | - - import pathlib # TC003 -4 | -5 | TYPE_CHECKING = False -6 | if TYPE_CHECKING: -7 + import pathlib -8 | from types import TracebackType +4 + +5 | +6 ~ TYPE_CHECKING = False +7 | if TYPE_CHECKING: +8 + import pathlib | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__import_from.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__import_from.snap index 04e16164af433..e849a4e4267ea 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__import_from.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__import_from.snap @@ -12,16 +12,14 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -4 | from pandas import ( - - DataFrame, # DataFrame -5 | Series, # Series -6 | ) -7 + from typing import TYPE_CHECKING -8 + -9 + if TYPE_CHECKING: + 4 + from pandas import ( + 5 + Series, # Series + 6 + ) + 7 + from typing import TYPE_CHECKING + 8 ~ + 9 + if TYPE_CHECKING: 10 + from pandas import ( 11 + DataFrame, # DataFrame 12 + ) -13 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__import_from_type_checking_block.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__import_from_type_checking_block.snap index 7d9a602810685..15ea0b5755a32 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__import_from_type_checking_block.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__import_from_type_checking_block.snap @@ -12,15 +12,15 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -6 | from pandas import ( - - DataFrame, # DataFrame -7 | Series, # Series -8 | ) -9 | + 4 ~ from typing import TYPE_CHECKING + 5 | + 6 + from pandas import ( + 7 + Series, # Series + 8 + ) + 9 | 10 | if TYPE_CHECKING: 11 + from pandas import ( 12 + DataFrame, # DataFrame 13 + ) -14 | import os | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__multiple_members.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__multiple_members.snap index 29233a7847d13..0e652b63fe58b 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__multiple_members.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__multiple_members.snap @@ -12,19 +12,15 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -5 | - - from pandas import ( - - DataFrame, # DataFrame - - Series, # Series - - ) -6 | -7 + if TYPE_CHECKING: -8 + from pandas import ( -9 + DataFrame, # DataFrame -10 + Series, # Series -11 + ) -12 + -13 | def f(x: DataFrame, y: Series): + 4 ~ from typing import TYPE_CHECKING + 5 | + 6 + + 7 + + 8 + if TYPE_CHECKING: + 9 + from pandas import ( +10 + DataFrame, # DataFrame +11 + Series, # Series +12 + ) | note: This is an unsafe fix and may change runtime behavior @@ -39,18 +35,14 @@ TC002 [*] Move third-party import `pandas.Series` into a type-checking block | help: Move into type-checking block | -5 | - - from pandas import ( - - DataFrame, # DataFrame - - Series, # Series - - ) -6 | -7 + if TYPE_CHECKING: -8 + from pandas import ( -9 + DataFrame, # DataFrame -10 + Series, # Series -11 + ) -12 + -13 | def f(x: DataFrame, y: Series): + 4 ~ from typing import TYPE_CHECKING + 5 | + 6 + + 7 + + 8 + if TYPE_CHECKING: + 9 + from pandas import ( +10 + DataFrame, # DataFrame +11 + Series, # Series +12 + ) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__multiple_modules_different_types.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__multiple_modules_different_types.snap index 84d66119e80d3..ca45a5f37366a 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__multiple_modules_different_types.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__multiple_modules_different_types.snap @@ -12,15 +12,14 @@ TC003 [*] Move standard library import `os` into a type-checking block 8 | def f(x: os, y: pandas): | help: Move into type-checking block - | -5 | - - import os, pandas -6 + import pandas -7 + -8 + if TYPE_CHECKING: -9 + import os -10 | - | + | +4 ~ from typing import TYPE_CHECKING +5 | +6 + import pandas +7 + +8 + if TYPE_CHECKING: +9 + import os + | note: This is an unsafe fix and may change runtime behavior TC002 [*] Move third-party import `pandas` into a type-checking block @@ -34,13 +33,12 @@ TC002 [*] Move third-party import `pandas` into a type-checking block 8 | def f(x: os, y: pandas): | help: Move into type-checking block - | -5 | - - import os, pandas -6 + import os -7 + -8 + if TYPE_CHECKING: -9 + import pandas -10 | - | + | +4 ~ from typing import TYPE_CHECKING +5 | +6 + import os +7 + +8 + if TYPE_CHECKING: +9 + import pandas + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__multiple_modules_same_type.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__multiple_modules_same_type.snap index 1b51f141e6349..eec8291c11cd6 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__multiple_modules_same_type.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__multiple_modules_same_type.snap @@ -12,15 +12,14 @@ TC003 [*] Move standard library import `os` into a type-checking block 8 | def f(x: os, y: sys): | help: Move into type-checking block - | -5 | - - import os, sys -6 | -7 + if TYPE_CHECKING: -8 + import os, sys -9 + -10 | def f(x: os, y: sys): - | + | +4 ~ from typing import TYPE_CHECKING +5 | +6 + +7 + +8 + if TYPE_CHECKING: +9 + import os, sys + | note: This is an unsafe fix and may change runtime behavior TC003 [*] Move standard library import `sys` into a type-checking block @@ -34,13 +33,12 @@ TC003 [*] Move standard library import `sys` into a type-checking block 8 | def f(x: os, y: sys): | help: Move into type-checking block - | -5 | - - import os, sys -6 | -7 + if TYPE_CHECKING: -8 + import os, sys -9 + -10 | def f(x: os, y: sys): - | + | +4 ~ from typing import TYPE_CHECKING +5 | +6 + +7 + +8 + if TYPE_CHECKING: +9 + import os, sys + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__no_typing_import.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__no_typing_import.snap index 582c0af8a9db2..0b39143d5b51e 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__no_typing_import.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__no_typing_import.snap @@ -13,12 +13,10 @@ TC002 [*] Move third-party import `pandas` into a type-checking block | help: Move into type-checking block | -3 | - - import pandas as pd -4 + from typing import TYPE_CHECKING -5 + -6 + if TYPE_CHECKING: -7 + import pandas as pd -8 | +4 + +5 + from typing import TYPE_CHECKING +6 ~ +7 + if TYPE_CHECKING: +8 + import pandas as pd | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__pre_py310_quoted-type-alias_TC008_union_syntax_pre_py310.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__pre_py310_quoted-type-alias_TC008_union_syntax_pre_py310.py.snap index a0d9c0f80ac15..c231a9694f831 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__pre_py310_quoted-type-alias_TC008_union_syntax_pre_py310.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__pre_py310_quoted-type-alias_TC008_union_syntax_pre_py310.py.snap @@ -13,10 +13,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -9 | c: TypeAlias = 'int | None' # OK - - d: TypeAlias = 'Annotated[int, 1 | 2]' # TC008 +10 - d: TypeAlias = 'Annotated[int, 1 | 2]' # TC008 10 + d: TypeAlias = Annotated[int, 1 | 2] # TC008 -11 | e: TypeAlias = 'Annotated[int, 1 + 2]' # TC008 | TC008 [*] Remove quotes from type alias @@ -30,8 +28,6 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -10 | d: TypeAlias = 'Annotated[int, 1 | 2]' # TC008 - - e: TypeAlias = 'Annotated[int, 1 + 2]' # TC008 +11 - e: TypeAlias = 'Annotated[int, 1 + 2]' # TC008 11 + e: TypeAlias = Annotated[int, 1 + 2] # TC008 -12 | f: TypeAlias = 'dict[str, int | None]' # OK | diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quote_runtime-import-in-type-checking-block_quote.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quote_runtime-import-in-type-checking-block_quote.py.snap index d8b6f0a655154..43648dcc7aeca 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quote_runtime-import-in-type-checking-block_quote.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quote_runtime-import-in-type-checking-block_quote.py.snap @@ -12,12 +12,11 @@ TC004 [*] Move import `pandas.DataFrame` out of type-checking block. Import is u | --------- Used at runtime here help: Move out of type-checking block | -1 + from pandas import DataFrame -2 | def f(): --------------------------------------------------------------------------------- + 1 + from pandas import DataFrame + 2 | def f(): + 3 | from pandas import DataFrame + … 110 | if TYPE_CHECKING: - - from pandas import DataFrame -111 + pass -112 | +111 ~ pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quote_typing-only-third-party-import_quote.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quote_typing-only-third-party-import_quote.py.snap index 4ba02e685a682..751606392cd37 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quote_typing-only-third-party-import_quote.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quote_typing-only-third-party-import_quote.py.snap @@ -12,13 +12,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | - - def f(): 1 + from typing import TYPE_CHECKING -2 + +2 ~ 3 + if TYPE_CHECKING: -4 | from pandas import DataFrame -5 + def f(): -6 | +4 + from pandas import DataFrame +5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -33,15 +31,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from pandas import DataFrame -5 | def f(): --------------------------------------------------------------------------------- -12 | def f(): - - from pandas import DataFrame -13 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from pandas import DataFrame + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -56,15 +50,11 @@ TC002 [*] Move third-party import `pandas` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + import pandas as pd -5 | def f(): --------------------------------------------------------------------------------- -19 | def f(): - - import pandas as pd -20 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + import pandas as pd + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -79,15 +69,11 @@ TC002 [*] Move third-party import `pandas` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + import pandas as pd -5 | def f(): --------------------------------------------------------------------------------- -26 | def f(): - - import pandas as pd -27 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + import pandas as pd + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -102,15 +88,11 @@ TC002 [*] Move third-party import `pandas` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + import pandas as pd -5 | def f(): --------------------------------------------------------------------------------- -33 | def f(): - - import pandas as pd -34 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + import pandas as pd + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -125,15 +107,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from pandas import DataFrame -5 | def f(): --------------------------------------------------------------------------------- -41 | def f(): - - from pandas import DataFrame -42 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from pandas import DataFrame + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -149,15 +127,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from pandas import DataFrame -5 | def f(): --------------------------------------------------------------------------------- -50 | - - from pandas import DataFrame -51 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from pandas import DataFrame + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -172,15 +146,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from pandas import DataFrame, Series -5 | def f(): --------------------------------------------------------------------------------- -67 | def f(): - - from pandas import DataFrame, Series -68 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from pandas import DataFrame, Series + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -195,15 +165,11 @@ TC002 [*] Move third-party import `pandas.Series` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from pandas import DataFrame, Series -5 | def f(): --------------------------------------------------------------------------------- -67 | def f(): - - from pandas import DataFrame, Series -68 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from pandas import DataFrame, Series + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -218,15 +184,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from pandas import DataFrame, Series -5 | def f(): --------------------------------------------------------------------------------- -74 | def f(): - - from pandas import DataFrame, Series -75 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from pandas import DataFrame, Series + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -241,15 +203,11 @@ TC002 [*] Move third-party import `pandas.Series` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from pandas import DataFrame, Series -5 | def f(): --------------------------------------------------------------------------------- -74 | def f(): - - from pandas import DataFrame, Series -75 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from pandas import DataFrame, Series + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -264,15 +222,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from pandas import DataFrame, Series -5 | def f(): --------------------------------------------------------------------------------- -92 | def f(): - - from pandas import DataFrame, Series -93 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from pandas import DataFrame, Series + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -287,14 +241,10 @@ TC002 [*] Move third-party import `pandas.Series` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from pandas import DataFrame, Series -5 | def f(): --------------------------------------------------------------------------------- -92 | def f(): - - from pandas import DataFrame, Series -93 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from pandas import DataFrame, Series + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quote_typing-only-third-party-import_quote2.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quote_typing-only-third-party-import_quote2.py.snap index d50a0e6207fb4..3798f6af8a466 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quote_typing-only-third-party-import_quote2.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quote_typing-only-third-party-import_quote2.py.snap @@ -12,13 +12,11 @@ TC002 [*] Move third-party import `django.contrib.auth.models.AbstractBaseUser` | help: Move into type-checking block | - - def f(): 1 + from typing import TYPE_CHECKING -2 + +2 ~ 3 + if TYPE_CHECKING: -4 | from django.contrib.auth.models import AbstractBaseUser -5 + def f(): -6 | +4 + from django.contrib.auth.models import AbstractBaseUser +5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -33,15 +31,11 @@ TC002 [*] Move third-party import `django.contrib.auth.models.AbstractBaseUser` | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from django.contrib.auth.models import AbstractBaseUser -5 | def f(): --------------------------------------------------------------------------------- -12 | def f(): - - from django.contrib.auth.models import AbstractBaseUser -13 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from django.contrib.auth.models import AbstractBaseUser + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -56,15 +50,11 @@ TC002 [*] Move third-party import `django.contrib.auth.models.AbstractBaseUser` | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from django.contrib.auth.models import AbstractBaseUser -5 | def f(): --------------------------------------------------------------------------------- -19 | def f(): - - from django.contrib.auth.models import AbstractBaseUser -20 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from django.contrib.auth.models import AbstractBaseUser + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -80,15 +70,11 @@ TC002 [*] Move third-party import `django.contrib.auth.models.AbstractBaseUser` | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from django.contrib.auth.models import AbstractBaseUser -5 | def f(): --------------------------------------------------------------------------------- -28 | - - from django.contrib.auth.models import AbstractBaseUser -29 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from django.contrib.auth.models import AbstractBaseUser + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -104,15 +90,11 @@ TC002 [*] Move third-party import `django.contrib.auth.models.AbstractBaseUser` | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from django.contrib.auth.models import AbstractBaseUser -5 | def f(): --------------------------------------------------------------------------------- -37 | - - from django.contrib.auth.models import AbstractBaseUser -38 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from django.contrib.auth.models import AbstractBaseUser + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -128,15 +110,11 @@ TC002 [*] Move third-party import `django.contrib.auth.models.AbstractBaseUser` | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from django.contrib.auth.models import AbstractBaseUser -5 | def f(): --------------------------------------------------------------------------------- -46 | - - from django.contrib.auth.models import AbstractBaseUser -47 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from django.contrib.auth.models import AbstractBaseUser + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -152,15 +130,11 @@ TC002 [*] Move third-party import `django.contrib.auth.models.AbstractBaseUser` | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from django.contrib.auth.models import AbstractBaseUser -5 | def f(): --------------------------------------------------------------------------------- -55 | - - from django.contrib.auth.models import AbstractBaseUser -56 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from django.contrib.auth.models import AbstractBaseUser + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -176,15 +150,11 @@ TC002 [*] Move third-party import `django.contrib.auth.models.AbstractBaseUser` | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from django.contrib.auth.models import AbstractBaseUser -5 | def f(): --------------------------------------------------------------------------------- -64 | - - from django.contrib.auth.models import AbstractBaseUser -65 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from django.contrib.auth.models import AbstractBaseUser + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -200,14 +170,10 @@ TC002 [*] Move third-party import `django.contrib.auth.models.AbstractBaseUser` | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from django.contrib.auth.models import AbstractBaseUser -5 | def f(): --------------------------------------------------------------------------------- -73 | - - from django.contrib.auth.models import AbstractBaseUser -74 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from django.contrib.auth.models import AbstractBaseUser + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quote_typing-only-third-party-import_quote3.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quote_typing-only-third-party-import_quote3.py.snap index 141605bc4899b..d06b08b7f0271 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quote_typing-only-third-party-import_quote3.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quote_typing-only-third-party-import_quote3.py.snap @@ -14,14 +14,10 @@ TC002 [*] Move third-party import `django.contrib.auth.models.AbstractBaseUser` help: Move into type-checking block | 1 + from typing import TYPE_CHECKING -2 + +2 ~ 3 + if TYPE_CHECKING: 4 + from django.contrib.auth.models import AbstractBaseUser 5 | def f(): -6 | from typing import Literal, Union -7 | - - from django.contrib.auth.models import AbstractBaseUser -8 | | note: This is an unsafe fix and may change runtime behavior @@ -37,15 +33,11 @@ TC002 [*] Move third-party import `django.contrib.auth.models.AbstractBaseUser` | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from django.contrib.auth.models import AbstractBaseUser -5 | def f(): --------------------------------------------------------------------------------- -16 | - - from django.contrib.auth.models import AbstractBaseUser -17 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from django.contrib.auth.models import AbstractBaseUser + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -61,15 +53,11 @@ TC002 [*] Move third-party import `django.contrib.auth.models.AbstractBaseUser` | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from django.contrib.auth.models import AbstractBaseUser -5 | def f(): --------------------------------------------------------------------------------- -25 | - - from django.contrib.auth.models import AbstractBaseUser -26 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from django.contrib.auth.models import AbstractBaseUser + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -85,15 +73,11 @@ TC002 [*] Move third-party import `django.contrib.auth.models` into a type-check | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from django.contrib.auth import models -5 | def f(): --------------------------------------------------------------------------------- -34 | - - from django.contrib.auth import models -35 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from django.contrib.auth import models + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -109,15 +93,11 @@ TC002 [*] Move third-party import `django.contrib.auth.models` into a type-check | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from django.contrib.auth import models -5 | def f(): --------------------------------------------------------------------------------- -43 | - - from django.contrib.auth import models -44 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from django.contrib.auth import models + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -133,15 +113,11 @@ TC002 [*] Move third-party import `third_party.Type` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from third_party import Type -5 | def f(): --------------------------------------------------------------------------------- -62 | from typing import Literal - - from third_party import Type -63 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from third_party import Type + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -157,14 +133,10 @@ TC002 [*] Move third-party import `third_party.Type` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from third_party import Type -5 | def f(): --------------------------------------------------------------------------------- -70 | from typing import Literal - - from third_party import Type -71 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from third_party import Type + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quoted-type-alias_TC008.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quoted-type-alias_TC008.py.snap index f63bd8a044c1a..3bffeaef018fb 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quoted-type-alias_TC008.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quoted-type-alias_TC008.py.snap @@ -13,10 +13,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -14 | - - a: TypeAlias = 'int' # TC008 +15 - a: TypeAlias = 'int' # TC008 15 + a: TypeAlias = int # TC008 -16 | b: TypeAlias = 'Dict' # OK | TC008 [*] Remove quotes from type alias @@ -31,10 +29,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -16 | b: TypeAlias = 'Dict' # OK - - c: TypeAlias = 'Foo' # TC008 +17 - c: TypeAlias = 'Foo' # TC008 17 + c: TypeAlias = Foo # TC008 -18 | d: TypeAlias = 'Foo[str]' # OK | TC008 [*] Remove quotes from type alias @@ -49,10 +45,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -19 | e: TypeAlias = 'Foo.bar' # OK - - f: TypeAlias = 'Foo | None' # TC008 +20 - f: TypeAlias = 'Foo | None' # TC008 20 + f: TypeAlias = Foo | None # TC008 -21 | g: TypeAlias = 'OptStr' # OK | TC008 [*] Remove quotes from type alias @@ -67,10 +61,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -21 | g: TypeAlias = 'OptStr' # OK - - h: TypeAlias = 'Bar' # TC008 +22 - h: TypeAlias = 'Bar' # TC008 22 + h: TypeAlias = Bar # TC008 -23 | i: TypeAlias = Foo['str'] # TC008 | TC008 [*] Remove quotes from type alias @@ -85,10 +77,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -22 | h: TypeAlias = 'Bar' # TC008 - - i: TypeAlias = Foo['str'] # TC008 +23 - i: TypeAlias = Foo['str'] # TC008 23 + i: TypeAlias = Foo[str] # TC008 -24 | j: TypeAlias = 'Baz' # OK | TC008 [*] Remove quotes from type alias @@ -103,10 +93,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -25 | k: TypeAlias = 'k | None' # OK - - l: TypeAlias = 'int' | None # TC008 (because TC010 is not enabled) +26 - l: TypeAlias = 'int' | None # TC008 (because TC010 is not enabled) 26 + l: TypeAlias = int | None # TC008 (because TC010 is not enabled) -27 | m: TypeAlias = ('int' # TC008 | TC008 [*] Remove quotes from type alias @@ -121,10 +109,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -26 | l: TypeAlias = 'int' | None # TC008 (because TC010 is not enabled) - - m: TypeAlias = ('int' # TC008 +27 - m: TypeAlias = ('int' # TC008 27 + m: TypeAlias = (int # TC008 -28 | | None) | TC008 [*] Remove quotes from type alias @@ -141,11 +127,9 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -28 | | None) - - n: TypeAlias = ('int' # TC008 (fix removes comment currently) - - ' | None') +29 - n: TypeAlias = ('int' # TC008 (fix removes comment currently) +30 - ' | None') 29 + n: TypeAlias = (int | None) -30 | | note: This is an unsafe fix and may change runtime behavior @@ -161,10 +145,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -31 | - - type B = 'Dict' # TC008 +32 - type B = 'Dict' # TC008 32 + type B = Dict # TC008 -33 | type D = 'Foo[str]' # TC008 | TC008 [*] Remove quotes from type alias @@ -178,10 +160,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -32 | type B = 'Dict' # TC008 - - type D = 'Foo[str]' # TC008 +33 - type D = 'Foo[str]' # TC008 33 + type D = Foo[str] # TC008 -34 | type E = 'Foo.bar' # TC008 | TC008 [*] Remove quotes from type alias @@ -196,10 +176,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -33 | type D = 'Foo[str]' # TC008 - - type E = 'Foo.bar' # TC008 +34 - type E = 'Foo.bar' # TC008 34 + type E = Foo.bar # TC008 -35 | type G = 'OptStr' # TC008 | TC008 [*] Remove quotes from type alias @@ -214,10 +192,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -34 | type E = 'Foo.bar' # TC008 - - type G = 'OptStr' # TC008 +35 - type G = 'OptStr' # TC008 35 + type G = OptStr # TC008 -36 | type I = Foo['str'] # TC008 | TC008 [*] Remove quotes from type alias @@ -232,10 +208,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -35 | type G = 'OptStr' # TC008 - - type I = Foo['str'] # TC008 +36 - type I = Foo['str'] # TC008 36 + type I = Foo[str] # TC008 -37 | type J = 'Baz' # TC008 | TC008 [*] Remove quotes from type alias @@ -250,10 +224,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -36 | type I = Foo['str'] # TC008 - - type J = 'Baz' # TC008 +37 - type J = 'Baz' # TC008 37 + type J = Baz # TC008 -38 | type K = 'K | None' # TC008 | TC008 [*] Remove quotes from type alias @@ -268,10 +240,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -37 | type J = 'Baz' # TC008 - - type K = 'K | None' # TC008 +38 - type K = 'K | None' # TC008 38 + type K = K | None # TC008 -39 | type L = 'int' | None # TC008 (because TC010 is not enabled) | TC008 [*] Remove quotes from type alias @@ -286,10 +256,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -38 | type K = 'K | None' # TC008 - - type L = 'int' | None # TC008 (because TC010 is not enabled) +39 - type L = 'int' | None # TC008 (because TC010 is not enabled) 39 + type L = int | None # TC008 (because TC010 is not enabled) -40 | type M = ('int' # TC008 | TC008 [*] Remove quotes from type alias @@ -304,10 +272,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -39 | type L = 'int' | None # TC008 (because TC010 is not enabled) - - type M = ('int' # TC008 +40 - type M = ('int' # TC008 40 + type M = (int # TC008 -41 | | None) | TC008 [*] Remove quotes from type alias @@ -321,11 +287,9 @@ TC008 [*] Remove quotes from type alias | |_____________^ help: Remove quotes | -41 | | None) - - type N = ('int' # TC008 (fix removes comment currently) - - ' | None') +42 - type N = ('int' # TC008 (fix removes comment currently) +43 - ' | None') 42 + type N = (int | None) -43 | | note: This is an unsafe fix and may change runtime behavior @@ -341,10 +305,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -47 | a: TypeAlias = 'Baz' # OK - - type A = 'Baz' # TC008 +48 - type A = 'Baz' # TC008 48 + type A = Baz # TC008 -49 | | TC008 [*] Remove quotes from type alias @@ -359,10 +321,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -51 | a: TypeAlias = 'Baz' # OK - - type A = 'Baz' # TC008 +52 - type A = 'Baz' # TC008 52 + type A = Baz # TC008 -53 | | TC008 [*] Remove quotes from type alias @@ -378,12 +338,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -54 | # O should have parenthesis added - - o: TypeAlias = """int - - | None""" -55 + o: TypeAlias = (int +55 ~ o: TypeAlias = (int 56 + | None) -57 | type O = """int | TC008 [*] Remove quotes from type alias @@ -400,12 +356,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -56 | | None""" - - type O = """int - - | None""" -57 + type O = (int +57 ~ type O = (int 58 + | None) -59 | | TC008 [*] Remove quotes from type alias @@ -421,12 +373,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -60 | # P, Q, and R should not have parenthesis added - - p: TypeAlias = ("""int - - | None""") -61 + p: TypeAlias = (int -62 + | None) -63 | type P = ("""int +61 ~ p: TypeAlias = (int +62 ~ | None) | TC008 [*] Remove quotes from type alias @@ -443,12 +391,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -62 | | None""") - - type P = ("""int - - | None""") -63 + type P = (int -64 + | None) -65 | +63 ~ type P = (int +64 ~ | None) | TC008 [*] Remove quotes from type alias @@ -465,12 +409,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -65 | - - q: TypeAlias = """(int - - | None)""" -66 + q: TypeAlias = (int +66 ~ q: TypeAlias = (int 67 + | None) -68 | type Q = """(int | TC008 [*] Remove quotes from type alias @@ -487,12 +427,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -67 | | None)""" - - type Q = """(int - - | None)""" -68 + type Q = (int +68 ~ type Q = (int 69 + | None) -70 | | TC008 [*] Remove quotes from type alias @@ -506,10 +442,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -70 | - - r: TypeAlias = """int | None""" +71 - r: TypeAlias = """int | None""" 71 + r: TypeAlias = int | None -72 | type R = """int | None""" | TC008 [*] Remove quotes from type alias @@ -520,7 +454,6 @@ TC008 [*] Remove quotes from type alias | ^^^^^^^^^^^^^^^^ help: Remove quotes | -71 | r: TypeAlias = """int | None""" - - type R = """int | None""" +72 - type R = """int | None""" 72 + type R = int | None | diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quoted-type-alias_TC008_typing_execution_context.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quoted-type-alias_TC008_typing_execution_context.py.snap index 517f8dc7a5d96..414f91a956306 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quoted-type-alias_TC008_typing_execution_context.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__quoted-type-alias_TC008_typing_execution_context.py.snap @@ -13,10 +13,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -12 | - - a: TypeAlias = 'int' # TC008 +13 - a: TypeAlias = 'int' # TC008 13 + a: TypeAlias = int # TC008 -14 | b: TypeAlias = 'Dict' # TC008 | TC008 [*] Remove quotes from type alias @@ -30,10 +28,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -13 | a: TypeAlias = 'int' # TC008 - - b: TypeAlias = 'Dict' # TC008 +14 - b: TypeAlias = 'Dict' # TC008 14 + b: TypeAlias = Dict # TC008 -15 | c: TypeAlias = 'Foo' # TC008 | TC008 [*] Remove quotes from type alias @@ -48,10 +44,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -14 | b: TypeAlias = 'Dict' # TC008 - - c: TypeAlias = 'Foo' # TC008 +15 - c: TypeAlias = 'Foo' # TC008 15 + c: TypeAlias = Foo # TC008 -16 | d: TypeAlias = 'Foo[str]' # TC008 | TC008 [*] Remove quotes from type alias @@ -66,10 +60,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -15 | c: TypeAlias = 'Foo' # TC008 - - d: TypeAlias = 'Foo[str]' # TC008 +16 - d: TypeAlias = 'Foo[str]' # TC008 16 + d: TypeAlias = Foo[str] # TC008 -17 | e: TypeAlias = 'Foo.bar' # TC008 | TC008 [*] Remove quotes from type alias @@ -84,10 +76,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -16 | d: TypeAlias = 'Foo[str]' # TC008 - - e: TypeAlias = 'Foo.bar' # TC008 +17 - e: TypeAlias = 'Foo.bar' # TC008 17 + e: TypeAlias = Foo.bar # TC008 -18 | f: TypeAlias = 'Foo | None' # TC008 | TC008 [*] Remove quotes from type alias @@ -102,10 +92,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -17 | e: TypeAlias = 'Foo.bar' # TC008 - - f: TypeAlias = 'Foo | None' # TC008 +18 - f: TypeAlias = 'Foo | None' # TC008 18 + f: TypeAlias = Foo | None # TC008 -19 | g: TypeAlias = 'OptStr' # TC008 | TC008 [*] Remove quotes from type alias @@ -120,10 +108,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -18 | f: TypeAlias = 'Foo | None' # TC008 - - g: TypeAlias = 'OptStr' # TC008 +19 - g: TypeAlias = 'OptStr' # TC008 19 + g: TypeAlias = OptStr # TC008 -20 | h: TypeAlias = 'Bar' # TC008 | TC008 [*] Remove quotes from type alias @@ -138,10 +124,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -19 | g: TypeAlias = 'OptStr' # TC008 - - h: TypeAlias = 'Bar' # TC008 +20 - h: TypeAlias = 'Bar' # TC008 20 + h: TypeAlias = Bar # TC008 -21 | i: TypeAlias = Foo['str'] # TC008 | TC008 [*] Remove quotes from type alias @@ -156,10 +140,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -20 | h: TypeAlias = 'Bar' # TC008 - - i: TypeAlias = Foo['str'] # TC008 +21 - i: TypeAlias = Foo['str'] # TC008 21 + i: TypeAlias = Foo[str] # TC008 -22 | j: TypeAlias = 'Baz' # OK (this would be treated as use before define) | TC008 [*] Remove quotes from type alias @@ -174,10 +156,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -23 | k: TypeAlias = 'k | None' # False negative in type checking block - - l: TypeAlias = 'int' | None # TC008 (because TC010 is not enabled) +24 - l: TypeAlias = 'int' | None # TC008 (because TC010 is not enabled) 24 + l: TypeAlias = int | None # TC008 (because TC010 is not enabled) -25 | m: TypeAlias = ('int' # TC008 | TC008 [*] Remove quotes from type alias @@ -192,10 +172,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -24 | l: TypeAlias = 'int' | None # TC008 (because TC010 is not enabled) - - m: TypeAlias = ('int' # TC008 +25 - m: TypeAlias = ('int' # TC008 25 + m: TypeAlias = (int # TC008 -26 | | None) | TC008 [*] Remove quotes from type alias @@ -209,10 +187,8 @@ TC008 [*] Remove quotes from type alias | |_________________^ help: Remove quotes | -26 | | None) - - n: TypeAlias = ('int' # TC008 (fix removes comment currently) - - ' | None') +27 - n: TypeAlias = ('int' # TC008 (fix removes comment currently) +28 - ' | None') 27 + n: TypeAlias = (int | None) -28 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-cast-value_TC006.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-cast-value_TC006.py.snap index 36bef6dbce100..b93a57b3104b7 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-cast-value_TC006.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-cast-value_TC006.py.snap @@ -10,10 +10,8 @@ TC006 [*] Add quotes to type expression in `typing.cast()` | ^^^ help: Add quotes | -3 | - - cast(int, 3.0) # TC006 +4 - cast(int, 3.0) # TC006 4 + cast("int", 3.0) # TC006 -5 | | TC006 [*] Add quotes to type expression in `typing.cast()` @@ -25,10 +23,8 @@ TC006 [*] Add quotes to type expression in `typing.cast()` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add quotes | -9 | - - cast(list[tuple[bool | float | int | str]], 3.0) # TC006 +10 - cast(list[tuple[bool | float | int | str]], 3.0) # TC006 10 + cast("list[tuple[bool | float | int | str]]", 3.0) # TC006 -11 | | TC006 [*] Add quotes to type expression in `typing.cast()` @@ -40,10 +36,8 @@ TC006 [*] Add quotes to type expression in `typing.cast()` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add quotes | -15 | - - cast(list[tuple[Union[bool, float, int, str]]], 3.0) # TC006 +16 - cast(list[tuple[Union[bool, float, int, str]]], 3.0) # TC006 16 + cast("list[tuple[Union[bool, float, int, str]]]", 3.0) # TC006 -17 | | TC006 [*] Add quotes to type expression in `typing.cast()` @@ -55,10 +49,8 @@ TC006 [*] Add quotes to type expression in `typing.cast()` | ^^^ help: Add quotes | -39 | - - typecast(int, 3.0) # TC006 +40 - typecast(int, 3.0) # TC006 40 + typecast("int", 3.0) # TC006 -41 | | TC006 [*] Add quotes to type expression in `typing.cast()` @@ -70,10 +62,8 @@ TC006 [*] Add quotes to type expression in `typing.cast()` | ^^^ help: Add quotes | -45 | - - typing.cast(int, 3.0) # TC006 +46 - typing.cast(int, 3.0) # TC006 46 + typing.cast("int", 3.0) # TC006 -47 | | TC006 [*] Add quotes to type expression in `typing.cast()` @@ -85,10 +75,8 @@ TC006 [*] Add quotes to type expression in `typing.cast()` | ^^^^^^^^^^^^^^^^^^^^^ help: Add quotes | -51 | - - t.cast(t.Literal["3.0", '3'], 3.0) # TC006 +52 - t.cast(t.Literal["3.0", '3'], 3.0) # TC006 52 + t.cast("t.Literal['3.0', '3']", 3.0) # TC006 -53 | | TC006 [*] Add quotes to type expression in `typing.cast()` @@ -103,11 +91,9 @@ TC006 [*] Add quotes to type expression in `typing.cast()` | help: Add quotes | -58 | cast( - - int # TC006 (unsafe, because it will get rid of this comment) - - | None, +59 - int # TC006 (unsafe, because it will get rid of this comment) +60 - | None, 59 + "int | None", -60 | 3.0 | note: This is an unsafe fix and may change runtime behavior @@ -120,10 +106,8 @@ TC006 [*] Add quotes to type expression in `typing.cast()` | ^^^^ help: Add quotes | -67 | import typing - - typing.cast(M-()) +68 - typing.cast(M-()) 68 + typing.cast("M - ()") -69 | | TC006 [*] Add quotes to type expression in `typing.cast()` @@ -135,10 +119,8 @@ TC006 [*] Add quotes to type expression in `typing.cast()` | ^^^^^^^^^^^^ help: Add quotes | -74 | - - cast(Literal["A"], 'A') +75 - cast(Literal["A"], 'A') 75 + cast("Literal['A']", 'A') -76 | | TC006 [*] Add quotes to type expression in `typing.cast()` @@ -150,10 +132,8 @@ TC006 [*] Add quotes to type expression in `typing.cast()` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add quotes | -81 | - - cast(list[Annotated["list['Literal[\"A\"]']", "Foo"]], ['A']) +82 - cast(list[Annotated["list['Literal[\"A\"]']", "Foo"]], ['A']) 82 + cast("list[Annotated[list[Literal['A']], 'Foo']]", ['A']) -83 | | TC006 [*] Add quotes to type expression in `typing.cast()` @@ -167,10 +147,8 @@ TC006 [*] Add quotes to type expression in `typing.cast()` | help: Add quotes | -88 | cast( - - int # TC006 +89 - int # TC006 89 + "int" # TC006 -90 | , 6.0 | TC006 [*] Add quotes to type expression in `typing.cast()` @@ -184,10 +162,8 @@ TC006 [*] Add quotes to type expression in `typing.cast()` | help: Add quotes | -97 | - - cast(typ=int, val=3.0) # TC006 +98 - cast(typ=int, val=3.0) # TC006 98 + cast(typ="int", val=3.0) # TC006 -99 | cast(val=3.0, typ=int) # TC006 | TC006 [*] Add quotes to type expression in `typing.cast()` @@ -198,7 +174,6 @@ TC006 [*] Add quotes to type expression in `typing.cast()` | ^^^ help: Add quotes | -98 | cast(typ=int, val=3.0) # TC006 - - cast(val=3.0, typ=int) # TC006 +99 - cast(val=3.0, typ=int) # TC006 99 + cast(val=3.0, typ="int") # TC006 | diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_TC004_1.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_TC004_1.py.snap index c1dfe6e37f6f2..41c09154bb0b2 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_TC004_1.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_TC004_1.py.snap @@ -11,12 +11,9 @@ TC004 [*] Move import `datetime.datetime` out of type-checking block. Import is | -------- Used at runtime here help: Move out of type-checking block | -1 | from typing import TYPE_CHECKING 2 + from datetime import datetime -3 | +3 + 4 | if TYPE_CHECKING: - - from datetime import datetime -5 + pass -6 | x = datetime +5 ~ pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_TC004_11.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_TC004_11.py.snap index 89d4fe9398db5..c9d5ceda3df73 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_TC004_11.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_TC004_11.py.snap @@ -12,12 +12,9 @@ TC004 [*] Move import `typing.List` out of type-checking block. Import is used f | ------ Used at runtime here help: Move out of type-checking block | -1 | from typing import TYPE_CHECKING 2 + from typing import List -3 | +3 + 4 | if TYPE_CHECKING: - - from typing import List -5 + pass -6 | +5 ~ pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_TC004_12.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_TC004_12.py.snap index be666704c77d7..fc4d58b8d15bd 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_TC004_12.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_TC004_12.py.snap @@ -12,12 +12,9 @@ TC004 [*] Move import `collections.abc.Callable` out of type-checking block. Imp | -------- Used at runtime here help: Move out of type-checking block | -3 | from typing import Any, TYPE_CHECKING, TypeAlias 4 + from collections.abc import Callable -5 | +5 + 6 | if TYPE_CHECKING: - - from collections.abc import Callable -7 + pass -8 | +7 ~ pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_TC004_17.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_TC004_17.py.snap index 6c0f3187df265..a24aa218ed11e 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_TC004_17.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_TC004_17.py.snap @@ -15,12 +15,9 @@ TC004 [*] Move import `pandas.DataFrame` out of type-checking block. Import is u | --------- Used at runtime here help: Move out of type-checking block | -3 | from typing_extensions import TYPE_CHECKING 4 + from pandas import DataFrame -5 | +5 + 6 | if TYPE_CHECKING: - - from pandas import DataFrame -7 + pass -8 | +7 ~ pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_TC004_2.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_TC004_2.py.snap index 709bb9b82971e..a262f6a50a77e 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_TC004_2.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_TC004_2.py.snap @@ -15,12 +15,9 @@ TC004 [*] Move import `datetime.date` out of type-checking block. Import is used | ---- Used at runtime here help: Move out of type-checking block | -1 | from typing import TYPE_CHECKING 2 + from datetime import date -3 | +3 + 4 | if TYPE_CHECKING: - - from datetime import date -5 + pass -6 | +5 ~ pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_module__app.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_module__app.py.snap index 08f6454281890..1287611901d1d 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_module__app.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_module__app.py.snap @@ -17,14 +17,10 @@ TC004 [*] Move import `datetime` out of type-checking block. Import is used for 21 | pass | help: Move out of type-checking block - | -6 | from fastapi import FastAPI as Api -7 + import datetime -8 | -9 | if TYPE_CHECKING: - - import datetime # TC004 -10 | from array import array # TC004 - | + | +7 + import datetime +8 + + | note: This is an unsafe fix and may change runtime behavior TC004 [*] Move import `array.array` out of type-checking block. Import is used for more than type hinting. @@ -46,12 +42,7 @@ TC004 [*] Move import `array.array` out of type-checking block. Import is used f | help: Move out of type-checking block | -6 | from fastapi import FastAPI as Api -7 + from array import array -8 | -9 | if TYPE_CHECKING: -10 | import datetime # TC004 - - from array import array # TC004 -11 | + 7 + from array import array + 8 + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_quote.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_quote.py.snap index d8b6f0a655154..43648dcc7aeca 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_quote.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_quote.py.snap @@ -12,12 +12,11 @@ TC004 [*] Move import `pandas.DataFrame` out of type-checking block. Import is u | --------- Used at runtime here help: Move out of type-checking block | -1 + from pandas import DataFrame -2 | def f(): --------------------------------------------------------------------------------- + 1 + from pandas import DataFrame + 2 | def f(): + 3 | from pandas import DataFrame + … 110 | if TYPE_CHECKING: - - from pandas import DataFrame -111 + pass -112 | +111 ~ pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_runtime_evaluated_base_classes_1.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_runtime_evaluated_base_classes_1.py.snap index db0d51de8ed6b..1dfe56824a063 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_runtime_evaluated_base_classes_1.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_runtime_evaluated_base_classes_1.py.snap @@ -16,12 +16,8 @@ TC004 [*] Move import `datetime` out of type-checking block. Import is used for | -------- Used at runtime here help: Move out of type-checking block | -7 | from pydantic import BaseModel -8 + import datetime -9 | -10 | if TYPE_CHECKING: - - import datetime # TC004 -11 | from array import array # TC004 + 8 + import datetime + 9 + | note: This is an unsafe fix and may change runtime behavior @@ -42,13 +38,8 @@ TC004 [*] Move import `array.array` out of type-checking block. Import is used f | ----- Used at runtime here help: Move out of type-checking block | -7 | from pydantic import BaseModel -8 + from array import array -9 | -10 | if TYPE_CHECKING: -11 | import datetime # TC004 - - from array import array # TC004 -12 | + 8 + from array import array + 9 + | note: This is an unsafe fix and may change runtime behavior @@ -68,12 +59,7 @@ TC004 [*] Move import `pandas` out of type-checking block. Import is used for mo | ------ Used at runtime here help: Move out of type-checking block | -7 | from pydantic import BaseModel -8 + import pandas -9 | --------------------------------------------------------------------------------- -13 | - - import pandas # TC004 -14 | import pyproj + 8 + import pandas + 9 + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_runtime_evaluated_decorators_1.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_runtime_evaluated_decorators_1.py.snap index c02544dddfdf0..92ba510daa485 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_runtime_evaluated_decorators_1.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_runtime_evaluated_decorators_1.py.snap @@ -17,12 +17,8 @@ TC004 [*] Move import `datetime` out of type-checking block. Import is used for | -------- Used at runtime here help: Move out of type-checking block | -9 | import numpy 10 + import datetime -11 | -12 | if TYPE_CHECKING: - - import datetime # TC004 -13 | from array import array # TC004 +11 + | note: This is an unsafe fix and may change runtime behavior @@ -44,13 +40,8 @@ TC004 [*] Move import `array.array` out of type-checking block. Import is used f | ----- Used at runtime here help: Move out of type-checking block | -9 | import numpy 10 + from array import array -11 | -12 | if TYPE_CHECKING: -13 | import datetime # TC004 - - from array import array # TC004 -14 | +11 + | note: This is an unsafe fix and may change runtime behavior @@ -71,12 +62,7 @@ TC004 [*] Move import `pandas` out of type-checking block. Import is used for mo | ------ Used at runtime here help: Move out of type-checking block | -9 | import numpy 10 + import pandas -11 | --------------------------------------------------------------------------------- -15 | - - import pandas # TC004 -16 | import pyproj +11 + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_whitespace.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_whitespace.py.snap index f1d806a07f4e0..46fe57d01d46a 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_whitespace.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__runtime-import-in-type-checking-block_whitespace.py.snap @@ -12,12 +12,8 @@ TC004 [*] Move import `builtins` out of type-checking block. Import is used for | -------- Used at runtime here help: Move out of type-checking block | -2 | # there is a (potentially invisible) unicode formfeed character (000C) between `TYPE_CHECKING` and the backslash - - from typing import TYPE_CHECKING \ -3 + from typing import TYPE_CHECKING; import builtins \ +3 ~ from typing import TYPE_CHECKING; import builtins␌\ 4 | - - if TYPE_CHECKING: import builtins -5 + if TYPE_CHECKING: pass -6 | builtins.print("!") +5 ~ if TYPE_CHECKING: pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__strict_typing-only-standard-library-import_init_var.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__strict_typing-only-standard-library-import_init_var.py.snap index 44fc3c1612bcf..24759ff0e90d5 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__strict_typing-only-standard-library-import_init_var.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__strict_typing-only-standard-library-import_init_var.py.snap @@ -12,15 +12,12 @@ TC003 [*] Move standard library import `dataclasses.FrozenInstanceError` into a | help: Move into type-checking block | -4 | - - from dataclasses import FrozenInstanceError, InitVar, dataclass -5 + from dataclasses import InitVar, dataclass -6 | from pathlib import Path -7 + from typing import TYPE_CHECKING -8 + -9 + if TYPE_CHECKING: + 5 + from dataclasses import InitVar, dataclass + 6 | from pathlib import Path + 7 + from typing import TYPE_CHECKING + 8 ~ + 9 + if TYPE_CHECKING: 10 + from dataclasses import FrozenInstanceError -11 | | note: This is an unsafe fix and may change runtime behavior @@ -32,12 +29,10 @@ TC003 [*] Move standard library import `pathlib.Path` into a type-checking block | ^^^^ help: Move into type-checking block | -5 | from dataclasses import FrozenInstanceError, InitVar, dataclass - - from pathlib import Path -6 + from typing import TYPE_CHECKING -7 + -8 + if TYPE_CHECKING: -9 + from pathlib import Path -10 | + 6 + + 7 + from typing import TYPE_CHECKING + 8 ~ + 9 + if TYPE_CHECKING: +10 + from pathlib import Path | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__strict_typing-only-standard-library-import_kw_only.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__strict_typing-only-standard-library-import_kw_only.py.snap index 9769c79b31870..68121936e56a0 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__strict_typing-only-standard-library-import_kw_only.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__strict_typing-only-standard-library-import_kw_only.py.snap @@ -9,14 +9,11 @@ TC003 [*] Move standard library import `dataclasses.Field` into a type-checking 5 | from dataclasses import KW_ONLY, dataclass, Field | ^^^^^ help: Move into type-checking block - | -4 | - - from dataclasses import KW_ONLY, dataclass, Field -5 + from dataclasses import KW_ONLY, dataclass -6 + from typing import TYPE_CHECKING -7 + -8 + if TYPE_CHECKING: -9 + from dataclasses import Field -10 | - | + | +5 + from dataclasses import KW_ONLY, dataclass +6 + from typing import TYPE_CHECKING +7 ~ +8 + if TYPE_CHECKING: +9 + from dataclasses import Field + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__strict_typing-only-third-party-import_strict.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__strict_typing-only-third-party-import_strict.py.snap index d0aa58c683a9a..d64e4ed230445 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__strict_typing-only-third-party-import_strict.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__strict_typing-only-third-party-import_strict.py.snap @@ -13,16 +13,11 @@ TC002 [*] Move third-party import `pkg.A` into a type-checking block | help: Move into type-checking block | -1 | from __future__ import annotations -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + from pkg import A -6 | --------------------------------------------------------------------------------- -30 | import pkg - - from pkg import A -31 | + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + from pkg import A + 6 + | note: This is an unsafe fix and may change runtime behavior @@ -38,17 +33,15 @@ TC002 [*] Move third-party import `pkg.A` into a type-checking block | help: Move into type-checking block | -1 | from __future__ import annotations -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + from pkg import A -6 | --------------------------------------------------------------------------------- + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + from pkg import A + 6 + + 7 | + … 38 | # In un-strict mode, this shouldn't raise an error, since `pkg` is used at runtime. - - from pkg import A, B -39 + from pkg import B -40 | +39 ~ from pkg import B | note: This is an unsafe fix and may change runtime behavior @@ -64,16 +57,11 @@ TC002 [*] Move third-party import `pkg.bar.A` into a type-checking block | help: Move into type-checking block | -1 | from __future__ import annotations -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + from pkg.bar import A -6 | --------------------------------------------------------------------------------- -57 | import pkg - - from pkg.bar import A -58 | + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + from pkg.bar import A + 6 + | note: This is an unsafe fix and may change runtime behavior @@ -88,16 +76,11 @@ TC002 [*] Move third-party import `pkg` into a type-checking block | help: Move into type-checking block | -1 | from __future__ import annotations -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + import pkg -6 | --------------------------------------------------------------------------------- -65 | # In un-strict mode, this shouldn't raise an error, since `pkg.bar` is used at runtime. - - import pkg -66 | import pkg.bar as B + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + import pkg + 6 + | note: This is an unsafe fix and may change runtime behavior @@ -112,16 +95,11 @@ TC002 [*] Move third-party import `pkg.foo` into a type-checking block | help: Move into type-checking block | -1 | from __future__ import annotations -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + import pkg.foo as F -6 | --------------------------------------------------------------------------------- -74 | # In un-strict mode, this shouldn't raise an error, since `pkg.foo.bar` is used at runtime. - - import pkg.foo as F -75 | import pkg.foo.bar as B + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + import pkg.foo as F + 6 + | note: This is an unsafe fix and may change runtime behavior @@ -136,16 +114,11 @@ TC002 [*] Move third-party import `pkg` into a type-checking block | help: Move into type-checking block | -1 | from __future__ import annotations -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + import pkg -6 | --------------------------------------------------------------------------------- -83 | # In un-strict mode, this shouldn't raise an error, since `pkg.foo.bar` is used at runtime. - - import pkg -84 | import pkg.foo.bar as B + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + import pkg + 6 + | note: This is an unsafe fix and may change runtime behavior @@ -160,16 +133,11 @@ TC002 [*] Move third-party import `pkg` into a type-checking block | help: Move into type-checking block | -1 | from __future__ import annotations -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + import pkg -6 | --------------------------------------------------------------------------------- -94 | # testing the implementation. - - import pkg -95 | import pkgfoo.bar as B + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + import pkg + 6 + | note: This is an unsafe fix and may change runtime behavior @@ -185,15 +153,10 @@ TC002 [*] Move third-party import `pkg.foo` into a type-checking block | help: Move into type-checking block | -1 | from __future__ import annotations -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + import pkg.foo as F -6 | --------------------------------------------------------------------------------- -104 | import pkg.bar as B - - import pkg.foo as F -105 | + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + import pkg.foo as F + 6 + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__tc004_precedence_over_tc007.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__tc004_precedence_over_tc007.snap index 566470801b858..3c29850cae9b8 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__tc004_precedence_over_tc007.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__tc004_precedence_over_tc007.snap @@ -13,11 +13,8 @@ TC004 [*] Move import `foo.Foo` out of type-checking block. Import is used for m | --- Used at runtime here help: Move out of type-checking block | -4 | from typing import TYPE_CHECKING, TypeAlias 5 + from foo import Foo 6 | if TYPE_CHECKING: - - from foo import Foo # TC004 -7 + pass # TC004 -8 | +7 ~ pass # TC004 | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__tc010_precedence_over_tc008.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__tc010_precedence_over_tc008.snap index 55c4cdebc4c77..bd50d986151c9 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__tc010_precedence_over_tc008.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__tc010_precedence_over_tc008.snap @@ -12,10 +12,8 @@ TC008 [*] Remove quotes from type alias | help: Remove quotes | -5 | - - a: TypeAlias = 'int | None' # TC008 +6 - a: TypeAlias = 'int | None' # TC008 6 + a: TypeAlias = int | None # TC008 -7 | b: TypeAlias = 'int' | None # TC010 | TC010 Invalid string member in `X | Y`-style union type diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__type_checking_block_after_usage.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__type_checking_block_after_usage.snap index 306f7ca9fcfca..40b3b19c99bcf 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__type_checking_block_after_usage.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__type_checking_block_after_usage.snap @@ -12,13 +12,12 @@ TC002 [*] Move third-party import `pandas` into a type-checking block 8 | def f(x: pd.DataFrame): | help: Move into type-checking block - | -5 | - - import pandas as pd -6 | -7 + if TYPE_CHECKING: -8 + import pandas as pd -9 + -10 | def f(x: pd.DataFrame): - | + | +4 ~ from typing import TYPE_CHECKING +5 | +6 + +7 + +8 + if TYPE_CHECKING: +9 + import pandas as pd + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__type_checking_block_comment.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__type_checking_block_comment.snap index 3de71f359454a..aaea44e290902 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__type_checking_block_comment.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__type_checking_block_comment.snap @@ -13,12 +13,12 @@ TC002 [*] Move third-party import `pandas` into a type-checking block | help: Move into type-checking block | -5 | - - import pandas as pd -6 | -7 | if TYPE_CHECKING: -8 | # This is a comment. -9 + import pandas as pd -10 | import os + 4 ~ from typing import TYPE_CHECKING + 5 | + 6 + + 7 | + 8 | if TYPE_CHECKING: + 9 | # This is a comment. +10 + import pandas as pd | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__type_checking_block_inline.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__type_checking_block_inline.snap index ddbf603eccc05..e422ab3d9543e 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__type_checking_block_inline.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__type_checking_block_inline.snap @@ -13,11 +13,10 @@ TC002 [*] Move third-party import `pandas` into a type-checking block | help: Move into type-checking block | +4 ~ from typing import TYPE_CHECKING 5 | - - import pandas as pd -6 | - - if TYPE_CHECKING: import os -7 + if TYPE_CHECKING: import pandas as pd; import os -8 | +6 + +7 | +8 ~ if TYPE_CHECKING: import pandas as pd; import os | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__type_checking_block_own_line.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__type_checking_block_own_line.snap index 13eccf2ad795c..f561ea1dadbb3 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__type_checking_block_own_line.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__type_checking_block_own_line.snap @@ -13,11 +13,11 @@ TC002 [*] Move third-party import `pandas` into a type-checking block | help: Move into type-checking block | +4 ~ from typing import TYPE_CHECKING 5 | - - import pandas as pd -6 | -7 | if TYPE_CHECKING: -8 + import pandas as pd -9 | import os +6 + +7 | +8 | if TYPE_CHECKING: +9 + import pandas as pd | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-first-party-import_TC001.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-first-party-import_TC001.py.snap index 97cb90654f6e4..ff2c30e188009 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-first-party-import_TC001.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-first-party-import_TC001.py.snap @@ -12,15 +12,10 @@ TC001 [*] Move application import `.TYP001` into a type-checking block | help: Move into type-checking block | -4 | """ -5 + from typing import TYPE_CHECKING -6 + -7 + if TYPE_CHECKING: -8 + from . import TYP001 -9 | --------------------------------------------------------------------------------- -23 | def f(): - - from . import TYP001 -24 | + 5 + from typing import TYPE_CHECKING + 6 ~ + 7 + if TYPE_CHECKING: + 8 + from . import TYP001 + 9 + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_TC003.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_TC003.py.snap index 38053965d3f47..9592f14b4776d 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_TC003.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_TC003.py.snap @@ -12,15 +12,10 @@ TC003 [*] Move standard library import `os` into a type-checking block | help: Move into type-checking block | -4 | """ -5 + from typing import TYPE_CHECKING -6 + -7 + if TYPE_CHECKING: -8 + import os -9 | -10 | -11 | def f(): - - import os -12 | + 5 + from typing import TYPE_CHECKING + 6 ~ + 7 + if TYPE_CHECKING: + 8 + import os + 9 + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_exempt_type_checking_1.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_exempt_type_checking_1.py.snap index d042546b1955f..dec3b78e862e5 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_exempt_type_checking_1.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_exempt_type_checking_1.py.snap @@ -13,12 +13,10 @@ TC003 [*] Move standard library import `typing.Final` into a type-checking block | help: Move into type-checking block | -4 | - - from typing import Final -5 + from typing import TYPE_CHECKING -6 + -7 + if TYPE_CHECKING: -8 + from typing import Final -9 | +5 + +6 + from typing import TYPE_CHECKING +7 ~ +8 + if TYPE_CHECKING: +9 + from typing import Final | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_exempt_type_checking_2.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_exempt_type_checking_2.py.snap index e7ddf864202ef..a9e099ee24f40 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_exempt_type_checking_2.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_exempt_type_checking_2.py.snap @@ -13,12 +13,9 @@ TC003 [*] Move standard library import `typing.Final` into a type-checking block | help: Move into type-checking block | -4 | - - from typing import Final, TYPE_CHECKING 5 + from typing import TYPE_CHECKING -6 + +6 + 7 + if TYPE_CHECKING: 8 + from typing import Final -9 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_exempt_type_checking_3.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_exempt_type_checking_3.py.snap index d9a4c8c98f106..62d22979f34bf 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_exempt_type_checking_3.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_exempt_type_checking_3.py.snap @@ -12,14 +12,11 @@ TC003 [*] Move standard library import `typing.Final` into a type-checking block 7 | Const: Final[dict] = {} | help: Move into type-checking block - | -4 | - - from typing import Final, Mapping -5 + from typing import Mapping -6 + from typing import TYPE_CHECKING -7 + -8 + if TYPE_CHECKING: -9 + from typing import Final -10 | - | + | +5 + from typing import Mapping +6 + from typing import TYPE_CHECKING +7 ~ +8 + if TYPE_CHECKING: +9 + from typing import Final + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_init_var.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_init_var.py.snap index 6309149d40a56..943f5644cc4d5 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_init_var.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_init_var.py.snap @@ -9,12 +9,10 @@ TC003 [*] Move standard library import `pathlib.Path` into a type-checking block | ^^^^ help: Move into type-checking block | -5 | from dataclasses import FrozenInstanceError, InitVar, dataclass - - from pathlib import Path -6 + from typing import TYPE_CHECKING -7 + -8 + if TYPE_CHECKING: -9 + from pathlib import Path -10 | + 6 + + 7 + from typing import TYPE_CHECKING + 8 ~ + 9 + if TYPE_CHECKING: +10 + from pathlib import Path | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_module__undefined.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_module__undefined.py.snap index b3c19763e74e4..ffb9f1dfddf72 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_module__undefined.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_module__undefined.py.snap @@ -10,12 +10,10 @@ TC003 [*] Move standard library import `collections.abc.Sequence` into a type-ch | ^^^^^^^^ help: Move into type-checking block | -2 | - - from collections.abc import Sequence -3 + from typing import TYPE_CHECKING -4 + -5 + if TYPE_CHECKING: -6 + from collections.abc import Sequence -7 | +3 + +4 + from typing import TYPE_CHECKING +5 ~ +6 + if TYPE_CHECKING: +7 + from collections.abc import Sequence | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_runtime_evaluated_base_classes_3.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_runtime_evaluated_base_classes_3.py.snap index 50edc5d6759cb..ba07e84c14a01 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_runtime_evaluated_base_classes_3.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_runtime_evaluated_base_classes_3.py.snap @@ -13,15 +13,13 @@ TC003 [*] Move standard library import `uuid.UUID` into a type-checking block | help: Move into type-checking block | -4 | import pathlib - - from uuid import UUID # TC003 -5 | -6 | import pydantic -7 | from pydantic import BaseModel -8 + from typing import TYPE_CHECKING -9 + -10 + if TYPE_CHECKING: -11 + from uuid import UUID -12 | + 5 + + 6 | + 7 | import pydantic + 8 | from pydantic import BaseModel + 9 + from typing import TYPE_CHECKING +10 ~ +11 + if TYPE_CHECKING: +12 + from uuid import UUID | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_runtime_evaluated_decorators_3.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_runtime_evaluated_decorators_3.py.snap index 2ee8749b0c2a0..083e3c6f1eca7 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_runtime_evaluated_decorators_3.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_runtime_evaluated_decorators_3.py.snap @@ -13,15 +13,13 @@ TC003 [*] Move standard library import `uuid.UUID` into a type-checking block | help: Move into type-checking block | -5 | from dataclasses import dataclass - - from uuid import UUID # TC003 -6 | from collections.abc import Sequence --------------------------------------------------------------------------------- -10 | from attrs import frozen -11 + from typing import TYPE_CHECKING -12 + -13 + if TYPE_CHECKING: -14 + from uuid import UUID -15 | + 6 + + 7 | from collections.abc import Sequence + … +11 | from attrs import frozen +12 + from typing import TYPE_CHECKING +13 ~ +14 + if TYPE_CHECKING: +15 + from uuid import UUID | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_singledispatchmethod.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_singledispatchmethod.py.snap index c84241d1a9dab..e7ae31cb3a533 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_singledispatchmethod.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-standard-library-import_singledispatchmethod.py.snap @@ -12,14 +12,11 @@ TC003 [*] Move standard library import `pathlib.Path` into a type-checking block | help: Move into type-checking block | -3 | from collections.abc import MutableMapping, Mapping - - from pathlib import Path -4 | from functools import singledispatchmethod - - from typing import Union -5 + from typing import Union, TYPE_CHECKING -6 + -7 + if TYPE_CHECKING: -8 + from pathlib import Path -9 | +4 + +5 | from functools import singledispatchmethod +6 ~ from typing import Union, TYPE_CHECKING +7 + +8 + if TYPE_CHECKING: +9 + from pathlib import Path | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_TC002.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_TC002.py.snap index 10e3d78153466..30d3902e5bc29 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_TC002.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_TC002.py.snap @@ -12,16 +12,11 @@ TC002 [*] Move third-party import `pandas` into a type-checking block | help: Move into type-checking block | -1 | """Tests to determine accurate detection of typing-only imports.""" 2 + from typing import TYPE_CHECKING -3 + +3 ~ 4 + if TYPE_CHECKING: 5 + import pandas as pd -6 | -7 | -8 | def f(): - - import pandas as pd # TC002 -9 | +6 + | note: This is an unsafe fix and may change runtime behavior @@ -36,16 +31,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -1 | """Tests to determine accurate detection of typing-only imports.""" -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + from pandas import DataFrame -6 | --------------------------------------------------------------------------------- -14 | def f(): - - from pandas import DataFrame # TC002 -15 | + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + from pandas import DataFrame + 6 + | note: This is an unsafe fix and may change runtime behavior @@ -60,16 +50,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -1 | """Tests to determine accurate detection of typing-only imports.""" -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + from pandas import DataFrame as df -6 | --------------------------------------------------------------------------------- -20 | def f(): - - from pandas import DataFrame as df # TC002 -21 | + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + from pandas import DataFrame as df + 6 + | note: This is an unsafe fix and may change runtime behavior @@ -84,16 +69,11 @@ TC002 [*] Move third-party import `pandas` into a type-checking block | help: Move into type-checking block | -1 | """Tests to determine accurate detection of typing-only imports.""" -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + import pandas as pd -6 | --------------------------------------------------------------------------------- -26 | def f(): - - import pandas as pd # TC002 -27 | + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + import pandas as pd + 6 + | note: This is an unsafe fix and may change runtime behavior @@ -108,16 +88,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -1 | """Tests to determine accurate detection of typing-only imports.""" -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + from pandas import DataFrame -6 | --------------------------------------------------------------------------------- -32 | def f(): - - from pandas import DataFrame # TC002 -33 | + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + from pandas import DataFrame + 6 + | note: This is an unsafe fix and may change runtime behavior @@ -132,16 +107,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -1 | """Tests to determine accurate detection of typing-only imports.""" -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + from pandas import DataFrame as df -6 | --------------------------------------------------------------------------------- -38 | def f(): - - from pandas import DataFrame as df # TC002 -39 | + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + from pandas import DataFrame as df + 6 + | note: This is an unsafe fix and may change runtime behavior @@ -156,16 +126,11 @@ TC002 [*] Move third-party import `pandas` into a type-checking block | help: Move into type-checking block | -1 | """Tests to determine accurate detection of typing-only imports.""" -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + import pandas as pd -6 | --------------------------------------------------------------------------------- -44 | def f(): - - import pandas as pd # TC002 -45 | + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + import pandas as pd + 6 + | note: This is an unsafe fix and may change runtime behavior @@ -180,15 +145,10 @@ TC002 [*] Move third-party import `pandas` into a type-checking block | help: Move into type-checking block | -1 | """Tests to determine accurate detection of typing-only imports.""" -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + import pandas as pd -6 | --------------------------------------------------------------------------------- -50 | def f(): - - import pandas as pd # TC002 -51 | + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + import pandas as pd + 6 + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_quote.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_quote.py.snap index 4ba02e685a682..751606392cd37 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_quote.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_quote.py.snap @@ -12,13 +12,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | - - def f(): 1 + from typing import TYPE_CHECKING -2 + +2 ~ 3 + if TYPE_CHECKING: -4 | from pandas import DataFrame -5 + def f(): -6 | +4 + from pandas import DataFrame +5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -33,15 +31,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from pandas import DataFrame -5 | def f(): --------------------------------------------------------------------------------- -12 | def f(): - - from pandas import DataFrame -13 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from pandas import DataFrame + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -56,15 +50,11 @@ TC002 [*] Move third-party import `pandas` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + import pandas as pd -5 | def f(): --------------------------------------------------------------------------------- -19 | def f(): - - import pandas as pd -20 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + import pandas as pd + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -79,15 +69,11 @@ TC002 [*] Move third-party import `pandas` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + import pandas as pd -5 | def f(): --------------------------------------------------------------------------------- -26 | def f(): - - import pandas as pd -27 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + import pandas as pd + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -102,15 +88,11 @@ TC002 [*] Move third-party import `pandas` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + import pandas as pd -5 | def f(): --------------------------------------------------------------------------------- -33 | def f(): - - import pandas as pd -34 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + import pandas as pd + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -125,15 +107,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from pandas import DataFrame -5 | def f(): --------------------------------------------------------------------------------- -41 | def f(): - - from pandas import DataFrame -42 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from pandas import DataFrame + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -149,15 +127,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from pandas import DataFrame -5 | def f(): --------------------------------------------------------------------------------- -50 | - - from pandas import DataFrame -51 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from pandas import DataFrame + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -172,15 +146,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from pandas import DataFrame, Series -5 | def f(): --------------------------------------------------------------------------------- -67 | def f(): - - from pandas import DataFrame, Series -68 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from pandas import DataFrame, Series + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -195,15 +165,11 @@ TC002 [*] Move third-party import `pandas.Series` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from pandas import DataFrame, Series -5 | def f(): --------------------------------------------------------------------------------- -67 | def f(): - - from pandas import DataFrame, Series -68 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from pandas import DataFrame, Series + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -218,15 +184,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from pandas import DataFrame, Series -5 | def f(): --------------------------------------------------------------------------------- -74 | def f(): - - from pandas import DataFrame, Series -75 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from pandas import DataFrame, Series + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -241,15 +203,11 @@ TC002 [*] Move third-party import `pandas.Series` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from pandas import DataFrame, Series -5 | def f(): --------------------------------------------------------------------------------- -74 | def f(): - - from pandas import DataFrame, Series -75 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from pandas import DataFrame, Series + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -264,15 +222,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from pandas import DataFrame, Series -5 | def f(): --------------------------------------------------------------------------------- -92 | def f(): - - from pandas import DataFrame, Series -93 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from pandas import DataFrame, Series + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior @@ -287,14 +241,10 @@ TC002 [*] Move third-party import `pandas.Series` into a type-checking block | help: Move into type-checking block | -1 + from typing import TYPE_CHECKING -2 + -3 + if TYPE_CHECKING: -4 + from pandas import DataFrame, Series -5 | def f(): --------------------------------------------------------------------------------- -92 | def f(): - - from pandas import DataFrame, Series -93 | + 1 + from typing import TYPE_CHECKING + 2 ~ + 3 + if TYPE_CHECKING: + 4 + from pandas import DataFrame, Series + 5 | def f(): | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_runtime_evaluated_base_classes_2.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_runtime_evaluated_base_classes_2.py.snap index 54b7776d2ef5a..c89e6a3d7e110 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_runtime_evaluated_base_classes_2.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_runtime_evaluated_base_classes_2.py.snap @@ -13,16 +13,14 @@ TC002 [*] Move third-party import `geopandas` into a type-checking block | help: Move into type-checking block | -2 | - - import geopandas as gpd # TC002 -3 | import pydantic --------------------------------------------------------------------------------- -7 | import numpy -8 + from typing import TYPE_CHECKING -9 + -10 + if TYPE_CHECKING: -11 + import geopandas as gpd -12 | + 3 + + 4 | import pydantic + … + 8 | import numpy + 9 + from typing import TYPE_CHECKING +10 ~ +11 + if TYPE_CHECKING: +12 + import geopandas as gpd | note: This is an unsafe fix and may change runtime behavior @@ -37,15 +35,13 @@ TC002 [*] Move third-party import `pyproj` into a type-checking block | help: Move into type-checking block | -4 | import pydantic - - import pyproj # TC002 -5 | from pydantic import BaseModel -6 | -7 | import numpy -8 + from typing import TYPE_CHECKING -9 + -10 + if TYPE_CHECKING: -11 + import pyproj -12 | + 5 + + 6 | from pydantic import BaseModel + 7 | + 8 | import numpy + 9 + from typing import TYPE_CHECKING +10 ~ +11 + if TYPE_CHECKING: +12 + import pyproj | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_runtime_evaluated_decorators_2.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_runtime_evaluated_decorators_2.py.snap index 4365a7675df35..b0f2c419919a7 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_runtime_evaluated_decorators_2.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_runtime_evaluated_decorators_2.py.snap @@ -10,12 +10,10 @@ TC002 [*] Move third-party import `numpy` into a type-checking block | ^^^^^ help: Move into type-checking block | -9 | - - import numpy # TC002 -10 + from typing import TYPE_CHECKING -11 + -12 + if TYPE_CHECKING: -13 + import numpy -14 | +10 + +11 + from typing import TYPE_CHECKING +12 ~ +13 + if TYPE_CHECKING: +14 + import numpy | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_singledispatch.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_singledispatch.py.snap index c1003022d434b..02b72fbf8acb8 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_singledispatch.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_singledispatch.py.snap @@ -13,11 +13,13 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | + 7 ~ from typing import TYPE_CHECKING + 8 | + … 11 | from scipy.sparse import spmatrix - - from pandas import DataFrame -12 | -13 | if TYPE_CHECKING: -14 + from pandas import DataFrame -15 | from numpy import ndarray +12 + +13 | +14 | if TYPE_CHECKING: +15 + from pandas import DataFrame | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_strict.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_strict.py.snap index b432f9a3baee1..61ed933bb466a 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_strict.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_strict.py.snap @@ -13,16 +13,11 @@ TC002 [*] Move third-party import `pkg.bar.A` into a type-checking block | help: Move into type-checking block | -1 | from __future__ import annotations -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + from pkg.bar import A -6 | --------------------------------------------------------------------------------- -57 | import pkg - - from pkg.bar import A -58 | + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + from pkg.bar import A + 6 + | note: This is an unsafe fix and may change runtime behavior @@ -37,15 +32,10 @@ TC002 [*] Move third-party import `pkg` into a type-checking block | help: Move into type-checking block | -1 | from __future__ import annotations -2 + from typing import TYPE_CHECKING -3 + -4 + if TYPE_CHECKING: -5 + import pkg -6 | --------------------------------------------------------------------------------- -94 | # testing the implementation. - - import pkg -95 | import pkgfoo.bar as B + 2 + from typing import TYPE_CHECKING + 3 ~ + 4 + if TYPE_CHECKING: + 5 + import pkg + 6 + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_typing_modules_1.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_typing_modules_1.py.snap index 6657ffe7381a7..8e6cb9b75076b 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_typing_modules_1.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_typing_modules_1.py.snap @@ -12,15 +12,10 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block | help: Move into type-checking block | -3 | from typing_extensions import Self -4 + from typing import TYPE_CHECKING -5 + -6 + if TYPE_CHECKING: -7 + from pandas import DataFrame -8 | -9 | -10 | def func(): - - from pandas import DataFrame -11 | + 4 + from typing import TYPE_CHECKING + 5 ~ + 6 + if TYPE_CHECKING: + 7 + from pandas import DataFrame + 8 + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_typing_modules_2.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_typing_modules_2.py.snap index 521962266cc7b..c25ec6496b931 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_typing_modules_2.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing-only-third-party-import_typing_modules_2.py.snap @@ -11,14 +11,11 @@ TC002 [*] Move third-party import `pandas.DataFrame` into a type-checking block 9 | df: DataFrame | help: Move into type-checking block - | -4 | -5 + if typing_extensions.TYPE_CHECKING: -6 + from pandas import DataFrame -7 + -8 | -9 | def func(): - - from pandas import DataFrame -10 | - | + | +3 ~ import typing_extensions +4 + +5 + if typing_extensions.TYPE_CHECKING: +6 + from pandas import DataFrame +7 + + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing_import_after_package_import.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing_import_after_package_import.snap index f7a23cd441063..aa35a6daf51b8 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing_import_after_package_import.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing_import_after_package_import.snap @@ -12,15 +12,12 @@ TC002 [*] Move third-party import `pandas` into a type-checking block 6 | from typing import TYPE_CHECKING | help: Move into type-checking block - | -3 | - - import pandas as pd -4 | -5 | from typing import TYPE_CHECKING -6 | -7 + if TYPE_CHECKING: -8 + import pandas as pd -9 + -10 | def f(x: pd.DataFrame): - | + | +4 + +5 | +6 ~ from typing import TYPE_CHECKING +7 + +8 + if TYPE_CHECKING: +9 + import pandas as pd + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing_import_before_package_import.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing_import_before_package_import.snap index 306f7ca9fcfca..40b3b19c99bcf 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing_import_before_package_import.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__typing_import_before_package_import.snap @@ -12,13 +12,12 @@ TC002 [*] Move third-party import `pandas` into a type-checking block 8 | def f(x: pd.DataFrame): | help: Move into type-checking block - | -5 | - - import pandas as pd -6 | -7 + if TYPE_CHECKING: -8 + import pandas as pd -9 + -10 | def f(x: pd.DataFrame): - | + | +4 ~ from typing import TYPE_CHECKING +5 | +6 + +7 + +8 + if TYPE_CHECKING: +9 + import pandas as pd + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__unquoted-type-alias_TC007.py.snap b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__unquoted-type-alias_TC007.py.snap index 1f0b7371e176c..80e3624b67969 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__unquoted-type-alias_TC007.py.snap +++ b/crates/ruff_linter/src/rules/flake8_type_checking/snapshots/ruff_linter__rules__flake8_type_checking__tests__unquoted-type-alias_TC007.py.snap @@ -13,10 +13,8 @@ TC007 [*] Add quotes to type alias | help: Add quotes | -14 | b: TypeAlias = Dict # OK - - c: TypeAlias = Foo # TC007 +15 - c: TypeAlias = Foo # TC007 15 + c: TypeAlias = "Foo" # TC007 -16 | d: TypeAlias = Foo | None # TC007 | note: This is an unsafe fix and may change runtime behavior @@ -32,10 +30,8 @@ TC007 [*] Add quotes to type alias | help: Add quotes | -15 | c: TypeAlias = Foo # TC007 - - d: TypeAlias = Foo | None # TC007 +16 - d: TypeAlias = Foo | None # TC007 16 + d: TypeAlias = "Foo | None" # TC007 -17 | e: TypeAlias = OptStr # TC007 | note: This is an unsafe fix and may change runtime behavior @@ -51,10 +47,8 @@ TC007 [*] Add quotes to type alias | help: Add quotes | -16 | d: TypeAlias = Foo | None # TC007 - - e: TypeAlias = OptStr # TC007 +17 - e: TypeAlias = OptStr # TC007 17 + e: TypeAlias = "OptStr" # TC007 -18 | f: TypeAlias = Bar # TC007 | note: This is an unsafe fix and may change runtime behavior @@ -70,10 +64,8 @@ TC007 [*] Add quotes to type alias | help: Add quotes | -17 | e: TypeAlias = OptStr # TC007 - - f: TypeAlias = Bar # TC007 +18 - f: TypeAlias = Bar # TC007 18 + f: TypeAlias = "Bar" # TC007 -19 | g: TypeAlias = Foo | Bar # TC007 x2 | note: This is an unsafe fix and may change runtime behavior @@ -89,10 +81,8 @@ TC007 [*] Add quotes to type alias | help: Add quotes | -18 | f: TypeAlias = Bar # TC007 - - g: TypeAlias = Foo | Bar # TC007 x2 +19 - g: TypeAlias = Foo | Bar # TC007 x2 19 + g: TypeAlias = "Foo | Bar" # TC007 x2 -20 | h: TypeAlias = Foo[str] # TC007 | note: This is an unsafe fix and may change runtime behavior @@ -108,10 +98,8 @@ TC007 [*] Add quotes to type alias | help: Add quotes | -18 | f: TypeAlias = Bar # TC007 - - g: TypeAlias = Foo | Bar # TC007 x2 +19 - g: TypeAlias = Foo | Bar # TC007 x2 19 + g: TypeAlias = "Foo | Bar" # TC007 x2 -20 | h: TypeAlias = Foo[str] # TC007 | note: This is an unsafe fix and may change runtime behavior @@ -127,10 +115,8 @@ TC007 [*] Add quotes to type alias | help: Add quotes | -19 | g: TypeAlias = Foo | Bar # TC007 x2 - - h: TypeAlias = Foo[str] # TC007 +20 - h: TypeAlias = Foo[str] # TC007 20 + h: TypeAlias = "Foo[str]" # TC007 -21 | i: TypeAlias = (Foo | # TC007 x2 (fix removes comment currently) | note: This is an unsafe fix and may change runtime behavior @@ -145,11 +131,9 @@ TC007 [*] Add quotes to type alias | help: Add quotes | -20 | h: TypeAlias = Foo[str] # TC007 - - i: TypeAlias = (Foo | # TC007 x2 (fix removes comment currently) - - Bar) +21 - i: TypeAlias = (Foo | # TC007 x2 (fix removes comment currently) +22 - Bar) 21 + i: TypeAlias = ("Foo | Bar") -22 | | note: This is an unsafe fix and may change runtime behavior @@ -165,10 +149,8 @@ TC007 [*] Add quotes to type alias | help: Add quotes | -20 | h: TypeAlias = Foo[str] # TC007 - - i: TypeAlias = (Foo | # TC007 x2 (fix removes comment currently) - - Bar) +21 - i: TypeAlias = (Foo | # TC007 x2 (fix removes comment currently) +22 - Bar) 21 + i: TypeAlias = ("Foo | Bar") -22 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__PTH201_PTH201.py.snap b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__PTH201_PTH201.py.snap index 5566beeebbef4..2653a0de47cff 100644 --- a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__PTH201_PTH201.py.snap +++ b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__PTH201_PTH201.py.snap @@ -12,10 +12,8 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -5 | # match - - _ = Path(".") +6 - _ = Path(".") 6 + _ = Path() -7 | _ = pth(".") | PTH201 [*] Do not pass the current directory explicitly to `Path` @@ -30,10 +28,8 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -6 | _ = Path(".") - - _ = pth(".") +7 - _ = pth(".") 7 + _ = pth() -8 | _ = PurePath(".") | PTH201 [*] Do not pass the current directory explicitly to `Path` @@ -47,10 +43,8 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -7 | _ = pth(".") - - _ = PurePath(".") +8 - _ = PurePath(".") 8 + _ = PurePath() -9 | _ = Path("") | PTH201 [*] Do not pass the current directory explicitly to `Path` @@ -64,12 +58,10 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` 11 | Path('', ) | help: Remove the current directory argument - | -8 | _ = PurePath(".") - - _ = Path("") -9 + _ = Path() -10 | - | + | +9 - _ = Path("") +9 + _ = Path() + | PTH201 [*] Do not pass the current directory explicitly to `Path` --> PTH201.py:11:6 @@ -83,10 +75,8 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -10 | - - Path('', ) +11 - Path('', ) 11 + Path() -12 | | PTH201 [*] Do not pass the current directory explicitly to `Path` @@ -99,12 +89,10 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -12 | - - Path( - - '', - - ) +13 - Path( +14 - '', +15 - ) 13 + Path() -14 | | PTH201 [*] Do not pass the current directory explicitly to `Path` @@ -117,12 +105,10 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -16 | - - Path( # Comment before argument - - '', - - ) +17 - Path( # Comment before argument +18 - '', +19 - ) 17 + Path() -18 | | note: This is an unsafe fix and may change runtime behavior @@ -136,12 +122,10 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -20 | - - Path( - - '', # EOL comment - - ) +21 - Path( +22 - '', # EOL comment +23 - ) 21 + Path() -22 | | note: This is an unsafe fix and may change runtime behavior @@ -156,13 +140,11 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -24 | - - Path( - - '' # Comment in the middle of implicitly concatenated string - - ".", - - ) +25 - Path( +26 - '' # Comment in the middle of implicitly concatenated string +27 - ".", +28 - ) 25 + Path() -26 | | note: This is an unsafe fix and may change runtime behavior @@ -177,13 +159,11 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -29 | - - Path( - - '' # Comment before comma - - , - - ) +30 - Path( +31 - '' # Comment before comma +32 - , +33 - ) 30 + Path() -31 | | note: This is an unsafe fix and may change runtime behavior @@ -197,12 +177,9 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -35 | Path( - - '', - - ) / "bare" +35 + Path( 36 + "bare", 37 + ) -38 | | PTH201 [*] Do not pass the current directory explicitly to `Path` @@ -215,12 +192,9 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -39 | Path( # Comment before argument - - '', - - ) / ("parenthesized") +39 + Path( # Comment before argument 40 + ("parenthesized"), 41 + ) -42 | | note: This is an unsafe fix and may change runtime behavior @@ -234,12 +208,9 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -43 | Path( - - '', # EOL comment - - ) / ( ("double parenthesized" ) ) +43 + Path( 44 + ( ("double parenthesized" ) ), # EOL comment 45 + ) -46 | | note: This is an unsafe fix and may change runtime behavior @@ -255,16 +226,11 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -46 | - - ( Path( - - '' # Comment in the middle of implicitly concatenated string - - ".", - - ) )/ (("parenthesized path call") 47 + Path( 48 + (("parenthesized path call") -49 | # Comment between closing parentheses +49 + # Comment between closing parentheses 50 + ), -51 | ) +51 + ) | note: This is an unsafe fix and may change runtime behavior @@ -279,12 +245,9 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -54 | Path( - - '' # Comment before comma +54 + Path( 55 + "multiple" # Comment before comma -56 | , - - ) / "multiple" / ( -57 + ) / ( -58 | "frag" # Comment +56 + , +57 ~ ) / ( | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__PTH210_PTH210.py.snap b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__PTH210_PTH210.py.snap index 4e0f8d46276f0..2ae46b3af3768 100644 --- a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__PTH210_PTH210.py.snap +++ b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__PTH210_PTH210.py.snap @@ -13,11 +13,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -21 | path.with_suffix(".") - - path.with_suffix("py") -22 + path.with_suffix(".py") -23 | path.with_suffix(r"s") - | +22 | path.with_suffix(".py") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -32,11 +29,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -22 | path.with_suffix("py") - - path.with_suffix(r"s") -23 + path.with_suffix(r".s") -24 | path.with_suffix(u'' "json") - | +23 | path.with_suffix(r".s") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -50,11 +44,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -23 | path.with_suffix(r"s") - - path.with_suffix(u'' "json") -24 + path.with_suffix(u'.' "json") -25 | path.with_suffix(suffix="js") - | +24 | path.with_suffix(u'.' "json") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -69,11 +60,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -24 | path.with_suffix(u'' "json") - - path.with_suffix(suffix="js") -25 + path.with_suffix(suffix=".js") -26 | - | +25 | path.with_suffix(suffix=".js") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -87,11 +75,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -27 | posix_path.with_suffix(".") - - posix_path.with_suffix("py") -28 + posix_path.with_suffix(".py") -29 | posix_path.with_suffix(r"s") - | +28 | posix_path.with_suffix(".py") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -106,11 +91,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -28 | posix_path.with_suffix("py") - - posix_path.with_suffix(r"s") -29 + posix_path.with_suffix(r".s") -30 | posix_path.with_suffix(u'' "json") - | +29 | posix_path.with_suffix(r".s") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -124,11 +106,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -29 | posix_path.with_suffix(r"s") - - posix_path.with_suffix(u'' "json") -30 + posix_path.with_suffix(u'.' "json") -31 | posix_path.with_suffix(suffix="js") - | +30 | posix_path.with_suffix(u'.' "json") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -143,11 +122,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -30 | posix_path.with_suffix(u'' "json") - - posix_path.with_suffix(suffix="js") -31 + posix_path.with_suffix(suffix=".js") -32 | - | +31 | posix_path.with_suffix(suffix=".js") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -161,11 +137,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -33 | pure_path.with_suffix(".") - - pure_path.with_suffix("py") -34 + pure_path.with_suffix(".py") -35 | pure_path.with_suffix(r"s") - | +34 | pure_path.with_suffix(".py") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -180,11 +153,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -34 | pure_path.with_suffix("py") - - pure_path.with_suffix(r"s") -35 + pure_path.with_suffix(r".s") -36 | pure_path.with_suffix(u'' "json") - | +35 | pure_path.with_suffix(r".s") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -198,11 +168,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -35 | pure_path.with_suffix(r"s") - - pure_path.with_suffix(u'' "json") -36 + pure_path.with_suffix(u'.' "json") -37 | pure_path.with_suffix(suffix="js") - | +36 | pure_path.with_suffix(u'.' "json") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -217,11 +184,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -36 | pure_path.with_suffix(u'' "json") - - pure_path.with_suffix(suffix="js") -37 + pure_path.with_suffix(suffix=".js") -38 | - | +37 | pure_path.with_suffix(suffix=".js") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -235,11 +199,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -39 | pure_posix_path.with_suffix(".") - - pure_posix_path.with_suffix("py") -40 + pure_posix_path.with_suffix(".py") -41 | pure_posix_path.with_suffix(r"s") - | +40 | pure_posix_path.with_suffix(".py") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -254,11 +215,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -40 | pure_posix_path.with_suffix("py") - - pure_posix_path.with_suffix(r"s") -41 + pure_posix_path.with_suffix(r".s") -42 | pure_posix_path.with_suffix(u'' "json") - | +41 | pure_posix_path.with_suffix(r".s") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -272,11 +230,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -41 | pure_posix_path.with_suffix(r"s") - - pure_posix_path.with_suffix(u'' "json") -42 + pure_posix_path.with_suffix(u'.' "json") -43 | pure_posix_path.with_suffix(suffix="js") - | +42 | pure_posix_path.with_suffix(u'.' "json") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -291,11 +246,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -42 | pure_posix_path.with_suffix(u'' "json") - - pure_posix_path.with_suffix(suffix="js") -43 + pure_posix_path.with_suffix(suffix=".js") -44 | - | +43 | pure_posix_path.with_suffix(suffix=".js") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -309,11 +261,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -45 | pure_windows_path.with_suffix(".") - - pure_windows_path.with_suffix("py") -46 + pure_windows_path.with_suffix(".py") -47 | pure_windows_path.with_suffix(r"s") - | +46 | pure_windows_path.with_suffix(".py") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -328,11 +277,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -46 | pure_windows_path.with_suffix("py") - - pure_windows_path.with_suffix(r"s") -47 + pure_windows_path.with_suffix(r".s") -48 | pure_windows_path.with_suffix(u'' "json") - | +47 | pure_windows_path.with_suffix(r".s") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -346,11 +292,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -47 | pure_windows_path.with_suffix(r"s") - - pure_windows_path.with_suffix(u'' "json") -48 + pure_windows_path.with_suffix(u'.' "json") -49 | pure_windows_path.with_suffix(suffix="js") - | +48 | pure_windows_path.with_suffix(u'.' "json") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -365,11 +308,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -48 | pure_windows_path.with_suffix(u'' "json") - - pure_windows_path.with_suffix(suffix="js") -49 + pure_windows_path.with_suffix(suffix=".js") -50 | - | +49 | pure_windows_path.with_suffix(suffix=".js") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -383,11 +323,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -51 | windows_path.with_suffix(".") - - windows_path.with_suffix("py") -52 + windows_path.with_suffix(".py") -53 | windows_path.with_suffix(r"s") - | +52 | windows_path.with_suffix(".py") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -402,11 +339,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -52 | windows_path.with_suffix("py") - - windows_path.with_suffix(r"s") -53 + windows_path.with_suffix(r".s") -54 | windows_path.with_suffix(u'' "json") - | +53 | windows_path.with_suffix(r".s") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -420,11 +354,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -53 | windows_path.with_suffix(r"s") - - windows_path.with_suffix(u'' "json") -54 + windows_path.with_suffix(u'.' "json") -55 | windows_path.with_suffix(suffix="js") - | +54 | windows_path.with_suffix(u'.' "json") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -439,11 +370,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -54 | windows_path.with_suffix(u'' "json") - - windows_path.with_suffix(suffix="js") -55 + windows_path.with_suffix(suffix=".js") -56 | - | +55 | windows_path.with_suffix(suffix=".js") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -457,11 +385,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -57 | Path().with_suffix(".") - - Path().with_suffix("py") -58 + Path().with_suffix(".py") -59 | PosixPath().with_suffix("py") - | +58 | Path().with_suffix(".py") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -476,11 +401,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -58 | Path().with_suffix("py") - - PosixPath().with_suffix("py") -59 + PosixPath().with_suffix(".py") -60 | PurePath().with_suffix("py") - | +59 | PosixPath().with_suffix(".py") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -495,11 +417,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -59 | PosixPath().with_suffix("py") - - PurePath().with_suffix("py") -60 + PurePath().with_suffix(".py") -61 | PurePosixPath().with_suffix("py") - | +60 | PurePath().with_suffix(".py") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -514,11 +433,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -60 | PurePath().with_suffix("py") - - PurePosixPath().with_suffix("py") -61 + PurePosixPath().with_suffix(".py") -62 | PureWindowsPath().with_suffix("py") - | +61 | PurePosixPath().with_suffix(".py") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -532,11 +448,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -61 | PurePosixPath().with_suffix("py") - - PureWindowsPath().with_suffix("py") -62 + PureWindowsPath().with_suffix(".py") -63 | WindowsPath().with_suffix("py") - | +62 | PureWindowsPath().with_suffix(".py") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -551,9 +464,6 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -62 | PureWindowsPath().with_suffix("py") - - WindowsPath().with_suffix("py") -63 + WindowsPath().with_suffix(".py") -64 | - | +63 | WindowsPath().with_suffix(".py") + | + note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__PTH210_PTH210_1.py.snap b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__PTH210_PTH210_1.py.snap index db9856296facd..df85ddb78cd90 100644 --- a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__PTH210_PTH210_1.py.snap +++ b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__PTH210_PTH210_1.py.snap @@ -13,11 +13,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -13 | p.with_suffix(".") - - p.with_suffix("py") -14 + p.with_suffix(".py") -15 | p.with_suffix(r"s") - | +14 | p.with_suffix(".py") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -32,11 +29,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -14 | p.with_suffix("py") - - p.with_suffix(r"s") -15 + p.with_suffix(r".s") -16 | p.with_suffix(u'' "json") - | +15 | p.with_suffix(r".s") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -50,11 +44,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -15 | p.with_suffix(r"s") - - p.with_suffix(u'' "json") -16 + p.with_suffix(u'.' "json") -17 | p.with_suffix(suffix="js") - | +16 | p.with_suffix(u'.' "json") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -69,11 +60,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -16 | p.with_suffix(u'' "json") - - p.with_suffix(suffix="js") -17 + p.with_suffix(suffix=".js") -18 | - | +17 | p.with_suffix(suffix=".js") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -88,11 +76,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -31 | p.with_suffix(".") - - p.with_suffix("py") -32 + p.with_suffix(".py") -33 | p.with_suffix(r"s") - | +32 | p.with_suffix(".py") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -107,11 +92,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -32 | p.with_suffix("py") - - p.with_suffix(r"s") -33 + p.with_suffix(r".s") -34 | p.with_suffix(u'' "json") - | +33 | p.with_suffix(r".s") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -125,11 +107,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -33 | p.with_suffix(r"s") - - p.with_suffix(u'' "json") -34 + p.with_suffix(u'.' "json") -35 | p.with_suffix(suffix="js") - | +34 | p.with_suffix(u'.' "json") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -144,11 +123,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -34 | p.with_suffix(u'' "json") - - p.with_suffix(suffix="js") -35 + p.with_suffix(suffix=".js") -36 | - | +35 | p.with_suffix(suffix=".js") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -163,11 +139,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -49 | p.with_suffix(".") - - p.with_suffix("py") -50 + p.with_suffix(".py") -51 | p.with_suffix(r"s") - | +50 | p.with_suffix(".py") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -182,11 +155,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -50 | p.with_suffix("py") - - p.with_suffix(r"s") -51 + p.with_suffix(r".s") -52 | p.with_suffix(u'' "json") - | +51 | p.with_suffix(r".s") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -200,11 +170,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -51 | p.with_suffix(r"s") - - p.with_suffix(u'' "json") -52 + p.with_suffix(u'.' "json") -53 | p.with_suffix(suffix="js") - | +52 | p.with_suffix(u'.' "json") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -219,11 +186,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -52 | p.with_suffix(u'' "json") - - p.with_suffix(suffix="js") -53 + p.with_suffix(suffix=".js") -54 | - | +53 | p.with_suffix(suffix=".js") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -238,11 +202,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -67 | p.with_suffix(".") - - p.with_suffix("py") -68 + p.with_suffix(".py") -69 | p.with_suffix(r"s") - | +68 | p.with_suffix(".py") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -257,11 +218,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -68 | p.with_suffix("py") - - p.with_suffix(r"s") -69 + p.with_suffix(r".s") -70 | p.with_suffix(u'' "json") - | +69 | p.with_suffix(r".s") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -275,11 +233,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -69 | p.with_suffix(r"s") - - p.with_suffix(u'' "json") -70 + p.with_suffix(u'.' "json") -71 | p.with_suffix(suffix="js") - | +70 | p.with_suffix(u'.' "json") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -294,11 +249,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -70 | p.with_suffix(u'' "json") - - p.with_suffix(suffix="js") -71 + p.with_suffix(suffix=".js") -72 | - | +71 | p.with_suffix(suffix=".js") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -313,11 +265,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -85 | p.with_suffix(".") - - p.with_suffix("py") -86 + p.with_suffix(".py") -87 | p.with_suffix(r"s") - | +86 | p.with_suffix(".py") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -332,11 +281,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -86 | p.with_suffix("py") - - p.with_suffix(r"s") -87 + p.with_suffix(r".s") -88 | p.with_suffix(u'' "json") - | +87 | p.with_suffix(r".s") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -350,11 +296,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -87 | p.with_suffix(r"s") - - p.with_suffix(u'' "json") -88 + p.with_suffix(u'.' "json") -89 | p.with_suffix(suffix="js") - | +88 | p.with_suffix(u'.' "json") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -369,11 +312,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -88 | p.with_suffix(u'' "json") - - p.with_suffix(suffix="js") -89 + p.with_suffix(suffix=".js") -90 | - | +89 | p.with_suffix(suffix=".js") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -388,11 +328,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -103 | p.with_suffix(".") - - p.with_suffix("py") -104 + p.with_suffix(".py") -105 | p.with_suffix(r"s") - | +104 | p.with_suffix(".py") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -407,11 +344,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -104 | p.with_suffix("py") - - p.with_suffix(r"s") -105 + p.with_suffix(r".s") -106 | p.with_suffix(u'' "json") - | +105 | p.with_suffix(r".s") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -425,11 +359,8 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -105 | p.with_suffix(r"s") - - p.with_suffix(u'' "json") -106 + p.with_suffix(u'.' "json") -107 | p.with_suffix(suffix="js") - | +106 | p.with_suffix(u'.' "json") + | + note: This is an unsafe fix and may change runtime behavior PTH210 [*] Dotless suffix passed to `.with_suffix()` @@ -444,9 +375,6 @@ PTH210 [*] Dotless suffix passed to `.with_suffix()` | help: Add a leading dot | -106 | p.with_suffix(u'' "json") - - p.with_suffix(suffix="js") -107 + p.with_suffix(suffix=".js") -108 | - | +107 | p.with_suffix(suffix=".js") + | + note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH123_PTH123.py.snap b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH123_PTH123.py.snap index 0ba78868075ca..de902217af14c 100644 --- a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH123_PTH123.py.snap +++ b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH123_PTH123.py.snap @@ -13,10 +13,11 @@ PTH123 [*] `open()` should be replaced by `Path.open()` | help: Replace with `Path.open()` | +2 ~ from pathlib import Path +3 | +… 7 | - - builtins.open(file=_file) 8 + Path(_file).open() -9 | | PTH123 [*] `open()` should be replaced by `Path.open()` @@ -31,10 +32,11 @@ PTH123 [*] `open()` should be replaced by `Path.open()` | help: Replace with `Path.open()` | -9 | - - open(_file, "r+ ", - 1) + 2 ~ from pathlib import Path + 3 | + … + 9 | 10 + Path(_file).open("r+ ", - 1) -11 | open(mode="wb", file=_file) | PTH123 [*] `open()` should be replaced by `Path.open()` @@ -48,10 +50,11 @@ PTH123 [*] `open()` should be replaced by `Path.open()` | help: Replace with `Path.open()` | + 2 ~ from pathlib import Path + 3 | + … 10 | open(_file, "r+ ", - 1) - - open(mode="wb", file=_file) 11 + Path(_file).open(mode="wb") -12 | open(mode="r+", buffering=-1, file=_file, encoding="utf-8") | PTH123 [*] `open()` should be replaced by `Path.open()` @@ -66,10 +69,11 @@ PTH123 [*] `open()` should be replaced by `Path.open()` | help: Replace with `Path.open()` | + 2 ~ from pathlib import Path + 3 | + … 11 | open(mode="wb", file=_file) - - open(mode="r+", buffering=-1, file=_file, encoding="utf-8") 12 + Path(_file).open(mode="r+", buffering=-1, encoding="utf-8") -13 | open(_file, "r+", - 1, None, None, None, True, None) | PTH123 [*] `open()` should be replaced by `Path.open()` @@ -84,10 +88,11 @@ PTH123 [*] `open()` should be replaced by `Path.open()` | help: Replace with `Path.open()` | + 2 ~ from pathlib import Path + 3 | + … 12 | open(mode="r+", buffering=-1, file=_file, encoding="utf-8") - - open(_file, "r+", - 1, None, None, None, True, None) 13 + Path(_file).open("r+", - 1, None, None, None) -14 | open(_file, "r+", -1, None, None, None, closefd=True, opener=None) | PTH123 [*] `open()` should be replaced by `Path.open()` @@ -102,10 +107,11 @@ PTH123 [*] `open()` should be replaced by `Path.open()` | help: Replace with `Path.open()` | + 2 ~ from pathlib import Path + 3 | + … 13 | open(_file, "r+", - 1, None, None, None, True, None) - - open(_file, "r+", -1, None, None, None, closefd=True, opener=None) 14 + Path(_file).open("r+", -1, None, None, None) -15 | open(_file, mode="r+", buffering=-1, encoding=None, errors=None, newline=None) | PTH123 [*] `open()` should be replaced by `Path.open()` @@ -120,10 +126,11 @@ PTH123 [*] `open()` should be replaced by `Path.open()` | help: Replace with `Path.open()` | + 2 ~ from pathlib import Path + 3 | + … 14 | open(_file, "r+", -1, None, None, None, closefd=True, opener=None) - - open(_file, mode="r+", buffering=-1, encoding=None, errors=None, newline=None) 15 + Path(_file).open(mode="r+", buffering=-1, encoding=None, errors=None, newline=None) -16 | open(_file, f" {r_plus} ", - 1) | PTH123 [*] `open()` should be replaced by `Path.open()` @@ -137,10 +144,11 @@ PTH123 [*] `open()` should be replaced by `Path.open()` | help: Replace with `Path.open()` | + 2 ~ from pathlib import Path + 3 | + … 15 | open(_file, mode="r+", buffering=-1, encoding=None, errors=None, newline=None) - - open(_file, f" {r_plus} ", - 1) 16 + Path(_file).open(f" {r_plus} ", - 1) -17 | open(buffering=- 1, file=_file, encoding= "utf-8") | PTH123 [*] `open()` should be replaced by `Path.open()` @@ -155,10 +163,11 @@ PTH123 [*] `open()` should be replaced by `Path.open()` | help: Replace with `Path.open()` | + 2 ~ from pathlib import Path + 3 | + … 16 | open(_file, f" {r_plus} ", - 1) - - open(buffering=- 1, file=_file, encoding= "utf-8") 17 + Path(_file).open(buffering=- 1, encoding= "utf-8") -18 | | PTH123 `open()` should be replaced by `Path.open()` diff --git a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH201_PTH201.py.snap b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH201_PTH201.py.snap index 5af0ac59be8f4..fecec4d2afe22 100644 --- a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH201_PTH201.py.snap +++ b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH201_PTH201.py.snap @@ -12,10 +12,8 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -5 | # match - - _ = Path(".") +6 - _ = Path(".") 6 + _ = Path() -7 | _ = pth(".") | PTH201 [*] Do not pass the current directory explicitly to `Path` @@ -30,10 +28,8 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -6 | _ = Path(".") - - _ = pth(".") +7 - _ = pth(".") 7 + _ = pth() -8 | _ = PurePath(".") | PTH201 [*] Do not pass the current directory explicitly to `Path` @@ -47,10 +43,8 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -7 | _ = pth(".") - - _ = PurePath(".") +8 - _ = PurePath(".") 8 + _ = PurePath() -9 | _ = Path("") | PTH201 [*] Do not pass the current directory explicitly to `Path` @@ -64,12 +58,10 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` 11 | Path('', ) | help: Remove the current directory argument - | -8 | _ = PurePath(".") - - _ = Path("") -9 + _ = Path() -10 | - | + | +9 - _ = Path("") +9 + _ = Path() + | PTH201 [*] Do not pass the current directory explicitly to `Path` --> PTH201.py:11:6 @@ -83,10 +75,8 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -10 | - - Path('', ) +11 - Path('', ) 11 + Path() -12 | | PTH201 [*] Do not pass the current directory explicitly to `Path` @@ -99,12 +89,10 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -12 | - - Path( - - '', - - ) +13 - Path( +14 - '', +15 - ) 13 + Path() -14 | | PTH201 [*] Do not pass the current directory explicitly to `Path` @@ -117,12 +105,10 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -16 | - - Path( # Comment before argument - - '', - - ) +17 - Path( # Comment before argument +18 - '', +19 - ) 17 + Path() -18 | | note: This is an unsafe fix and may change runtime behavior @@ -136,12 +122,10 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -20 | - - Path( - - '', # EOL comment - - ) +21 - Path( +22 - '', # EOL comment +23 - ) 21 + Path() -22 | | note: This is an unsafe fix and may change runtime behavior @@ -156,13 +140,11 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -24 | - - Path( - - '' # Comment in the middle of implicitly concatenated string - - ".", - - ) +25 - Path( +26 - '' # Comment in the middle of implicitly concatenated string +27 - ".", +28 - ) 25 + Path() -26 | | note: This is an unsafe fix and may change runtime behavior @@ -177,13 +159,11 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -29 | - - Path( - - '' # Comment before comma - - , - - ) +30 - Path( +31 - '' # Comment before comma +32 - , +33 - ) 30 + Path() -31 | | note: This is an unsafe fix and may change runtime behavior @@ -197,12 +177,9 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -35 | Path( - - '', - - ) / "bare" +35 + Path( 36 + "bare", 37 + ) -38 | | PTH201 [*] Do not pass the current directory explicitly to `Path` @@ -215,12 +192,9 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -39 | Path( # Comment before argument - - '', - - ) / ("parenthesized") +39 + Path( # Comment before argument 40 + ("parenthesized"), 41 + ) -42 | | note: This is an unsafe fix and may change runtime behavior @@ -234,12 +208,9 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -43 | Path( - - '', # EOL comment - - ) / ( ("double parenthesized" ) ) +43 + Path( 44 + ( ("double parenthesized" ) ), # EOL comment 45 + ) -46 | | note: This is an unsafe fix and may change runtime behavior @@ -255,16 +226,11 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -46 | - - ( Path( - - '' # Comment in the middle of implicitly concatenated string - - ".", - - ) )/ (("parenthesized path call") 47 + Path( 48 + (("parenthesized path call") -49 | # Comment between closing parentheses +49 + # Comment between closing parentheses 50 + ), -51 | ) +51 + ) | note: This is an unsafe fix and may change runtime behavior @@ -279,13 +245,10 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -54 | Path( - - '' # Comment before comma +54 + Path( 55 + "multiple" # Comment before comma -56 | , - - ) / "multiple" / ( -57 + ) / ( -58 | "frag" # Comment +56 + , +57 ~ ) / ( | note: This is an unsafe fix and may change runtime behavior @@ -301,10 +264,8 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -73 | - - _ = PosixPath(".") +74 - _ = PosixPath(".") 74 + _ = PosixPath() -75 | _ = PurePosixPath(".") | PTH201 [*] Do not pass the current directory explicitly to `Path` @@ -318,10 +279,8 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -74 | _ = PosixPath(".") - - _ = PurePosixPath(".") +75 - _ = PurePosixPath(".") 75 + _ = PurePosixPath() -76 | _ = WindowsPath(".") | PTH201 [*] Do not pass the current directory explicitly to `Path` @@ -336,10 +295,8 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -75 | _ = PurePosixPath(".") - - _ = WindowsPath(".") +76 - _ = WindowsPath(".") 76 + _ = WindowsPath() -77 | _ = PureWindowsPath(".") | PTH201 [*] Do not pass the current directory explicitly to `Path` @@ -353,10 +310,8 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | help: Remove the current directory argument | -76 | _ = WindowsPath(".") - - _ = PureWindowsPath(".") +77 - _ = PureWindowsPath(".") 77 + _ = PureWindowsPath() -78 | _ = PackagePath(".") | PTH201 [*] Do not pass the current directory explicitly to `Path` @@ -368,7 +323,6 @@ PTH201 [*] Do not pass the current directory explicitly to `Path` | ^^^ help: Remove the current directory argument | -77 | _ = PureWindowsPath(".") - - _ = PackagePath(".") +78 - _ = PackagePath(".") 78 + _ = PackagePath() | diff --git a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH202_PTH202.py.snap b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH202_PTH202.py.snap index 1a4120aea658a..ad2564d6c3f77 100644 --- a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH202_PTH202.py.snap +++ b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH202_PTH202.py.snap @@ -11,10 +11,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | -9 | - - os.path.getsize("filename") + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … + 9 | 10 + Path("filename").stat().st_size -11 | os.path.getsize(b"filename") | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -28,10 +29,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 10 | os.path.getsize("filename") - - os.path.getsize(b"filename") 11 + Path(b"filename").stat().st_size -12 | os.path.getsize(Path("filename")) | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -45,10 +47,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 11 | os.path.getsize(b"filename") - - os.path.getsize(Path("filename")) 12 + Path("filename").stat().st_size -13 | os.path.getsize(__file__) | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -63,10 +66,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 12 | os.path.getsize(Path("filename")) - - os.path.getsize(__file__) 13 + Path(__file__).stat().st_size -14 | | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -81,10 +85,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 14 | - - os.path.getsize(filename) 15 + Path(filename).stat().st_size -16 | os.path.getsize(filename1) | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -97,10 +102,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 15 | os.path.getsize(filename) - - os.path.getsize(filename1) 16 + Path(filename1).stat().st_size -17 | os.path.getsize(filename2) | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -115,10 +121,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 16 | os.path.getsize(filename1) - - os.path.getsize(filename2) 17 + Path(filename2).stat().st_size -18 | | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -133,10 +140,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 18 | - - os.path.getsize(filename="filename") 19 + Path("filename").stat().st_size -20 | os.path.getsize(filename=b"filename") | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -150,10 +158,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 19 | os.path.getsize(filename="filename") - - os.path.getsize(filename=b"filename") 20 + Path(b"filename").stat().st_size -21 | os.path.getsize(filename=Path("filename")) | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -167,10 +176,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 20 | os.path.getsize(filename=b"filename") - - os.path.getsize(filename=Path("filename")) 21 + Path("filename").stat().st_size -22 | os.path.getsize(filename=__file__) | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -185,10 +195,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 21 | os.path.getsize(filename=Path("filename")) - - os.path.getsize(filename=__file__) 22 + Path(__file__).stat().st_size -23 | | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -203,10 +214,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 23 | - - getsize("filename") 24 + Path("filename").stat().st_size -25 | getsize(b"filename") | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -220,10 +232,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 24 | getsize("filename") - - getsize(b"filename") 25 + Path(b"filename").stat().st_size -26 | getsize(Path("filename")) | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -237,10 +250,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 25 | getsize(b"filename") - - getsize(Path("filename")) 26 + Path("filename").stat().st_size -27 | getsize(__file__) | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -255,10 +269,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 26 | getsize(Path("filename")) - - getsize(__file__) 27 + Path(__file__).stat().st_size -28 | | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -273,10 +288,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 28 | - - getsize(filename="filename") 29 + Path("filename").stat().st_size -30 | getsize(filename=b"filename") | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -290,10 +306,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 29 | getsize(filename="filename") - - getsize(filename=b"filename") 30 + Path(b"filename").stat().st_size -31 | getsize(filename=Path("filename")) | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -307,10 +324,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 30 | getsize(filename=b"filename") - - getsize(filename=Path("filename")) 31 + Path("filename").stat().st_size -32 | getsize(filename=__file__) | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -325,10 +343,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 31 | getsize(filename=Path("filename")) - - getsize(filename=__file__) 32 + Path(__file__).stat().st_size -33 | | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -343,10 +362,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 33 | - - getsize(filename) 34 + Path(filename).stat().st_size -35 | getsize(filename1) | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -359,10 +379,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 34 | getsize(filename) - - getsize(filename1) 35 + Path(filename1).stat().st_size -36 | getsize(filename2) | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -374,10 +395,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | ^^^^^^^ help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 35 | getsize(filename1) - - getsize(filename2) 36 + Path(filename2).stat().st_size -37 | | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -390,12 +412,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 38 | - - os.path.getsize( - - "filename", # comment - - ) 39 + Path("filename").stat().st_size -40 | | note: This is an unsafe fix and may change runtime behavior @@ -411,15 +432,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 42 | - - os.path.getsize( - - # comment - - "filename" - - , - - # comment - - ) 43 + Path("filename").stat().st_size -44 | | note: This is an unsafe fix and may change runtime behavior @@ -435,14 +452,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 49 | - - os.path.getsize( - - # comment - - b"filename" - - # comment - - ) 50 + Path(b"filename").stat().st_size -51 | | note: This is an unsafe fix and may change runtime behavior @@ -458,13 +472,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 55 | - - os.path.getsize( # comment - - Path(__file__) - - # comment - - ) # comment -56 + Path(__file__).stat().st_size # comment -57 | +56 ~ Path(__file__).stat().st_size # comment | note: This is an unsafe fix and may change runtime behavior @@ -479,11 +491,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 60 | - - getsize( # comment - - "filename") 61 + Path("filename").stat().st_size -62 | | note: This is an unsafe fix and may change runtime behavior @@ -499,13 +511,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 63 | - - getsize( # comment - - b"filename", - - #comment - - ) 64 + Path(b"filename").stat().st_size -65 | | note: This is an unsafe fix and may change runtime behavior @@ -521,10 +531,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 68 | - - os.path.getsize("file" + "name") 69 + Path("file" + "name").stat().st_size -70 | | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -539,15 +550,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 70 | - - getsize \ - - \ - - \ - - ( # comment - - "filename", - - ) 71 + Path("filename").stat().st_size -72 | | note: This is an unsafe fix and may change runtime behavior @@ -563,10 +570,11 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | + 2 ~ from pathlib import Path + 3 | from os.path import getsize + … 77 | - - getsize(Path("filename").resolve()) 78 + Path(Path("filename").resolve()).stat().st_size -79 | | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -578,7 +586,7 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | ^^^^^^^^^^^^^^^ help: Replace with `Path(...).stat().st_size` | +80 ~ import pathlib 81 | - - os.path.getsize(pathlib.Path("filename")) 82 + pathlib.Path("filename").stat().st_size | diff --git a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH202_PTH202_2.py.snap b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH202_PTH202_2.py.snap index 1d644eb58ad5f..93dc2963ce9df 100644 --- a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH202_PTH202_2.py.snap +++ b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH202_PTH202_2.py.snap @@ -13,12 +13,9 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | -1 | import os 2 + import pathlib -3 | - - os.path.getsize(filename="filename") +3 + 4 + pathlib.Path("filename").stat().st_size -5 | os.path.getsize(filename=b"filename") | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -31,13 +28,10 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | help: Replace with `Path(...).stat().st_size` | -1 | import os 2 + import pathlib -3 | +3 + 4 | os.path.getsize(filename="filename") - - os.path.getsize(filename=b"filename") 5 + pathlib.Path(b"filename").stat().st_size -6 | os.path.getsize(filename=__file__) | PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` @@ -49,11 +43,9 @@ PTH202 [*] `os.path.getsize` should be replaced by `Path.stat().st_size` | ^^^^^^^^^^^^^^^ help: Replace with `Path(...).stat().st_size` | -1 | import os 2 + import pathlib -3 | +3 + 4 | os.path.getsize(filename="filename") 5 | os.path.getsize(filename=b"filename") - - os.path.getsize(filename=__file__) 6 + pathlib.Path(__file__).stat().st_size | diff --git a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH203_PTH203.py.snap b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH203_PTH203.py.snap index 8e855df1b5176..483c247a2eeb7 100644 --- a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH203_PTH203.py.snap +++ b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH203_PTH203.py.snap @@ -13,10 +13,10 @@ PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` | help: Replace with `Path.stat(...).st_atime` | +2 ~ from pathlib import Path +3 | from os.path import getatime 4 | - - os.path.getatime("filename") 5 + Path("filename").stat().st_atime -6 | os.path.getatime(b"filename") | PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` @@ -29,10 +29,11 @@ PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` | help: Replace with `Path.stat(...).st_atime` | +2 ~ from pathlib import Path +3 | from os.path import getatime +4 | 5 | os.path.getatime("filename") - - os.path.getatime(b"filename") 6 + Path(b"filename").stat().st_atime -7 | os.path.getatime(Path("filename")) | PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` @@ -44,10 +45,11 @@ PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` | ^^^^^^^^^^^^^^^^ help: Replace with `Path.stat(...).st_atime` | +2 ~ from pathlib import Path +3 | from os.path import getatime +… 6 | os.path.getatime(b"filename") - - os.path.getatime(Path("filename")) 7 + Path("filename").stat().st_atime -8 | | PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` @@ -60,10 +62,11 @@ PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` | help: Replace with `Path.stat(...).st_atime` | -9 | - - getatime("filename") + 2 ~ from pathlib import Path + 3 | from os.path import getatime + … + 9 | 10 + Path("filename").stat().st_atime -11 | getatime(b"filename") | PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` @@ -76,10 +79,11 @@ PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` | help: Replace with `Path.stat(...).st_atime` | + 2 ~ from pathlib import Path + 3 | from os.path import getatime + … 10 | getatime("filename") - - getatime(b"filename") 11 + Path(b"filename").stat().st_atime -12 | getatime(Path("filename")) | PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` @@ -91,10 +95,11 @@ PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` | ^^^^^^^^ help: Replace with `Path.stat(...).st_atime` | + 2 ~ from pathlib import Path + 3 | from os.path import getatime + … 11 | getatime(b"filename") - - getatime(Path("filename")) 12 + Path("filename").stat().st_atime -13 | | PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` @@ -109,10 +114,11 @@ PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` | help: Replace with `Path.stat(...).st_atime` | + 2 ~ from pathlib import Path + 3 | from os.path import getatime + … 16 | - - os.path.getatime(file) 17 + Path(file).stat().st_atime -18 | os.path.getatime(filename="filename") | PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` @@ -125,10 +131,11 @@ PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` | help: Replace with `Path.stat(...).st_atime` | + 2 ~ from pathlib import Path + 3 | from os.path import getatime + … 17 | os.path.getatime(file) - - os.path.getatime(filename="filename") 18 + Path("filename").stat().st_atime -19 | os.path.getatime(filename=Path("filename")) | PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` @@ -143,10 +150,11 @@ PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` | help: Replace with `Path.stat(...).st_atime` | + 2 ~ from pathlib import Path + 3 | from os.path import getatime + … 18 | os.path.getatime(filename="filename") - - os.path.getatime(filename=Path("filename")) 19 + Path("filename").stat().st_atime -20 | | PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` @@ -161,16 +169,11 @@ PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` | help: Replace with `Path.stat(...).st_atime` | + 2 ~ from pathlib import Path + 3 | from os.path import getatime + … 20 | - - os.path.getatime( # comment 1 - - # comment 2 - - "filename" # comment 3 - - # comment 4 - - , # comment 5 - - # comment 6 - - ) # comment 7 -21 + Path("filename").stat().st_atime # comment 7 -22 | +21 ~ Path("filename").stat().st_atime # comment 7 | note: This is an unsafe fix and may change runtime behavior @@ -186,10 +189,11 @@ PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` | help: Replace with `Path.stat(...).st_atime` | + 2 ~ from pathlib import Path + 3 | from os.path import getatime + … 28 | - - os.path.getatime("file" + "name") 29 + Path("file" + "name").stat().st_atime -30 | | PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` @@ -204,10 +208,11 @@ PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` | help: Replace with `Path.stat(...).st_atime` | + 2 ~ from pathlib import Path + 3 | from os.path import getatime + … 30 | - - getatime(Path("filename").resolve()) 31 + Path(Path("filename").resolve()).stat().st_atime -32 | | PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` @@ -222,10 +227,11 @@ PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` | help: Replace with `Path.stat(...).st_atime` | + 2 ~ from pathlib import Path + 3 | from os.path import getatime + … 32 | - - os.path.getatime(pathlib.Path("filename")) 33 + pathlib.Path("filename").stat().st_atime -34 | | PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` @@ -237,7 +243,9 @@ PTH203 [*] `os.path.getatime` should be replaced by `Path.stat().st_atime` | ^^^^^^^^ help: Replace with `Path.stat(...).st_atime` | + 2 ~ from pathlib import Path + 3 | from os.path import getatime + … 34 | - - getatime(Path("dir") / "file.txt") 35 + Path(Path("dir") / "file.txt").stat().st_atime | diff --git a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH204_PTH204.py.snap b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH204_PTH204.py.snap index 58cdff1799596..b0dc088e4c484 100644 --- a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH204_PTH204.py.snap +++ b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH204_PTH204.py.snap @@ -11,10 +11,11 @@ PTH204 [*] `os.path.getmtime` should be replaced by `Path.stat().st_mtime` | help: Replace with `Path.stat(...).st_mtime` | +2 ~ from pathlib import Path +3 | from os.path import getmtime +4 | 5 | - - os.path.getmtime("filename") 6 + Path("filename").stat().st_mtime -7 | os.path.getmtime(b"filename") | PTH204 [*] `os.path.getmtime` should be replaced by `Path.stat().st_mtime` @@ -27,10 +28,11 @@ PTH204 [*] `os.path.getmtime` should be replaced by `Path.stat().st_mtime` | help: Replace with `Path.stat(...).st_mtime` | +2 ~ from pathlib import Path +3 | from os.path import getmtime +… 6 | os.path.getmtime("filename") - - os.path.getmtime(b"filename") 7 + Path(b"filename").stat().st_mtime -8 | os.path.getmtime(Path("filename")) | PTH204 [*] `os.path.getmtime` should be replaced by `Path.stat().st_mtime` @@ -42,10 +44,11 @@ PTH204 [*] `os.path.getmtime` should be replaced by `Path.stat().st_mtime` | ^^^^^^^^^^^^^^^^ help: Replace with `Path.stat(...).st_mtime` | +2 ~ from pathlib import Path +3 | from os.path import getmtime +… 7 | os.path.getmtime(b"filename") - - os.path.getmtime(Path("filename")) 8 + Path("filename").stat().st_mtime -9 | | PTH204 [*] `os.path.getmtime` should be replaced by `Path.stat().st_mtime` @@ -58,10 +61,11 @@ PTH204 [*] `os.path.getmtime` should be replaced by `Path.stat().st_mtime` | help: Replace with `Path.stat(...).st_mtime` | + 2 ~ from pathlib import Path + 3 | from os.path import getmtime + … 10 | - - getmtime("filename") 11 + Path("filename").stat().st_mtime -12 | getmtime(b"filename") | PTH204 [*] `os.path.getmtime` should be replaced by `Path.stat().st_mtime` @@ -74,10 +78,11 @@ PTH204 [*] `os.path.getmtime` should be replaced by `Path.stat().st_mtime` | help: Replace with `Path.stat(...).st_mtime` | + 2 ~ from pathlib import Path + 3 | from os.path import getmtime + … 11 | getmtime("filename") - - getmtime(b"filename") 12 + Path(b"filename").stat().st_mtime -13 | getmtime(Path("filename")) | PTH204 [*] `os.path.getmtime` should be replaced by `Path.stat().st_mtime` @@ -89,7 +94,9 @@ PTH204 [*] `os.path.getmtime` should be replaced by `Path.stat().st_mtime` | ^^^^^^^^ help: Replace with `Path.stat(...).st_mtime` | + 2 ~ from pathlib import Path + 3 | from os.path import getmtime + … 12 | getmtime(b"filename") - - getmtime(Path("filename")) 13 + Path("filename").stat().st_mtime | diff --git a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH205_PTH205.py.snap b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH205_PTH205.py.snap index 1a124d5b1bf35..2efbe77b214b8 100644 --- a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH205_PTH205.py.snap +++ b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview__PTH205_PTH205.py.snap @@ -11,10 +11,11 @@ PTH205 [*] `os.path.getctime` should be replaced by `Path.stat().st_ctime` | help: Replace with `Path.stat(...).st_ctime` | +2 ~ from pathlib import Path +3 | from os.path import getctime +4 | 5 | - - os.path.getctime("filename") 6 + Path("filename").stat().st_ctime -7 | os.path.getctime(b"filename") | PTH205 [*] `os.path.getctime` should be replaced by `Path.stat().st_ctime` @@ -27,10 +28,11 @@ PTH205 [*] `os.path.getctime` should be replaced by `Path.stat().st_ctime` | help: Replace with `Path.stat(...).st_ctime` | +2 ~ from pathlib import Path +3 | from os.path import getctime +… 6 | os.path.getctime("filename") - - os.path.getctime(b"filename") 7 + Path(b"filename").stat().st_ctime -8 | os.path.getctime(Path("filename")) | PTH205 [*] `os.path.getctime` should be replaced by `Path.stat().st_ctime` @@ -45,10 +47,11 @@ PTH205 [*] `os.path.getctime` should be replaced by `Path.stat().st_ctime` | help: Replace with `Path.stat(...).st_ctime` | +2 ~ from pathlib import Path +3 | from os.path import getctime +… 7 | os.path.getctime(b"filename") - - os.path.getctime(Path("filename")) 8 + Path("filename").stat().st_ctime -9 | | PTH205 [*] `os.path.getctime` should be replaced by `Path.stat().st_ctime` @@ -63,10 +66,11 @@ PTH205 [*] `os.path.getctime` should be replaced by `Path.stat().st_ctime` | help: Replace with `Path.stat(...).st_ctime` | -9 | - - getctime("filename") + 2 ~ from pathlib import Path + 3 | from os.path import getctime + … + 9 | 10 + Path("filename").stat().st_ctime -11 | getctime(b"filename") | PTH205 [*] `os.path.getctime` should be replaced by `Path.stat().st_ctime` @@ -79,10 +83,11 @@ PTH205 [*] `os.path.getctime` should be replaced by `Path.stat().st_ctime` | help: Replace with `Path.stat(...).st_ctime` | + 2 ~ from pathlib import Path + 3 | from os.path import getctime + … 10 | getctime("filename") - - getctime(b"filename") 11 + Path(b"filename").stat().st_ctime -12 | getctime(Path("filename")) | PTH205 [*] `os.path.getctime` should be replaced by `Path.stat().st_ctime` @@ -94,7 +99,9 @@ PTH205 [*] `os.path.getctime` should be replaced by `Path.stat().st_ctime` | ^^^^^^^^ help: Replace with `Path.stat(...).st_ctime` | + 2 ~ from pathlib import Path + 3 | from os.path import getctime + … 11 | getctime(b"filename") - - getctime(Path("filename")) 12 + Path("filename").stat().st_ctime | diff --git a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview_full_name.py.snap b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview_full_name.py.snap index 968f293563c35..d86029fef4f22 100644 --- a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview_full_name.py.snap +++ b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview_full_name.py.snap @@ -13,15 +13,12 @@ PTH100 [*] `os.path.abspath()` should be replaced by `Path.resolve()` | help: Replace with `Path(...).resolve()` | -2 | import os.path 3 + import pathlib -4 | +4 + 5 | p = "/foo" 6 | q = "bar" 7 | - - a = os.path.abspath(p) -8 + a = pathlib.Path(p).resolve() -9 | aa = os.chmod(p) +8 ~ a = pathlib.Path(p).resolve() | note: This is an unsafe fix and may change runtime behavior @@ -48,14 +45,12 @@ PTH102 [*] `os.mkdir()` should be replaced by `Path.mkdir()` | help: Replace with `Path(...).mkdir()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- -9 | aa = os.chmod(p) - - aaa = os.mkdir(p) -10 + aaa = pathlib.Path(p).mkdir() -11 | os.makedirs(p) + 3 + import pathlib + 4 + + 5 | p = "/foo" + … + 9 | aa = os.chmod(p) +10 ~ aaa = pathlib.Path(p).mkdir() | PTH103 [*] `os.makedirs()` should be replaced by `Path.mkdir(parents=True)` @@ -70,14 +65,12 @@ PTH103 [*] `os.makedirs()` should be replaced by `Path.mkdir(parents=True)` | help: Replace with `Path(...).mkdir(parents=True)` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 10 | aaa = os.mkdir(p) - - os.makedirs(p) 11 + pathlib.Path(p).mkdir(parents=True) -12 | os.rename(p) | PTH104 `os.rename()` should be replaced by `Path.rename()` @@ -116,14 +109,12 @@ PTH106 [*] `os.rmdir()` should be replaced by `Path.rmdir()` | help: Replace with `Path(...).rmdir()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 13 | os.replace(p) - - os.rmdir(p) 14 + pathlib.Path(p).rmdir() -15 | os.remove(p) | PTH107 [*] `os.remove()` should be replaced by `Path.unlink()` @@ -138,14 +129,12 @@ PTH107 [*] `os.remove()` should be replaced by `Path.unlink()` | help: Replace with `Path(...).unlink()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 14 | os.rmdir(p) - - os.remove(p) 15 + pathlib.Path(p).unlink() -16 | os.unlink(p) | PTH108 [*] `os.unlink()` should be replaced by `Path.unlink()` @@ -160,14 +149,12 @@ PTH108 [*] `os.unlink()` should be replaced by `Path.unlink()` | help: Replace with `Path(...).unlink()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 15 | os.remove(p) - - os.unlink(p) 16 + pathlib.Path(p).unlink() -17 | os.getcwd(p) | PTH109 `os.getcwd()` should be replaced by `Path.cwd()` @@ -194,14 +181,12 @@ PTH110 [*] `os.path.exists()` should be replaced by `Path.exists()` | help: Replace with `Path(...).exists()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 17 | os.getcwd(p) - - b = os.path.exists(p) -18 + b = pathlib.Path(p).exists() -19 | bb = os.path.expanduser(p) +18 ~ b = pathlib.Path(p).exists() | PTH111 [*] `os.path.expanduser()` should be replaced by `Path.expanduser()` @@ -216,14 +201,12 @@ PTH111 [*] `os.path.expanduser()` should be replaced by `Path.expanduser()` | help: Replace with `Path(...).expanduser()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 18 | b = os.path.exists(p) - - bb = os.path.expanduser(p) -19 + bb = pathlib.Path(p).expanduser() -20 | bbb = os.path.isdir(p) +19 ~ bb = pathlib.Path(p).expanduser() | note: This is an unsafe fix and may change runtime behavior @@ -239,14 +222,12 @@ PTH112 [*] `os.path.isdir()` should be replaced by `Path.is_dir()` | help: Replace with `Path(...).is_dir()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 19 | bb = os.path.expanduser(p) - - bbb = os.path.isdir(p) -20 + bbb = pathlib.Path(p).is_dir() -21 | bbbb = os.path.isfile(p) +20 ~ bbb = pathlib.Path(p).is_dir() | PTH113 [*] `os.path.isfile()` should be replaced by `Path.is_file()` @@ -261,14 +242,12 @@ PTH113 [*] `os.path.isfile()` should be replaced by `Path.is_file()` | help: Replace with `Path(...).is_file()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 20 | bbb = os.path.isdir(p) - - bbbb = os.path.isfile(p) -21 + bbbb = pathlib.Path(p).is_file() -22 | bbbbb = os.path.islink(p) +21 ~ bbbb = pathlib.Path(p).is_file() | PTH114 [*] `os.path.islink()` should be replaced by `Path.is_symlink()` @@ -283,14 +262,12 @@ PTH114 [*] `os.path.islink()` should be replaced by `Path.is_symlink()` | help: Replace with `Path(...).is_symlink()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 21 | bbbb = os.path.isfile(p) - - bbbbb = os.path.islink(p) -22 + bbbbb = pathlib.Path(p).is_symlink() -23 | os.readlink(p) +22 ~ bbbbb = pathlib.Path(p).is_symlink() | PTH115 [*] `os.readlink()` should be replaced by `Path.readlink()` @@ -305,14 +282,12 @@ PTH115 [*] `os.readlink()` should be replaced by `Path.readlink()` | help: Replace with `Path(...).readlink()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 22 | bbbbb = os.path.islink(p) - - os.readlink(p) 23 + pathlib.Path(p).readlink() -24 | os.stat(p) | PTH116 `os.stat()` should be replaced by `Path.stat()`, `Path.owner()`, or `Path.group()` @@ -338,14 +313,12 @@ PTH117 [*] `os.path.isabs()` should be replaced by `Path.is_absolute()` | help: Replace with `Path(...).is_absolute()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 24 | os.stat(p) - - os.path.isabs(p) 25 + pathlib.Path(p).is_absolute() -26 | os.path.join(p, q) | PTH118 `os.path.join()` should be replaced by `Path` with `/` operator @@ -393,14 +366,12 @@ PTH119 [*] `os.path.basename()` should be replaced by `Path.name` | help: Replace with `Path(...).name` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 28 | os.sep.join((p, q)) - - os.path.basename(p) 29 + pathlib.Path(p).name -30 | os.path.dirname(p) | note: This is an unsafe fix and may change runtime behavior @@ -416,14 +387,12 @@ PTH120 [*] `os.path.dirname()` should be replaced by `Path.parent` | help: Replace with `Path(...).parent` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 29 | os.path.basename(p) - - os.path.dirname(p) 30 + pathlib.Path(p).parent -31 | os.path.samefile(p) | note: This is an unsafe fix and may change runtime behavior @@ -462,14 +431,12 @@ PTH123 [*] `open()` should be replaced by `Path.open()` | help: Replace with `Path.open()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 32 | os.path.splitext(p) - - with open(p) as fp: -33 + with pathlib.Path(p).open() as fp: -34 | fp.read() +33 ~ with pathlib.Path(p).open() as fp: | PTH123 [*] `open()` should be replaced by `Path.open()` @@ -484,14 +451,12 @@ PTH123 [*] `open()` should be replaced by `Path.open()` | help: Replace with `Path.open()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 34 | fp.read() - - open(p).close() -35 + pathlib.Path(p).open().close() -36 | os.getcwdb(p) +35 ~ pathlib.Path(p).open().close() | PTH109 `os.getcwd()` should be replaced by `Path.cwd()` @@ -539,14 +504,12 @@ PTH123 [*] `open()` should be replaced by `Path.open()` | help: Replace with `Path.open()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 46 | open(p, opener=opener) - - open(p, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) 47 + pathlib.Path(p).open(mode='r', buffering=-1, encoding=None, errors=None, newline=None) -48 | open(p, 'r', - 1, None, None, None, True, None) | PTH123 [*] `open()` should be replaced by `Path.open()` @@ -560,14 +523,12 @@ PTH123 [*] `open()` should be replaced by `Path.open()` | help: Replace with `Path.open()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 47 | open(p, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) - - open(p, 'r', - 1, None, None, None, True, None) 48 + pathlib.Path(p).open('r', - 1, None, None, None) -49 | open(p, 'r', - 1, None, None, None, False, opener) | PTH123 [*] `open()` should be replaced by `Path.open()` @@ -582,14 +543,12 @@ PTH123 [*] `open()` should be replaced by `Path.open()` | help: Replace with `Path.open()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 65 | - - open(b"foo") 66 + pathlib.Path(b"foo").open() -67 | byte_str = b"bar" | PTH123 [*] `open()` should be replaced by `Path.open()` @@ -604,14 +563,12 @@ PTH123 [*] `open()` should be replaced by `Path.open()` | help: Replace with `Path.open()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 67 | byte_str = b"bar" - - open(byte_str) 68 + pathlib.Path(byte_str).open() -69 | | PTH123 [*] `open()` should be replaced by `Path.open()` @@ -626,14 +583,12 @@ PTH123 [*] `open()` should be replaced by `Path.open()` | help: Replace with `Path.open()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 71 | return b"foo" - - open(bytes_str_func()) 72 + pathlib.Path(bytes_str_func()).open() -73 | | PTH109 [*] `os.getcwd()` should be replaced by `Path.cwd()` @@ -647,14 +602,12 @@ PTH109 [*] `os.getcwd()` should be replaced by `Path.cwd()` | help: Replace with `Path.cwd()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 108 | - - os.getcwd() 109 + pathlib.Path.cwd() -110 | os.getcwdb() | PTH109 [*] `os.getcwd()` should be replaced by `Path.cwd()` @@ -668,14 +621,12 @@ PTH109 [*] `os.getcwd()` should be replaced by `Path.cwd()` | help: Replace with `Path.cwd()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 109 | os.getcwd() - - os.getcwdb() 110 + pathlib.Path.cwd() -111 | | PTH102 [*] `os.mkdir()` should be replaced by `Path.mkdir()` @@ -690,14 +641,12 @@ PTH102 [*] `os.mkdir()` should be replaced by `Path.mkdir()` | help: Replace with `Path(...).mkdir()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 111 | - - os.mkdir(path="directory") 112 + pathlib.Path("directory").mkdir() -113 | | PTH102 [*] `os.mkdir()` should be replaced by `Path.mkdir()` @@ -712,18 +661,12 @@ PTH102 [*] `os.mkdir()` should be replaced by `Path.mkdir()` | help: Replace with `Path(...).mkdir()` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 113 | - - os.mkdir( - - # comment 1 - - "directory", - - mode=0o777 - - ) 114 + pathlib.Path("directory").mkdir(mode=0o777) -115 | | note: This is an unsafe fix and may change runtime behavior @@ -739,14 +682,12 @@ PTH103 [*] `os.makedirs()` should be replaced by `Path.mkdir(parents=True)` | help: Replace with `Path(...).mkdir(parents=True)` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 121 | - - os.makedirs("name", 0o777, exist_ok=False) 122 + pathlib.Path("name").mkdir(0o777, exist_ok=False, parents=True) -123 | | PTH103 [*] `os.makedirs()` should be replaced by `Path.mkdir(parents=True)` @@ -761,14 +702,12 @@ PTH103 [*] `os.makedirs()` should be replaced by `Path.mkdir(parents=True)` | help: Replace with `Path(...).mkdir(parents=True)` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 123 | - - os.makedirs("name", 0o777, False) 124 + pathlib.Path("name").mkdir(0o777, True, False) -125 | | PTH103 [*] `os.makedirs()` should be replaced by `Path.mkdir(parents=True)` @@ -783,14 +722,12 @@ PTH103 [*] `os.makedirs()` should be replaced by `Path.mkdir(parents=True)` | help: Replace with `Path(...).mkdir(parents=True)` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 125 | - - os.makedirs(name="name", mode=0o777, exist_ok=False) 126 + pathlib.Path("name").mkdir(mode=0o777, exist_ok=False, parents=True) -127 | | PTH103 `os.makedirs()` should be replaced by `Path.mkdir(parents=True)` @@ -815,14 +752,12 @@ PTH101 [*] `os.chmod()` should be replaced by `Path.chmod()` | help: Replace with `Path(...).chmod(...)` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 130 | # https://github.com/astral-sh/ruff/issues/20134 - - os.chmod("pth1_link", mode=0o600, follow_symlinks= False ) 131 + pathlib.Path("pth1_link").chmod(mode=0o600, follow_symlinks= False) -132 | os.chmod("pth1_link", mode=0o600, follow_symlinks=True) | PTH101 [*] `os.chmod()` should be replaced by `Path.chmod()` @@ -837,14 +772,12 @@ PTH101 [*] `os.chmod()` should be replaced by `Path.chmod()` | help: Replace with `Path(...).chmod(...)` | -2 | import os.path -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 131 | os.chmod("pth1_link", mode=0o600, follow_symlinks= False ) - - os.chmod("pth1_link", mode=0o600, follow_symlinks=True) 132 + pathlib.Path("pth1_link").chmod(mode=0o600, follow_symlinks=True) -133 | | PTH101 `os.chmod()` should be replaced by `Path.chmod()` @@ -904,12 +837,9 @@ PTH104 [*] `os.rename()` should be replaced by `Path.rename()` | help: Replace with `Path(...).rename(...)` | -142 | import sys 143 + import pathlib -144 | - - if os.rename("pth1.py", "pth1.py.bak"): -145 + if pathlib.Path("pth1.py").rename("pth1.py.bak"): -146 | print("rename: truthy") +144 + +145 ~ if pathlib.Path("pth1.py").rename("pth1.py.bak"): | note: This is an unsafe fix and may change runtime behavior @@ -925,14 +855,12 @@ PTH105 [*] `os.replace()` should be replaced by `Path.replace()` | help: Replace with `Path(...).replace(...)` | -142 | import sys 143 + import pathlib -144 | --------------------------------------------------------------------------------- +144 + +145 | if os.rename("pth1.py", "pth1.py.bak"): + … 149 | - - if os.replace("pth1.py.bak", "pth1.py"): -150 + if pathlib.Path("pth1.py.bak").replace("pth1.py"): -151 | print("replace: truthy") +150 ~ if pathlib.Path("pth1.py.bak").replace("pth1.py"): | note: This is an unsafe fix and may change runtime behavior @@ -947,14 +875,12 @@ PTH109 [*] `os.getcwd()` should be replaced by `Path.cwd()` | help: Replace with `Path.cwd()` | -142 | import sys 143 + import pathlib -144 | --------------------------------------------------------------------------------- +144 + +145 | if os.rename("pth1.py", "pth1.py.bak"): + … 155 | try: - - for _ in os.getcwd(): -156 + for _ in pathlib.Path.cwd(): -157 | print("getcwd: iterable") +156 ~ for _ in pathlib.Path.cwd(): | note: This is an unsafe fix and may change runtime behavior @@ -969,14 +895,12 @@ PTH109 [*] `os.getcwd()` should be replaced by `Path.cwd()` | help: Replace with `Path.cwd()` | -142 | import sys 143 + import pathlib -144 | --------------------------------------------------------------------------------- +144 + +145 | if os.rename("pth1.py", "pth1.py.bak"): + … 162 | try: - - for _ in os.getcwdb(): -163 + for _ in pathlib.Path.cwd(): -164 | print("getcwdb: iterable") +163 ~ for _ in pathlib.Path.cwd(): | note: This is an unsafe fix and may change runtime behavior @@ -991,14 +915,12 @@ PTH115 [*] `os.readlink()` should be replaced by `Path.readlink()` | help: Replace with `Path(...).readlink()` | -142 | import sys 143 + import pathlib -144 | --------------------------------------------------------------------------------- +144 + +145 | if os.rename("pth1.py", "pth1.py.bak"): + … 169 | try: - - for _ in os.readlink(sys.executable): -170 + for _ in pathlib.Path(sys.executable).readlink(): -171 | print("readlink: iterable") +170 ~ for _ in pathlib.Path(sys.executable).readlink(): | note: This is an unsafe fix and may change runtime behavior @@ -1010,11 +932,10 @@ PTH101 [*] `os.chmod()` should be replaced by `Path.chmod()` | ^^^^^^^^ help: Replace with `Path(...).chmod(...)` | -142 | import sys 143 + import pathlib -144 | --------------------------------------------------------------------------------- +144 + +145 | if os.rename("pth1.py", "pth1.py.bak"): + … 187 | os.chmod(_AttrHolder.fd, 0o644) # Suppressed: resolved as `int` - - os.chmod(_AttrHolder.name, 0o644) # Diagnostic + fix: resolved as `str` -188 + pathlib.Path(_AttrHolder.name).chmod(0o644) # Diagnostic + fix: resolved as `str` +188 ~ pathlib.Path(_AttrHolder.name).chmod(0o644) # Diagnostic + fix: resolved as `str` | diff --git a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview_import_as.py.snap b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview_import_as.py.snap index 327e1a1bc0507..1962d91ccac3f 100644 --- a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview_import_as.py.snap +++ b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview_import_as.py.snap @@ -13,15 +13,12 @@ PTH100 [*] `os.path.abspath()` should be replaced by `Path.resolve()` | help: Replace with `Path(...).resolve()` | -2 | import os.path as foo_p 3 + import pathlib -4 | +4 + 5 | p = "/foo" 6 | q = "bar" 7 | - - a = foo_p.abspath(p) -8 + a = pathlib.Path(p).resolve() -9 | aa = foo.chmod(p) +8 ~ a = pathlib.Path(p).resolve() | note: This is an unsafe fix and may change runtime behavior @@ -48,14 +45,12 @@ PTH102 [*] `os.mkdir()` should be replaced by `Path.mkdir()` | help: Replace with `Path(...).mkdir()` | -2 | import os.path as foo_p -3 + import pathlib -4 | --------------------------------------------------------------------------------- -9 | aa = foo.chmod(p) - - aaa = foo.mkdir(p) -10 + aaa = pathlib.Path(p).mkdir() -11 | foo.makedirs(p) + 3 + import pathlib + 4 + + 5 | p = "/foo" + … + 9 | aa = foo.chmod(p) +10 ~ aaa = pathlib.Path(p).mkdir() | PTH103 [*] `os.makedirs()` should be replaced by `Path.mkdir(parents=True)` @@ -70,14 +65,12 @@ PTH103 [*] `os.makedirs()` should be replaced by `Path.mkdir(parents=True)` | help: Replace with `Path(...).mkdir(parents=True)` | -2 | import os.path as foo_p -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 10 | aaa = foo.mkdir(p) - - foo.makedirs(p) 11 + pathlib.Path(p).mkdir(parents=True) -12 | foo.rename(p) | PTH104 `os.rename()` should be replaced by `Path.rename()` @@ -116,14 +109,12 @@ PTH106 [*] `os.rmdir()` should be replaced by `Path.rmdir()` | help: Replace with `Path(...).rmdir()` | -2 | import os.path as foo_p -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 13 | foo.replace(p) - - foo.rmdir(p) 14 + pathlib.Path(p).rmdir() -15 | foo.remove(p) | PTH107 [*] `os.remove()` should be replaced by `Path.unlink()` @@ -138,14 +129,12 @@ PTH107 [*] `os.remove()` should be replaced by `Path.unlink()` | help: Replace with `Path(...).unlink()` | -2 | import os.path as foo_p -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 14 | foo.rmdir(p) - - foo.remove(p) 15 + pathlib.Path(p).unlink() -16 | foo.unlink(p) | PTH108 [*] `os.unlink()` should be replaced by `Path.unlink()` @@ -160,14 +149,12 @@ PTH108 [*] `os.unlink()` should be replaced by `Path.unlink()` | help: Replace with `Path(...).unlink()` | -2 | import os.path as foo_p -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 15 | foo.remove(p) - - foo.unlink(p) 16 + pathlib.Path(p).unlink() -17 | foo.getcwd(p) | PTH109 `os.getcwd()` should be replaced by `Path.cwd()` @@ -194,14 +181,12 @@ PTH110 [*] `os.path.exists()` should be replaced by `Path.exists()` | help: Replace with `Path(...).exists()` | -2 | import os.path as foo_p -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 17 | foo.getcwd(p) - - b = foo_p.exists(p) -18 + b = pathlib.Path(p).exists() -19 | bb = foo_p.expanduser(p) +18 ~ b = pathlib.Path(p).exists() | PTH111 [*] `os.path.expanduser()` should be replaced by `Path.expanduser()` @@ -216,14 +201,12 @@ PTH111 [*] `os.path.expanduser()` should be replaced by `Path.expanduser()` | help: Replace with `Path(...).expanduser()` | -2 | import os.path as foo_p -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 18 | b = foo_p.exists(p) - - bb = foo_p.expanduser(p) -19 + bb = pathlib.Path(p).expanduser() -20 | bbb = foo_p.isdir(p) +19 ~ bb = pathlib.Path(p).expanduser() | note: This is an unsafe fix and may change runtime behavior @@ -239,14 +222,12 @@ PTH112 [*] `os.path.isdir()` should be replaced by `Path.is_dir()` | help: Replace with `Path(...).is_dir()` | -2 | import os.path as foo_p -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 19 | bb = foo_p.expanduser(p) - - bbb = foo_p.isdir(p) -20 + bbb = pathlib.Path(p).is_dir() -21 | bbbb = foo_p.isfile(p) +20 ~ bbb = pathlib.Path(p).is_dir() | PTH113 [*] `os.path.isfile()` should be replaced by `Path.is_file()` @@ -261,14 +242,12 @@ PTH113 [*] `os.path.isfile()` should be replaced by `Path.is_file()` | help: Replace with `Path(...).is_file()` | -2 | import os.path as foo_p -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 20 | bbb = foo_p.isdir(p) - - bbbb = foo_p.isfile(p) -21 + bbbb = pathlib.Path(p).is_file() -22 | bbbbb = foo_p.islink(p) +21 ~ bbbb = pathlib.Path(p).is_file() | PTH114 [*] `os.path.islink()` should be replaced by `Path.is_symlink()` @@ -283,14 +262,12 @@ PTH114 [*] `os.path.islink()` should be replaced by `Path.is_symlink()` | help: Replace with `Path(...).is_symlink()` | -2 | import os.path as foo_p -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 21 | bbbb = foo_p.isfile(p) - - bbbbb = foo_p.islink(p) -22 + bbbbb = pathlib.Path(p).is_symlink() -23 | foo.readlink(p) +22 ~ bbbbb = pathlib.Path(p).is_symlink() | PTH115 [*] `os.readlink()` should be replaced by `Path.readlink()` @@ -305,14 +282,12 @@ PTH115 [*] `os.readlink()` should be replaced by `Path.readlink()` | help: Replace with `Path(...).readlink()` | -2 | import os.path as foo_p -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 22 | bbbbb = foo_p.islink(p) - - foo.readlink(p) 23 + pathlib.Path(p).readlink() -24 | foo.stat(p) | PTH116 `os.stat()` should be replaced by `Path.stat()`, `Path.owner()`, or `Path.group()` @@ -338,14 +313,12 @@ PTH117 [*] `os.path.isabs()` should be replaced by `Path.is_absolute()` | help: Replace with `Path(...).is_absolute()` | -2 | import os.path as foo_p -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 24 | foo.stat(p) - - foo_p.isabs(p) 25 + pathlib.Path(p).is_absolute() -26 | foo_p.join(p, q) | PTH118 `os.path.join()` should be replaced by `Path` with `/` operator @@ -393,14 +366,12 @@ PTH119 [*] `os.path.basename()` should be replaced by `Path.name` | help: Replace with `Path(...).name` | -2 | import os.path as foo_p -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 28 | foo.sep.join((p, q)) - - foo_p.basename(p) 29 + pathlib.Path(p).name -30 | foo_p.dirname(p) | note: This is an unsafe fix and may change runtime behavior @@ -416,14 +387,12 @@ PTH120 [*] `os.path.dirname()` should be replaced by `Path.parent` | help: Replace with `Path(...).parent` | -2 | import os.path as foo_p -3 + import pathlib -4 | --------------------------------------------------------------------------------- + 3 + import pathlib + 4 + + 5 | p = "/foo" + … 29 | foo_p.basename(p) - - foo_p.dirname(p) 30 + pathlib.Path(p).parent -31 | foo_p.samefile(p) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview_import_from.py.snap b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview_import_from.py.snap index 0f889292ca723..4b0356e9ce3e2 100644 --- a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview_import_from.py.snap +++ b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview_import_from.py.snap @@ -13,15 +13,12 @@ PTH100 [*] `os.path.abspath()` should be replaced by `Path.resolve()` | help: Replace with `Path(...).resolve()` | -4 | from os.path import isabs, join, basename, dirname, samefile, splitext -5 + import pathlib -6 | -7 | p = "/foo" -8 | q = "bar" -9 | - - a = abspath(p) -10 + a = pathlib.Path(p).resolve() -11 | aa = chmod(p) + 5 + import pathlib + 6 + + 7 | p = "/foo" + 8 | q = "bar" + 9 | +10 ~ a = pathlib.Path(p).resolve() | note: This is an unsafe fix and may change runtime behavior @@ -48,14 +45,12 @@ PTH102 [*] `os.mkdir()` should be replaced by `Path.mkdir()` | help: Replace with `Path(...).mkdir()` | -4 | from os.path import isabs, join, basename, dirname, samefile, splitext -5 + import pathlib -6 | --------------------------------------------------------------------------------- + 5 + import pathlib + 6 + + 7 | p = "/foo" + … 11 | aa = chmod(p) - - aaa = mkdir(p) -12 + aaa = pathlib.Path(p).mkdir() -13 | makedirs(p) +12 ~ aaa = pathlib.Path(p).mkdir() | PTH103 [*] `os.makedirs()` should be replaced by `Path.mkdir(parents=True)` @@ -70,14 +65,12 @@ PTH103 [*] `os.makedirs()` should be replaced by `Path.mkdir(parents=True)` | help: Replace with `Path(...).mkdir(parents=True)` | -4 | from os.path import isabs, join, basename, dirname, samefile, splitext -5 + import pathlib -6 | --------------------------------------------------------------------------------- + 5 + import pathlib + 6 + + 7 | p = "/foo" + … 12 | aaa = mkdir(p) - - makedirs(p) 13 + pathlib.Path(p).mkdir(parents=True) -14 | rename(p) | PTH104 `os.rename()` should be replaced by `Path.rename()` @@ -116,14 +109,12 @@ PTH106 [*] `os.rmdir()` should be replaced by `Path.rmdir()` | help: Replace with `Path(...).rmdir()` | -4 | from os.path import isabs, join, basename, dirname, samefile, splitext -5 + import pathlib -6 | --------------------------------------------------------------------------------- + 5 + import pathlib + 6 + + 7 | p = "/foo" + … 15 | replace(p) - - rmdir(p) 16 + pathlib.Path(p).rmdir() -17 | remove(p) | PTH107 [*] `os.remove()` should be replaced by `Path.unlink()` @@ -138,14 +129,12 @@ PTH107 [*] `os.remove()` should be replaced by `Path.unlink()` | help: Replace with `Path(...).unlink()` | -4 | from os.path import isabs, join, basename, dirname, samefile, splitext -5 + import pathlib -6 | --------------------------------------------------------------------------------- + 5 + import pathlib + 6 + + 7 | p = "/foo" + … 16 | rmdir(p) - - remove(p) 17 + pathlib.Path(p).unlink() -18 | unlink(p) | PTH108 [*] `os.unlink()` should be replaced by `Path.unlink()` @@ -160,14 +149,12 @@ PTH108 [*] `os.unlink()` should be replaced by `Path.unlink()` | help: Replace with `Path(...).unlink()` | -4 | from os.path import isabs, join, basename, dirname, samefile, splitext -5 + import pathlib -6 | --------------------------------------------------------------------------------- + 5 + import pathlib + 6 + + 7 | p = "/foo" + … 17 | remove(p) - - unlink(p) 18 + pathlib.Path(p).unlink() -19 | getcwd(p) | PTH109 `os.getcwd()` should be replaced by `Path.cwd()` @@ -194,14 +181,12 @@ PTH110 [*] `os.path.exists()` should be replaced by `Path.exists()` | help: Replace with `Path(...).exists()` | -4 | from os.path import isabs, join, basename, dirname, samefile, splitext -5 + import pathlib -6 | --------------------------------------------------------------------------------- + 5 + import pathlib + 6 + + 7 | p = "/foo" + … 19 | getcwd(p) - - b = exists(p) -20 + b = pathlib.Path(p).exists() -21 | bb = expanduser(p) +20 ~ b = pathlib.Path(p).exists() | PTH111 [*] `os.path.expanduser()` should be replaced by `Path.expanduser()` @@ -216,14 +201,12 @@ PTH111 [*] `os.path.expanduser()` should be replaced by `Path.expanduser()` | help: Replace with `Path(...).expanduser()` | -4 | from os.path import isabs, join, basename, dirname, samefile, splitext -5 + import pathlib -6 | --------------------------------------------------------------------------------- + 5 + import pathlib + 6 + + 7 | p = "/foo" + … 20 | b = exists(p) - - bb = expanduser(p) -21 + bb = pathlib.Path(p).expanduser() -22 | bbb = isdir(p) +21 ~ bb = pathlib.Path(p).expanduser() | note: This is an unsafe fix and may change runtime behavior @@ -239,14 +222,12 @@ PTH112 [*] `os.path.isdir()` should be replaced by `Path.is_dir()` | help: Replace with `Path(...).is_dir()` | -4 | from os.path import isabs, join, basename, dirname, samefile, splitext -5 + import pathlib -6 | --------------------------------------------------------------------------------- + 5 + import pathlib + 6 + + 7 | p = "/foo" + … 21 | bb = expanduser(p) - - bbb = isdir(p) -22 + bbb = pathlib.Path(p).is_dir() -23 | bbbb = isfile(p) +22 ~ bbb = pathlib.Path(p).is_dir() | PTH113 [*] `os.path.isfile()` should be replaced by `Path.is_file()` @@ -261,14 +242,12 @@ PTH113 [*] `os.path.isfile()` should be replaced by `Path.is_file()` | help: Replace with `Path(...).is_file()` | -4 | from os.path import isabs, join, basename, dirname, samefile, splitext -5 + import pathlib -6 | --------------------------------------------------------------------------------- + 5 + import pathlib + 6 + + 7 | p = "/foo" + … 22 | bbb = isdir(p) - - bbbb = isfile(p) -23 + bbbb = pathlib.Path(p).is_file() -24 | bbbbb = islink(p) +23 ~ bbbb = pathlib.Path(p).is_file() | PTH114 [*] `os.path.islink()` should be replaced by `Path.is_symlink()` @@ -283,14 +262,12 @@ PTH114 [*] `os.path.islink()` should be replaced by `Path.is_symlink()` | help: Replace with `Path(...).is_symlink()` | -4 | from os.path import isabs, join, basename, dirname, samefile, splitext -5 + import pathlib -6 | --------------------------------------------------------------------------------- + 5 + import pathlib + 6 + + 7 | p = "/foo" + … 23 | bbbb = isfile(p) - - bbbbb = islink(p) -24 + bbbbb = pathlib.Path(p).is_symlink() -25 | readlink(p) +24 ~ bbbbb = pathlib.Path(p).is_symlink() | PTH115 [*] `os.readlink()` should be replaced by `Path.readlink()` @@ -305,14 +282,12 @@ PTH115 [*] `os.readlink()` should be replaced by `Path.readlink()` | help: Replace with `Path(...).readlink()` | -4 | from os.path import isabs, join, basename, dirname, samefile, splitext -5 + import pathlib -6 | --------------------------------------------------------------------------------- + 5 + import pathlib + 6 + + 7 | p = "/foo" + … 24 | bbbbb = islink(p) - - readlink(p) 25 + pathlib.Path(p).readlink() -26 | stat(p) | PTH116 `os.stat()` should be replaced by `Path.stat()`, `Path.owner()`, or `Path.group()` @@ -338,14 +313,12 @@ PTH117 [*] `os.path.isabs()` should be replaced by `Path.is_absolute()` | help: Replace with `Path(...).is_absolute()` | -4 | from os.path import isabs, join, basename, dirname, samefile, splitext -5 + import pathlib -6 | --------------------------------------------------------------------------------- + 5 + import pathlib + 6 + + 7 | p = "/foo" + … 26 | stat(p) - - isabs(p) 27 + pathlib.Path(p).is_absolute() -28 | join(p, q) | PTH118 `os.path.join()` should be replaced by `Path` with `/` operator @@ -393,14 +366,12 @@ PTH119 [*] `os.path.basename()` should be replaced by `Path.name` | help: Replace with `Path(...).name` | -4 | from os.path import isabs, join, basename, dirname, samefile, splitext -5 + import pathlib -6 | --------------------------------------------------------------------------------- + 5 + import pathlib + 6 + + 7 | p = "/foo" + … 30 | sep.join([p, q]) - - basename(p) 31 + pathlib.Path(p).name -32 | dirname(p) | note: This is an unsafe fix and may change runtime behavior @@ -416,14 +387,12 @@ PTH120 [*] `os.path.dirname()` should be replaced by `Path.parent` | help: Replace with `Path(...).parent` | -4 | from os.path import isabs, join, basename, dirname, samefile, splitext -5 + import pathlib -6 | --------------------------------------------------------------------------------- + 5 + import pathlib + 6 + + 7 | p = "/foo" + … 31 | basename(p) - - dirname(p) 32 + pathlib.Path(p).parent -33 | samefile(p) | note: This is an unsafe fix and may change runtime behavior @@ -462,14 +431,12 @@ PTH123 [*] `open()` should be replaced by `Path.open()` | help: Replace with `Path.open()` | -4 | from os.path import isabs, join, basename, dirname, samefile, splitext -5 + import pathlib -6 | --------------------------------------------------------------------------------- + 5 + import pathlib + 6 + + 7 | p = "/foo" + … 34 | splitext(p) - - with open(p) as fp: -35 + with pathlib.Path(p).open() as fp: -36 | fp.read() +35 ~ with pathlib.Path(p).open() as fp: | PTH123 [*] `open()` should be replaced by `Path.open()` @@ -481,14 +448,12 @@ PTH123 [*] `open()` should be replaced by `Path.open()` | ^^^^ help: Replace with `Path.open()` | -4 | from os.path import isabs, join, basename, dirname, samefile, splitext -5 + import pathlib -6 | --------------------------------------------------------------------------------- + 5 + import pathlib + 6 + + 7 | p = "/foo" + … 36 | fp.read() - - open(p).close() -37 + pathlib.Path(p).open().close() -38 | +37 ~ pathlib.Path(p).open().close() | PTH123 [*] `open()` should be replaced by `Path.open()` @@ -500,14 +465,12 @@ PTH123 [*] `open()` should be replaced by `Path.open()` | ^^^^ help: Replace with `Path.open()` | -4 | from os.path import isabs, join, basename, dirname, samefile, splitext -5 + import pathlib -6 | --------------------------------------------------------------------------------- + 5 + import pathlib + 6 + + 7 | p = "/foo" + … 43 | - - with open(p) as _: ... # Error -44 + with pathlib.Path(p).open() as _: ... # Error -45 | +44 ~ with pathlib.Path(p).open() as _: ... # Error | PTH104 [*] `os.rename()` should be replaced by `Path.rename()` @@ -522,14 +485,12 @@ PTH104 [*] `os.rename()` should be replaced by `Path.rename()` | help: Replace with `Path(...).rename(...)` | -4 | from os.path import isabs, join, basename, dirname, samefile, splitext -5 + import pathlib -6 | --------------------------------------------------------------------------------- + 5 + import pathlib + 6 + + 7 | p = "/foo" + … 53 | - - rename(file, "file_2.py") 54 + pathlib.Path(file).rename("file_2.py") -55 | | PTH104 [*] `os.rename()` should be replaced by `Path.rename()` @@ -544,20 +505,12 @@ PTH104 [*] `os.rename()` should be replaced by `Path.rename()` | help: Replace with `Path(...).rename(...)` | -4 | from os.path import isabs, join, basename, dirname, samefile, splitext -5 + import pathlib -6 | --------------------------------------------------------------------------------- + 5 + import pathlib + 6 + + 7 | p = "/foo" + … 55 | - - rename( - - # comment 1 - - file, # comment 2 - - "file_2.py" - - , - - # comment 3 - - ) 56 + pathlib.Path(file).rename("file_2.py") -57 | | note: This is an unsafe fix and may change runtime behavior @@ -573,12 +526,10 @@ PTH104 [*] `os.rename()` should be replaced by `Path.rename()` | help: Replace with `Path(...).rename(...)` | -4 | from os.path import isabs, join, basename, dirname, samefile, splitext -5 + import pathlib -6 | --------------------------------------------------------------------------------- + 5 + import pathlib + 6 + + 7 | p = "/foo" + … 63 | - - rename(file, "file_2.py", src_dir_fd=None, dst_dir_fd=None) 64 + pathlib.Path(file).rename("file_2.py") -65 | | diff --git a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview_import_from_as.py.snap b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview_import_from_as.py.snap index 2e5f5bcf1ad18..a345bed3964bf 100644 --- a/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview_import_from_as.py.snap +++ b/crates/ruff_linter/src/rules/flake8_use_pathlib/snapshots/ruff_linter__rules__flake8_use_pathlib__tests__preview_import_from_as.py.snap @@ -13,15 +13,12 @@ PTH100 [*] `os.path.abspath()` should be replaced by `Path.resolve()` | help: Replace with `Path(...).resolve()` | -9 | from os.path import samefile as xsamefile, splitext as xsplitext 10 + import pathlib -11 | +11 + 12 | p = "/foo" 13 | q = "bar" 14 | - - a = xabspath(p) -15 + a = pathlib.Path(p).resolve() -16 | aa = xchmod(p) +15 ~ a = pathlib.Path(p).resolve() | note: This is an unsafe fix and may change runtime behavior @@ -48,14 +45,12 @@ PTH102 [*] `os.mkdir()` should be replaced by `Path.mkdir()` | help: Replace with `Path(...).mkdir()` | -9 | from os.path import samefile as xsamefile, splitext as xsplitext 10 + import pathlib -11 | --------------------------------------------------------------------------------- +11 + +12 | p = "/foo" + … 16 | aa = xchmod(p) - - aaa = xmkdir(p) -17 + aaa = pathlib.Path(p).mkdir() -18 | xmakedirs(p) +17 ~ aaa = pathlib.Path(p).mkdir() | PTH103 [*] `os.makedirs()` should be replaced by `Path.mkdir(parents=True)` @@ -70,14 +65,12 @@ PTH103 [*] `os.makedirs()` should be replaced by `Path.mkdir(parents=True)` | help: Replace with `Path(...).mkdir(parents=True)` | -9 | from os.path import samefile as xsamefile, splitext as xsplitext 10 + import pathlib -11 | --------------------------------------------------------------------------------- +11 + +12 | p = "/foo" + … 17 | aaa = xmkdir(p) - - xmakedirs(p) 18 + pathlib.Path(p).mkdir(parents=True) -19 | xrename(p) | PTH104 `os.rename()` should be replaced by `Path.rename()` @@ -116,14 +109,12 @@ PTH106 [*] `os.rmdir()` should be replaced by `Path.rmdir()` | help: Replace with `Path(...).rmdir()` | -9 | from os.path import samefile as xsamefile, splitext as xsplitext 10 + import pathlib -11 | --------------------------------------------------------------------------------- +11 + +12 | p = "/foo" + … 20 | xreplace(p) - - xrmdir(p) 21 + pathlib.Path(p).rmdir() -22 | xremove(p) | PTH107 [*] `os.remove()` should be replaced by `Path.unlink()` @@ -138,14 +129,12 @@ PTH107 [*] `os.remove()` should be replaced by `Path.unlink()` | help: Replace with `Path(...).unlink()` | -9 | from os.path import samefile as xsamefile, splitext as xsplitext 10 + import pathlib -11 | --------------------------------------------------------------------------------- +11 + +12 | p = "/foo" + … 21 | xrmdir(p) - - xremove(p) 22 + pathlib.Path(p).unlink() -23 | xunlink(p) | PTH108 [*] `os.unlink()` should be replaced by `Path.unlink()` @@ -160,14 +149,12 @@ PTH108 [*] `os.unlink()` should be replaced by `Path.unlink()` | help: Replace with `Path(...).unlink()` | -9 | from os.path import samefile as xsamefile, splitext as xsplitext 10 + import pathlib -11 | --------------------------------------------------------------------------------- +11 + +12 | p = "/foo" + … 22 | xremove(p) - - xunlink(p) 23 + pathlib.Path(p).unlink() -24 | xgetcwd(p) | PTH109 `os.getcwd()` should be replaced by `Path.cwd()` @@ -194,14 +181,12 @@ PTH110 [*] `os.path.exists()` should be replaced by `Path.exists()` | help: Replace with `Path(...).exists()` | -9 | from os.path import samefile as xsamefile, splitext as xsplitext 10 + import pathlib -11 | --------------------------------------------------------------------------------- +11 + +12 | p = "/foo" + … 24 | xgetcwd(p) - - b = xexists(p) -25 + b = pathlib.Path(p).exists() -26 | bb = xexpanduser(p) +25 ~ b = pathlib.Path(p).exists() | PTH111 [*] `os.path.expanduser()` should be replaced by `Path.expanduser()` @@ -216,14 +201,12 @@ PTH111 [*] `os.path.expanduser()` should be replaced by `Path.expanduser()` | help: Replace with `Path(...).expanduser()` | -9 | from os.path import samefile as xsamefile, splitext as xsplitext 10 + import pathlib -11 | --------------------------------------------------------------------------------- +11 + +12 | p = "/foo" + … 25 | b = xexists(p) - - bb = xexpanduser(p) -26 + bb = pathlib.Path(p).expanduser() -27 | bbb = xisdir(p) +26 ~ bb = pathlib.Path(p).expanduser() | note: This is an unsafe fix and may change runtime behavior @@ -239,14 +222,12 @@ PTH112 [*] `os.path.isdir()` should be replaced by `Path.is_dir()` | help: Replace with `Path(...).is_dir()` | -9 | from os.path import samefile as xsamefile, splitext as xsplitext 10 + import pathlib -11 | --------------------------------------------------------------------------------- +11 + +12 | p = "/foo" + … 26 | bb = xexpanduser(p) - - bbb = xisdir(p) -27 + bbb = pathlib.Path(p).is_dir() -28 | bbbb = xisfile(p) +27 ~ bbb = pathlib.Path(p).is_dir() | PTH113 [*] `os.path.isfile()` should be replaced by `Path.is_file()` @@ -261,14 +242,12 @@ PTH113 [*] `os.path.isfile()` should be replaced by `Path.is_file()` | help: Replace with `Path(...).is_file()` | -9 | from os.path import samefile as xsamefile, splitext as xsplitext 10 + import pathlib -11 | --------------------------------------------------------------------------------- +11 + +12 | p = "/foo" + … 27 | bbb = xisdir(p) - - bbbb = xisfile(p) -28 + bbbb = pathlib.Path(p).is_file() -29 | bbbbb = xislink(p) +28 ~ bbbb = pathlib.Path(p).is_file() | PTH114 [*] `os.path.islink()` should be replaced by `Path.is_symlink()` @@ -283,14 +262,12 @@ PTH114 [*] `os.path.islink()` should be replaced by `Path.is_symlink()` | help: Replace with `Path(...).is_symlink()` | -9 | from os.path import samefile as xsamefile, splitext as xsplitext 10 + import pathlib -11 | --------------------------------------------------------------------------------- +11 + +12 | p = "/foo" + … 28 | bbbb = xisfile(p) - - bbbbb = xislink(p) -29 + bbbbb = pathlib.Path(p).is_symlink() -30 | xreadlink(p) +29 ~ bbbbb = pathlib.Path(p).is_symlink() | PTH115 [*] `os.readlink()` should be replaced by `Path.readlink()` @@ -305,14 +282,12 @@ PTH115 [*] `os.readlink()` should be replaced by `Path.readlink()` | help: Replace with `Path(...).readlink()` | -9 | from os.path import samefile as xsamefile, splitext as xsplitext 10 + import pathlib -11 | --------------------------------------------------------------------------------- +11 + +12 | p = "/foo" + … 29 | bbbbb = xislink(p) - - xreadlink(p) 30 + pathlib.Path(p).readlink() -31 | xstat(p) | PTH116 `os.stat()` should be replaced by `Path.stat()`, `Path.owner()`, or `Path.group()` @@ -338,14 +313,12 @@ PTH117 [*] `os.path.isabs()` should be replaced by `Path.is_absolute()` | help: Replace with `Path(...).is_absolute()` | -9 | from os.path import samefile as xsamefile, splitext as xsplitext 10 + import pathlib -11 | --------------------------------------------------------------------------------- +11 + +12 | p = "/foo" + … 31 | xstat(p) - - xisabs(p) 32 + pathlib.Path(p).is_absolute() -33 | xjoin(p, q) | PTH118 `os.path.join()` should be replaced by `Path` with `/` operator @@ -393,14 +366,12 @@ PTH119 [*] `os.path.basename()` should be replaced by `Path.name` | help: Replace with `Path(...).name` | -9 | from os.path import samefile as xsamefile, splitext as xsplitext 10 + import pathlib -11 | --------------------------------------------------------------------------------- +11 + +12 | p = "/foo" + … 35 | s.join([p, q]) - - xbasename(p) 36 + pathlib.Path(p).name -37 | xdirname(p) | note: This is an unsafe fix and may change runtime behavior @@ -416,14 +387,12 @@ PTH120 [*] `os.path.dirname()` should be replaced by `Path.parent` | help: Replace with `Path(...).parent` | -9 | from os.path import samefile as xsamefile, splitext as xsplitext 10 + import pathlib -11 | --------------------------------------------------------------------------------- +11 + +12 | p = "/foo" + … 36 | xbasename(p) - - xdirname(p) 37 + pathlib.Path(p).parent -38 | xsamefile(p) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/flynt/snapshots/ruff_linter__rules__flynt__tests__FLY002_FLY002.py.snap b/crates/ruff_linter/src/rules/flynt/snapshots/ruff_linter__rules__flynt__tests__FLY002_FLY002.py.snap index 0a8f48e8e8939..adfb3a38febba 100644 --- a/crates/ruff_linter/src/rules/flynt/snapshots/ruff_linter__rules__flynt__tests__FLY002_FLY002.py.snap +++ b/crates/ruff_linter/src/rules/flynt/snapshots/ruff_linter__rules__flynt__tests__FLY002_FLY002.py.snap @@ -12,10 +12,8 @@ FLY002 [*] Consider `f"{a} World"` instead of string join | help: Replace with `f"{a} World"` | -4 | a = "Hello" - - ok1 = " ".join([a, " World"]) # OK +5 - ok1 = " ".join([a, " World"]) # OK 5 + ok1 = f"{a} World" # OK -6 | ok2 = "".join(["Finally, ", a, " World"]) # OK | note: This is an unsafe fix and may change runtime behavior @@ -31,10 +29,8 @@ FLY002 [*] Consider `f"Finally, {a} World"` instead of string join | help: Replace with `f"Finally, {a} World"` | -5 | ok1 = " ".join([a, " World"]) # OK - - ok2 = "".join(["Finally, ", a, " World"]) # OK +6 - ok2 = "".join(["Finally, ", a, " World"]) # OK 6 + ok2 = f"Finally, {a} World" # OK -7 | ok3 = "x".join(("1", "2", "3")) # OK | note: This is an unsafe fix and may change runtime behavior @@ -50,10 +46,8 @@ FLY002 [*] Consider `"1x2x3"` instead of string join | help: Replace with `"1x2x3"` | -6 | ok2 = "".join(["Finally, ", a, " World"]) # OK - - ok3 = "x".join(("1", "2", "3")) # OK +7 - ok3 = "x".join(("1", "2", "3")) # OK 7 + ok3 = "1x2x3" # OK -8 | ok4 = "y".join([1, 2, 3]) # Technically OK, though would've been an error originally | note: This is an unsafe fix and may change runtime behavior @@ -69,10 +63,8 @@ FLY002 [*] Consider `f"{1}y{2}y{3}"` instead of string join | help: Replace with `f"{1}y{2}y{3}"` | -7 | ok3 = "x".join(("1", "2", "3")) # OK - - ok4 = "y".join([1, 2, 3]) # Technically OK, though would've been an error originally +8 - ok4 = "y".join([1, 2, 3]) # Technically OK, though would've been an error originally 8 + ok4 = f"{1}y{2}y{3}" # Technically OK, though would've been an error originally -9 | ok5 = "a".join([random(), random()]) # OK (simple calls) | note: This is an unsafe fix and may change runtime behavior @@ -86,12 +78,10 @@ FLY002 [*] Consider `f"{random()}a{random()}"` instead of string join 10 | ok6 = "a".join([secrets.token_urlsafe(), secrets.token_hex()]) # OK (attr calls) | help: Replace with `f"{random()}a{random()}"` - | -8 | ok4 = "y".join([1, 2, 3]) # Technically OK, though would've been an error originally - - ok5 = "a".join([random(), random()]) # OK (simple calls) -9 + ok5 = f"{random()}a{random()}" # OK (simple calls) -10 | ok6 = "a".join([secrets.token_urlsafe(), secrets.token_hex()]) # OK (attr calls) - | + | +9 - ok5 = "a".join([random(), random()]) # OK (simple calls) +9 + ok5 = f"{random()}a{random()}" # OK (simple calls) + | note: This is an unsafe fix and may change runtime behavior FLY002 [*] Consider `f"{secrets.token_urlsafe()}a{secrets.token_hex()}"` instead of string join @@ -106,10 +96,8 @@ FLY002 [*] Consider `f"{secrets.token_urlsafe()}a{secrets.token_hex()}"` instead | help: Replace with `f"{secrets.token_urlsafe()}a{secrets.token_hex()}"` | -9 | ok5 = "a".join([random(), random()]) # OK (simple calls) - - ok6 = "a".join([secrets.token_urlsafe(), secrets.token_hex()]) # OK (attr calls) +10 - ok6 = "a".join([secrets.token_urlsafe(), secrets.token_hex()]) # OK (attr calls) 10 + ok6 = f"{secrets.token_urlsafe()}a{secrets.token_hex()}" # OK (attr calls) -11 | | note: This is an unsafe fix and may change runtime behavior @@ -124,11 +112,8 @@ FLY002 [*] Consider f-string instead of string join | help: Replace with f-string | -19 | # https://github.com/astral-sh/ruff/issues/19887 - - nok8 = '\n'.join([r'line1','line2']) -20 + nok8 = r'''line1 +20 ~ nok8 = r'''line1 21 + line2''' -22 | nok9 = '\n'.join([r"raw string", '<""">', "<'''>"]) # Not OK (both triple-quote delimiters appear; should bail) | note: This is an unsafe fix and may change runtime behavior @@ -144,10 +129,8 @@ FLY002 [*] Consider `f"{url}{filename}"` instead of string join | help: Replace with `f"{url}{filename}"` | -24 | def create_file_public_url(url, filename): - - return''.join([url, filename]) +25 - return''.join([url, filename]) 25 + return f"{url}{filename}" -26 | | note: This is an unsafe fix and may change runtime behavior @@ -162,10 +145,8 @@ FLY002 [*] Consider `f'{foo}"'` instead of string join | help: Replace with `f'{foo}"'` | -27 | # Regression test for: https://github.com/astral-sh/ruff/issues/19837 - - nok10 = "".join((foo, '"')) +28 - nok10 = "".join((foo, '"')) 28 + nok10 = f'{foo}"' -29 | nok11 = ''.join((foo, "'")) | note: This is an unsafe fix and may change runtime behavior @@ -181,9 +162,7 @@ FLY002 [*] Consider `f"{foo}'"` instead of string join | help: Replace with `f"{foo}'"` | -28 | nok10 = "".join((foo, '"')) - - nok11 = ''.join((foo, "'")) +29 - nok11 = ''.join((foo, "'")) 29 + nok11 = f"{foo}'" -30 | nok12 = ''.join([foo, "'", '"']) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__1_separate_subpackage_first_and_third_party_imports.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__1_separate_subpackage_first_and_third_party_imports.py.snap index 4af5fa8f98df5..923b5b59d7277 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__1_separate_subpackage_first_and_third_party_imports.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__1_separate_subpackage_first_and_third_party_imports.py.snap @@ -15,18 +15,14 @@ I001 [*] Import block is un-sorted or un-formatted | |__________________^ help: Organize imports | -1 | import sys -2 + -3 + import foo -4 + from foo import bar, baz -5 + -6 | import baz - - from foo import bar, baz -7 + import foo.bar -8 + import foo.bar.baz -9 | from foo.bar import blah, blub -10 | from foo.bar.baz import something - - import foo - - import foo.bar - - import foo.bar.baz + 1 + import sys + 2 + + 3 + import foo + 4 + from foo import bar, baz + 5 + + 6 + import baz + 7 + import foo.bar + 8 + import foo.bar.baz + 9 + from foo.bar import blah, blub +10 + from foo.bar.baz import something | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__2_separate_subpackage_first_and_third_party_imports.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__2_separate_subpackage_first_and_third_party_imports.py.snap index 887980a2bd643..37e16af5ba25f 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__2_separate_subpackage_first_and_third_party_imports.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__2_separate_subpackage_first_and_third_party_imports.py.snap @@ -15,17 +15,14 @@ I001 [*] Import block is un-sorted or un-formatted | |__________________^ help: Organize imports | -1 | import sys -2 + -3 | import baz - - from foo import bar, baz -4 + import foo.bar -5 + import foo.bar.baz -6 | from foo.bar import blah, blub -7 | from foo.bar.baz import something -8 + -9 | import foo - - import foo.bar - - import foo.bar.baz + 1 + import sys + 2 + + 3 + import baz + 4 + import foo.bar + 5 + import foo.bar.baz + 6 + from foo.bar import blah, blub + 7 + from foo.bar.baz import something + 8 + + 9 + import foo 10 + from foo import bar, baz | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__add_newline_before_comments.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__add_newline_before_comments.py.snap index 555d6ccc20e8a..815249ea85a45 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__add_newline_before_comments.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__add_newline_before_comments.py.snap @@ -13,13 +13,15 @@ I001 [*] Import block is un-sorted or un-formatted 7 | | import leading_prefix | |_____________________^ help: Organize imports - | -1 | import os -2 + -3 | # This is a comment in the same section, so we need to add one newline. -4 | import sys -5 + -6 | import numpy as np -7 + -8 | # This is a comment, but it starts a new section, so we don't need to add a newline - | + | + 1 + import os + 2 + + 3 + # This is a comment in the same section, so we need to add one newline. + 4 + import sys + 5 + + 6 + import numpy as np + 7 + + 8 + # This is a comment, but it starts a new section, so we don't need to add a newline + 9 + # before it. +10 + import leading_prefix + | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__as_imports_comments.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__as_imports_comments.py.snap index 1db22a4a0e1d5..aba70a15756df 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__as_imports_comments.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__as_imports_comments.py.snap @@ -22,23 +22,12 @@ I001 [*] Import block is un-sorted or un-formatted | |_^ help: Organize imports | - - from foo import ( # Comment on `foo` - - Member as Alias, # Comment on `Alias` - - ) - - -1 | from bar import ( # Comment on `bar` -2 | Member, # Comment on `Member` - - ) - - - - from baz import ( # Comment on `baz` - - Member as Alias # Comment on `Alias` -3 | ) - - - - from bop import ( # Comment on `bop` - - Member # Comment on `Member` +1 + from bar import ( # Comment on `bar` +2 + Member, # Comment on `Member` +3 + ) 4 + from baz import Member as Alias # Comment on `baz` # Comment on `Alias` 5 + from bop import Member # Comment on `bop` # Comment on `Member` 6 + from foo import ( # Comment on `foo` 7 + Member as Alias, # Comment on `Alias` -8 | ) +8 + ) | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__bom_unsorted.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__bom_unsorted.py.snap index 181eb565f8807..0f0ec736c6ddc 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__bom_unsorted.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__bom_unsorted.py.snap @@ -9,8 +9,6 @@ I001 [*] Import block is un-sorted or un-formatted | |__________^ help: Organize imports | - - import foo - - import bar -1 + import bar +1 ~ import bar 2 + import foo | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__case_sensitive_case_sensitive.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__case_sensitive_case_sensitive.py.snap index d84c4838e77a2..92c8dd27874db 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__case_sensitive_case_sensitive.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__case_sensitive_case_sensitive.py.snap @@ -16,16 +16,13 @@ I001 [*] Import block is un-sorted or un-formatted | |_____________________^ help: Organize imports | -2 | import B +1 + import A +2 + import B 3 + import C 4 + import E -5 | import b - - import C -6 | import d - - import E -7 | import f - - from g import a, B, c - - from h import A, b, C +5 + import b +6 + import d +7 + import f 8 + from g import B, a, c 9 + from h import A, C, b | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__closest_to_furthest_relative_imports_order.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__closest_to_furthest_relative_imports_order.py.snap index a77cb654ef124..4f5a892f3d92a 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__closest_to_furthest_relative_imports_order.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__closest_to_furthest_relative_imports_order.py.snap @@ -12,7 +12,5 @@ help: Organize imports | 1 + from . import c 2 + from .. import b -3 | from ... import a - - from .. import b - - from . import c +3 + from ... import a | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__combine_as_imports.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__combine_as_imports.py.snap index e43c9f990be35..64bb9556a0ef7 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__combine_as_imports.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__combine_as_imports.py.snap @@ -12,8 +12,6 @@ I001 [*] Import block is un-sorted or un-formatted help: Organize imports | 1 + from module import CONSTANT, function -2 | from module import Class as C - - from module import CONSTANT - - from module import function -3 | from module import function as f +2 + from module import Class as C +3 + from module import function as f | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__combine_as_imports_combine_as_imports.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__combine_as_imports_combine_as_imports.py.snap index 9fcbbe57f2b1b..46aee25fa3a71 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__combine_as_imports_combine_as_imports.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__combine_as_imports_combine_as_imports.py.snap @@ -11,9 +11,9 @@ I001 [*] Import block is un-sorted or un-formatted | |________________________________^ help: Organize imports | - - from module import Class as C - - from module import CONSTANT - - from module import function - - from module import function as f +1 - from module import Class as C +2 - from module import CONSTANT +3 - from module import function +4 - from module import function as f 1 + from module import CONSTANT, Class as C, function, function as f | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__combine_import_from.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__combine_import_from.py.snap index 6350201903671..00b85f1077804 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__combine_import_from.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__combine_import_from.py.snap @@ -12,11 +12,6 @@ I001 [*] Import block is un-sorted or un-formatted | |_______________________________________________________^ help: Organize imports | - - from collections import Awaitable - - from collections import AsyncIterable - - from collections import Collection - - from collections import ChainMap - - from collections import MutableSequence, MutableMapping 1 + from collections import ( 2 + AsyncIterable, 3 + Awaitable, diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__comments.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__comments.py.snap index 0927db196b163..aac06790d2f07 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__comments.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__comments.py.snap @@ -40,46 +40,25 @@ I001 [*] Import block is un-sorted or un-formatted | |_______________^ help: Organize imports | -2 | # Comment 2 - - import D -3 + import B # Comment 4 -4 | -5 | # Comment 3a - - import C - - -6 | # Comment 3b -7 | import C -8 + import D -9 | - - import B # Comment 4 - - -10 | # Comment 5 - - -11 | # Comment 6 -12 | from A import ( - - a, # Comment 7 - - b, - - c, # Comment 8 + 3 + import B # Comment 4 + 4 + + 5 + # Comment 3a + 6 + # Comment 3b + 7 + import C + 8 + import D + 9 + +10 + # Comment 5 +11 + # Comment 6 +12 + from A import ( 13 + a, # Comment 7 # Comment 9 14 + b, # Comment 10 15 + c, # Comment 8 # Comment 11 -16 | ) - - from A import ( - - a, # Comment 9 - - b, # Comment 10 - - c, # Comment 11 +16 + ) 17 + from D import ( 18 + a_long_name_to_force_multiple_lines, # Comment 12 19 + another_long_name_to_force_multiple_lines, # Comment 13 -20 | ) - - - - from D import a_long_name_to_force_multiple_lines # Comment 12 - - from D import another_long_name_to_force_multiple_lines # Comment 13 - - -21 | from E import a # Comment 1 - - - - from F import a # Comment 1 - - from F import b +20 + ) +21 + from E import a # Comment 1 22 + from F import ( 23 + a, # Comment 1 24 + b, diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__deduplicate_imports.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__deduplicate_imports.py.snap index f90f628d5cc5d..80ef76df7cecd 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__deduplicate_imports.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__deduplicate_imports.py.snap @@ -11,7 +11,7 @@ I001 [*] Import block is un-sorted or un-formatted | |________________^ help: Organize imports | -1 | import os - - import os -2 | import os as os1 +1 + import os +2 + import os as os1 +3 + import os as os2 | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__detect_same_package.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__detect_same_package.snap index 2baad8d7ca9a8..1ec76270b042c 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__detect_same_package.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__detect_same_package.snap @@ -10,9 +10,9 @@ I001 [*] Import block is un-sorted or un-formatted | |______________^ help: Organize imports | -1 | import os -2 + -3 | import pandas -4 + -5 | import foo.baz +1 + import os +2 + +3 + import pandas +4 + +5 + import foo.baz | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__fit_line_length.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__fit_line_length.py.snap index 6135ea2c0372f..576c6e47470ce 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__fit_line_length.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__fit_line_length.py.snap @@ -16,13 +16,9 @@ I001 [*] Import block is un-sorted or un-formatted | |_____^ help: Organize imports | -7 | from line_with_88 import aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - - from line_with_89 import aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - - from line_with_90 import aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - - from line_with_91 import aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - - from line_with_92 import aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -8 + from line_with_89 import ( -9 + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, + 7 + from line_with_88 import aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + 8 + from line_with_89 import ( + 9 + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 10 + ) 11 + from line_with_90 import ( 12 + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, @@ -33,5 +29,7 @@ help: Organize imports 17 + from line_with_92 import ( 18 + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 19 + ) -20 | from line_with_93 import ( +20 + from line_with_93 import ( +21 + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, +22 + ) | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__fit_line_length_comment.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__fit_line_length_comment.py.snap index 0be10899f89b8..21ee57983c7a2 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__fit_line_length_comment.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__fit_line_length_comment.py.snap @@ -15,21 +15,19 @@ I001 [*] Import block is un-sorted or un-formatted | |_______________^ help: Organize imports | -1 | import a -2 + -3 | # Don't take this comment into account when determining whether the next import can fit on one line. -4 | from b import c - - from d import e # Do take this comment into account when determining whether the next import can fit on one line. -5 + from d import ( -6 + e, # Do take this comment into account when determining whether the next import can fit on one line. -7 + ) -8 + -9 | # The next import fits on one line. -10 | from f import g # 012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ -11 + -12 | # The next import doesn't fit on one line. - - from h import i # 012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9 + 1 + import a + 2 + + 3 + # Don't take this comment into account when determining whether the next import can fit on one line. + 4 + from b import c + 5 + from d import ( + 6 + e, # Do take this comment into account when determining whether the next import can fit on one line. + 7 + ) + 8 + + 9 + # The next import fits on one line. +10 ~ from f import g # 012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ +11 + +12 + # The next import doesn't fit on one line. 13 + from h import ( -14 + i, # 012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9 +14 ~ i, # 012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9012ß9💣2ℝ9 15 + ) | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_single_line_force_single_line.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_single_line_force_single_line.py.snap index c48cd441fdf58..ff73fb05dbb99 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_single_line_force_single_line.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_single_line_force_single_line.py.snap @@ -34,46 +34,32 @@ I001 [*] Import block is un-sorted or un-formatted | |_________________^ help: Organize imports | - - import sys, math - - from os import path, uname -1 + import math -2 + import sys -3 | from json import detect_encoding --------------------------------------------------------------------------------- -7 | from json import loads as json_loads - - from logging.handlers import StreamHandler, FileHandler -8 + from logging.handlers import FileHandler, StreamHandler -9 + from os import path, uname -10 | - - # comment 1 - - from third_party import lib1, lib2, \ - - lib3, lib7, lib5, lib6 - - # comment 2 - - from third_party import lib4 + 1 + import math + 2 + import sys + 3 + from json import detect_encoding + 4 + from json import dump + 5 + from json import dumps as json_dumps + 6 + from json import load + 7 + from json import loads as json_loads + 8 + from logging.handlers import FileHandler, StreamHandler + 9 + from os import path, uname +10 + 11 + # comment 6 12 + from bar import a # comment 7 13 + from bar import b # comment 8 -14 | +14 + 15 + # comment 9 16 + from baz import * # comment 10 -17 | from foo import bar # comment 3 -18 | from foo2 import bar2 # comment 4 - - from foo3 import bar3, baz3 # comment 5 +17 + from foo import bar # comment 3 +18 + from foo2 import bar2 # comment 4 19 + from foo3 import bar3 # comment 5 20 + from foo3 import baz3 # comment 5 -21 | - - # comment 6 - - from bar import ( - - a, # comment 7 - - b, # comment 8 - - ) +21 + 22 + # comment 1 23 + from third_party import lib1 24 + from third_party import lib2 25 + from third_party import lib3 -26 | - - # comment 9 - - from baz import * # comment 10 +26 + 27 + # comment 2 28 + from third_party import lib4 29 + from third_party import lib5 diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_sort_within_sections.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_sort_within_sections.py.snap index b7f693ac66534..70f01536f1e26 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_sort_within_sections.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_sort_within_sections.py.snap @@ -20,23 +20,17 @@ I001 [*] Import block is un-sorted or un-formatted | |______________________________^ help: Organize imports | - - from a import a1 # import_from - - from c import * # import_from_star -1 | import a # import -2 + import b as b1 # import_as -3 | import c.d -4 + import z -5 + from a import a1 # import_from -6 + from c import * # import_from_star -7 | from z import z1 - - import b as b1 # import_as - - import z -8 | -9 + from ...grandparent import fn3 -10 | from ..parent import * + 1 + import a # import + 2 + import b as b1 # import_as + 3 + import c.d + 4 + import z + 5 + from a import a1 # import_from + 6 + from c import * # import_from_star + 7 + from z import z1 + 8 + + 9 + from ...grandparent import fn3 +10 + from ..parent import * 11 + from . import my -12 | from .my import fn - - from . import my -13 | from .my.nested import fn2 - - from ...grandparent import fn3 +12 + from .my import fn +13 + from .my.nested import fn2 | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_sort_within_sections_force_sort_within_sections.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_sort_within_sections_force_sort_within_sections.py.snap index 13c4640dcbe65..85822631a872c 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_sort_within_sections_force_sort_within_sections.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_sort_within_sections_force_sort_within_sections.py.snap @@ -20,24 +20,17 @@ I001 [*] Import block is un-sorted or un-formatted | |______________________________^ help: Organize imports | - - from a import a1 # import_from - - from c import * # import_from_star -1 + import z -2 + from z import z1 -3 | import a # import -4 + from a import a1 # import_from -5 + import b as b1 # import_as -6 + from c import * # import_from_star -7 | import c.d - - from z import z1 - - import b as b1 # import_as - - import z -8 | -9 + from ...grandparent import fn3 -10 | from ..parent import * + 1 + import z + 2 + from z import z1 + 3 + import a # import + 4 + from a import a1 # import_from + 5 + import b as b1 # import_as + 6 + from c import * # import_from_star + 7 + import c.d + 8 + + 9 + from ...grandparent import fn3 +10 + from ..parent import * 11 + from . import my -12 | from .my import fn - - from . import my -13 | from .my.nested import fn2 - - from ...grandparent import fn3 +12 + from .my import fn +13 + from .my.nested import fn2 | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_sort_within_sections_force_sort_within_sections_future.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_sort_within_sections_force_sort_within_sections_future.py.snap index 2f8f2c71ba0cd..ac242ab877430 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_sort_within_sections_force_sort_within_sections_future.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_sort_within_sections_force_sort_within_sections_future.py.snap @@ -10,6 +10,5 @@ I001 [*] Import block is un-sorted or un-formatted help: Organize imports | 1 + from __future__ import annotations -2 | import __future__ - - from __future__ import annotations +2 + import __future__ | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_sort_within_sections_force_sort_within_sections_with_as_names.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_sort_within_sections_force_sort_within_sections_with_as_names.py.snap index 046d53ad5d980..be32b818da747 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_sort_within_sections_force_sort_within_sections_with_as_names.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_sort_within_sections_force_sort_within_sections_with_as_names.py.snap @@ -16,9 +16,5 @@ help: Organize imports 2 + import datetime as dt 3 + from datetime import timedelta 4 + from datetime import timezone as tz -5 | import encodings - - from datetime import timezone as tz - - from datetime import timedelta - - import datetime as dt - - import datetime +5 + import encodings | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_sort_within_sections_lazy_force_sort_within_sections.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_sort_within_sections_lazy_force_sort_within_sections.py.snap index 87eb58ef3146a..ca8c6eec05298 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_sort_within_sections_lazy_force_sort_within_sections.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_sort_within_sections_lazy_force_sort_within_sections.py.snap @@ -13,8 +13,6 @@ help: Organize imports | 1 + from math import pi 2 + import os -3 | lazy from math import pi - - from math import pi -4 | lazy import os - - import os +3 + lazy from math import pi +4 + lazy import os | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_to_top.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_to_top.py.snap index b226f8936c6c5..843ccc73e9518 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_to_top.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_to_top.py.snap @@ -30,37 +30,23 @@ I001 [*] Import block is un-sorted or un-formatted | |______________________________^ help: Organize imports | - - import lib6 -1 + import foo -2 + import lib1 -3 | import lib2 - - import lib5 - - import lib1 -4 | import lib3 -5 + import lib3.lib4 -6 + import lib3.lib4.lib5 -7 | import lib4 - - - - import foo -8 + import lib5 -9 + import lib6 -10 | import z -11 | from foo import bar + 1 + import foo + 2 + import lib1 + 3 + import lib2 + 4 + import lib3 + 5 + import lib3.lib4 + 6 + import lib3.lib4.lib5 + 7 + import lib4 + 8 + import lib5 + 9 + import lib6 +10 + import z +11 + from foo import bar 12 + from foo.lib1.bar import baz -13 | from lib1 import foo - - from lib2 import foo -14 | from lib1.lib2 import foo - - from foo.lib1.bar import baz - - from lib4 import lib1 - - from lib5 import lib2 - - from lib4 import lib2 - - from lib5 import lib1 - - - - import lib3.lib4 - - import lib3.lib4.lib5 +13 + from lib1 import foo +14 + from lib1.lib2 import foo 15 + from lib2 import foo -16 | from lib3.lib4 import foo -17 | from lib3.lib4.lib5 import foo +16 + from lib3.lib4 import foo +17 + from lib3.lib4.lib5 import foo 18 + from lib4 import lib1, lib2 19 + from lib5 import lib1, lib2 | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_to_top_force_to_top.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_to_top_force_to_top.py.snap index 47564887eae0f..4b68feb14423d 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_to_top_force_to_top.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_to_top_force_to_top.py.snap @@ -30,40 +30,23 @@ I001 [*] Import block is un-sorted or un-formatted | |______________________________^ help: Organize imports | - - import lib6 - - import lib2 - - import lib5 -1 | import lib1 -2 | import lib3 - - import lib4 - - -3 + import lib3.lib4 -4 + import lib5 -5 + import z -6 | import foo - - import z -7 + import lib2 -8 + import lib3.lib4.lib5 -9 + import lib4 + 1 + import lib1 + 2 + import lib3 + 3 + import lib3.lib4 + 4 + import lib5 + 5 + import z + 6 + import foo + 7 + import lib2 + 8 + import lib3.lib4.lib5 + 9 + import lib4 10 + import lib6 11 + from lib1 import foo 12 + from lib3.lib4 import foo 13 + from lib5 import lib1, lib2 -14 | from foo import bar - - from lib1 import foo - - from lib2 import foo - - from lib1.lib2 import foo -15 | from foo.lib1.bar import baz - - from lib4 import lib1 - - from lib5 import lib2 - - from lib4 import lib2 - - from lib5 import lib1 - - - - import lib3.lib4 - - import lib3.lib4.lib5 - - from lib3.lib4 import foo +14 + from foo import bar +15 + from foo.lib1.bar import baz 16 + from lib1.lib2 import foo 17 + from lib2 import foo -18 | from lib3.lib4.lib5 import foo +18 + from lib3.lib4.lib5 import foo 19 + from lib4 import lib1, lib2 | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_wrap_aliases.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_wrap_aliases.py.snap index ad36f643acacf..65a1da421ecb2 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_wrap_aliases.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_wrap_aliases.py.snap @@ -10,8 +10,8 @@ I001 [*] Import block is un-sorted or un-formatted | |_________________^ help: Organize imports | - - from .a import a1 as a1, a2 as a2 1 + from .a import a1 as a1 2 + from .a import a2 as a2 -3 | from .b import b1 as b1 +3 + from .b import b1 as b1 +4 + from .c import c1 | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_wrap_aliases_force_wrap_aliases.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_wrap_aliases_force_wrap_aliases.py.snap index 55e2ef2493d2c..503eba18190be 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_wrap_aliases_force_wrap_aliases.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__force_wrap_aliases_force_wrap_aliases.py.snap @@ -10,10 +10,10 @@ I001 [*] Import block is un-sorted or un-formatted | |_________________^ help: Organize imports | - - from .a import a1 as a1, a2 as a2 1 + from .a import ( 2 + a1 as a1, 3 + a2 as a2, 4 + ) -5 | from .b import b1 as b1 +5 + from .b import b1 as b1 +6 + from .c import c1 | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__forced_separate.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__forced_separate.py.snap index 1f5f81af22dc1..dd58001f20692 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__forced_separate.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__forced_separate.py.snap @@ -15,14 +15,12 @@ I001 [*] Import block is un-sorted or un-formatted | |__________________________________________________________^ help: Organize imports | -2 | # but we want tests and experiments to be separated, in that order -3 + from office_helper.assistants import entity_registry as er -4 | from office_helper.core import CoreState -5 + -6 | import tests.common.foo as tcf -7 | from tests.common import async_mock_service -8 + -9 | from experiments.starry import * -10 | from experiments.weird import varieties - - from office_helper.assistants import entity_registry as er + 3 + from office_helper.assistants import entity_registry as er + 4 + from office_helper.core import CoreState + 5 + + 6 + import tests.common.foo as tcf + 7 + from tests.common import async_mock_service + 8 + + 9 + from experiments.starry import * +10 + from experiments.weird import varieties | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__from_first_lazy_from_first.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__from_first_lazy_from_first.py.snap index f35e5a369afe7..f97ade8544e10 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__from_first_lazy_from_first.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__from_first_lazy_from_first.py.snap @@ -12,11 +12,9 @@ I001 [*] Import block is un-sorted or un-formatted help: Organize imports | 1 + from math import pi -2 + +2 + 3 + import os -4 | lazy from math import pi - - from math import pi -5 + -6 | lazy import os - - import os +4 + lazy from math import pi +5 + +6 + lazy import os | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__future_from.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__future_from.py.snap index 782750f0b494b..8e5b3fe92cedd 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__future_from.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__future_from.py.snap @@ -10,6 +10,5 @@ I001 [*] Import block is un-sorted or un-formatted help: Organize imports | 1 + from __future__ import annotations -2 | import __future__ - - from __future__ import annotations +2 + import __future__ | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__glob_1_separate_subpackage_first_and_third_party_imports.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__glob_1_separate_subpackage_first_and_third_party_imports.py.snap index 4af5fa8f98df5..923b5b59d7277 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__glob_1_separate_subpackage_first_and_third_party_imports.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__glob_1_separate_subpackage_first_and_third_party_imports.py.snap @@ -15,18 +15,14 @@ I001 [*] Import block is un-sorted or un-formatted | |__________________^ help: Organize imports | -1 | import sys -2 + -3 + import foo -4 + from foo import bar, baz -5 + -6 | import baz - - from foo import bar, baz -7 + import foo.bar -8 + import foo.bar.baz -9 | from foo.bar import blah, blub -10 | from foo.bar.baz import something - - import foo - - import foo.bar - - import foo.bar.baz + 1 + import sys + 2 + + 3 + import foo + 4 + from foo import bar, baz + 5 + + 6 + import baz + 7 + import foo.bar + 8 + import foo.bar.baz + 9 + from foo.bar import blah, blub +10 + from foo.bar.baz import something | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__if_elif_else.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__if_elif_else.py.snap index ed5a1d04bad10..5e8d0d31ccafd 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__if_elif_else.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__if_elif_else.py.snap @@ -11,8 +11,6 @@ I001 [*] Import block is un-sorted or un-formatted | |_______________________________________________________^ help: Organize imports | -5 | else: 6 + from distutils.command.sdist import sdist as _sdist -7 | from setuptools.command.sdist import sdist as _sdist - - from distutils.command.sdist import sdist as _sdist +7 + from setuptools.command.sdist import sdist as _sdist | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_from_after_import.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_from_after_import.py.snap index 1b72f5f7a553a..296487cd7511a 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_from_after_import.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_from_after_import.py.snap @@ -10,6 +10,5 @@ I001 [*] Import block is un-sorted or un-formatted help: Organize imports | 1 + import os -2 | from collections import Collection - - import os +2 + from collections import Collection | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_force_sort_within_sections_import_heading_force_sort_within_sections.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_force_sort_within_sections_import_heading_force_sort_within_sections.py.snap index 6319a48b69f2d..6a3e139f83ff5 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_force_sort_within_sections_import_heading_force_sort_within_sections.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_force_sort_within_sections_import_heading_force_sort_within_sections.py.snap @@ -13,13 +13,12 @@ I001 [*] Import block is un-sorted or un-formatted help: Organize imports | 1 + # Future imports -2 | from __future__ import annotations -3 + +2 + from __future__ import annotations +3 + 4 + # Standard library imports -5 | from typing import Any -6 | - - import requests +5 + from typing import Any +6 + 7 + # Third party imports -8 | import pandas +8 + import pandas 9 + import requests | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_import_heading.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_import_heading.py.snap index 97506d845c3a2..dec4d6fcde727 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_import_heading.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_import_heading.py.snap @@ -18,21 +18,20 @@ I001 [*] Import block is un-sorted or un-formatted | |____________________________________^ help: Organize imports | -1 + # Future imports -2 | from __future__ import annotations -3 | -4 + # Standard library imports -5 | import os -6 | import sys -7 | - - import requests -8 + # Third party imports -9 | import pandas + 1 + # Future imports + 2 + from __future__ import annotations + 3 + + 4 + # Standard library imports + 5 + import os + 6 + import sys + 7 + + 8 + # Third party imports + 9 + import pandas 10 + import requests -11 | +11 + 12 + # First party imports -13 | from my_first_party import my_first_party_object -14 | +13 + from my_first_party import my_first_party_object +14 + 15 + # Local folder imports -16 | from . import my_local_folder_object +16 + from . import my_local_folder_object | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_import_heading_already_present.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_import_heading_already_present.py.snap index 9c98987e91b15..17c88ae93e5dd 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_import_heading_already_present.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_import_heading_already_present.py.snap @@ -22,14 +22,20 @@ I001 [*] Import block is un-sorted or un-formatted | |____________________________________^ help: Organize imports | -8 | # Third party imports -9 + import pandas -10 | import requests - - import pandas -11 | -12 | # First party imports -13 | from my_first_party import my_first_party_object -14 | + 1 + # Future imports + 2 + from __future__ import annotations + 3 + + 4 + # Standard library imports + 5 + import os + 6 + import sys + 7 + + 8 + # Third party imports + 9 + import pandas +10 + import requests +11 + +12 + # First party imports +13 + from my_first_party import my_first_party_object +14 + 15 + # Local folder imports -16 | from . import my_local_folder_object +16 + from . import my_local_folder_object | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_import_heading_duplicate.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_import_heading_duplicate.py.snap index 5011e2658c54e..28ca57a00d41f 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_import_heading_duplicate.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_import_heading_duplicate.py.snap @@ -14,13 +14,11 @@ I001 [*] Import block is un-sorted or un-formatted | |_____________^ help: Organize imports | -1 | # Standard library imports - - # Standard library imports -2 | import os -3 | import sys -4 | +1 + # Standard library imports +2 + import os +3 + import sys +4 + 5 + # Third party imports 6 + import pandas -7 | import requests - - import pandas +7 + import requests | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_import_heading_unsorted.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_import_heading_unsorted.py.snap index f8eca59df0332..f0a1c08810133 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_import_heading_unsorted.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_import_heading_unsorted.py.snap @@ -14,22 +14,20 @@ I001 [*] Import block is un-sorted or un-formatted | |____________________________________^ help: Organize imports | - - import pandas - - import os -1 + # Future imports -2 | from __future__ import annotations -3 + -4 + # Standard library imports -5 + import os -6 | import sys -7 + -8 + # Third party imports -9 + import pandas -10 | import requests -11 + + 1 + # Future imports + 2 + from __future__ import annotations + 3 + + 4 + # Standard library imports + 5 + import os + 6 + import sys + 7 + + 8 + # Third party imports + 9 + import pandas +10 + import requests +11 + 12 + # First party imports -13 | from my_first_party import my_first_party_object -14 + +13 + from my_first_party import my_first_party_object +14 + 15 + # Local folder imports -16 | from . import my_local_folder_object +16 + from . import my_local_folder_object | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_partial_import_heading_partial.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_partial_import_heading_partial.py.snap index 147944e848a5c..2ff8890a7a02b 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_partial_import_heading_partial.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_partial_import_heading_partial.py.snap @@ -13,11 +13,10 @@ I001 [*] Import block is un-sorted or un-formatted help: Organize imports | 1 + # Standard library imports -2 | import os -3 | import sys -4 | +2 + import os +3 + import sys +4 + 5 + # Third party imports 6 + import pandas -7 | import requests - - import pandas +7 + import requests | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_single_section_import_heading_single_section.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_single_section_import_heading_single_section.py.snap index 5be1e45c00a00..591d60e0cbb73 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_single_section_import_heading_single_section.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_single_section_import_heading_single_section.py.snap @@ -9,8 +9,7 @@ I001 [*] Import block is un-sorted or un-formatted | |_____________^ help: Organize imports | - - import requests 1 + # Third party imports -2 | import pandas +2 + import pandas 3 + import requests | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_with_no_lines_before_import_heading_with_no_lines_before.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_with_no_lines_before_import_heading_with_no_lines_before.py.snap index cdf84e9b59305..fa39d97750ff1 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_with_no_lines_before_import_heading_with_no_lines_before.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_with_no_lines_before_import_heading_with_no_lines_before.py.snap @@ -18,21 +18,19 @@ I001 [*] Import block is un-sorted or un-formatted | |____________________________________^ help: Organize imports | -1 + # Future imports -2 | from __future__ import annotations -3 | -4 + # Standard library imports -5 | import os -6 | import sys -7 | -8 + # Third party imports -9 + import pandas -10 | import requests - - import pandas -11 | + 1 + # Future imports + 2 + from __future__ import annotations + 3 + + 4 + # Standard library imports + 5 + import os + 6 + import sys + 7 + + 8 + # Third party imports + 9 + import pandas +10 + import requests +11 + 12 + # First party imports -13 | from my_first_party import my_first_party_object - - +13 + from my_first_party import my_first_party_object 14 + # Local folder imports -15 | from . import my_local_folder_object +15 + from . import my_local_folder_object | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_wrong_heading_import_heading_wrong_heading.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_wrong_heading_import_heading_wrong_heading.py.snap index 80bec7999ac9e..5663705b7f92f 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_wrong_heading_import_heading_wrong_heading.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__import_heading_wrong_heading_import_heading_wrong_heading.py.snap @@ -16,16 +16,15 @@ I001 [*] Import block is un-sorted or un-formatted | |________________________________________________^ help: Organize imports | -1 | # Wrong heading -2 + # Standard library imports -3 | import os -4 | import sys -5 | -6 + # Third party imports -7 | # Also wrong heading -8 | import pandas -9 | import requests -10 | + 2 + # Standard library imports + 3 + import os + 4 + import sys + 5 + + 6 + # Third party imports + 7 + # Also wrong heading + 8 + import pandas + 9 + import requests +10 + 11 + # First party imports -12 | from my_first_party import my_first_party_object +12 + from my_first_party import my_first_party_object | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__inline_comments.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__inline_comments.py.snap index 1e561c667093c..999859637d641 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__inline_comments.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__inline_comments.py.snap @@ -18,18 +18,15 @@ I001 [*] Import block is un-sorted or un-formatted | |______________________________________________________________________________________^ help: Organize imports | -3 | ) - - -4 | from b.prometheus.metrics import ( -5 | TERMINAL_CURRENTLY_RUNNING_TOTAL, # type:ignore[attr-defined] -6 | ) - - - - from c.prometheus.metrics import TERMINAL_CURRENTLY_RUNNING_TOTAL # type:ignore[attr-defined] - - - - from d.prometheus.metrics import TERMINAL_CURRENTLY_RUNNING_TOTAL, OTHER_RUNNING_TOTAL # type:ignore[attr-defined] -7 + from c.prometheus.metrics import ( -8 + TERMINAL_CURRENTLY_RUNNING_TOTAL, # type:ignore[attr-defined] -9 + ) + 1 + from a.prometheus.metrics import ( # type:ignore[attr-defined] + 2 + TERMINAL_CURRENTLY_RUNNING_TOTAL, + 3 + ) + 4 + from b.prometheus.metrics import ( + 5 + TERMINAL_CURRENTLY_RUNNING_TOTAL, # type:ignore[attr-defined] + 6 + ) + 7 + from c.prometheus.metrics import ( + 8 + TERMINAL_CURRENTLY_RUNNING_TOTAL, # type:ignore[attr-defined] + 9 + ) 10 + from d.prometheus.metrics import ( # type:ignore[attr-defined] 11 + OTHER_RUNNING_TOTAL, 12 + TERMINAL_CURRENTLY_RUNNING_TOTAL, diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__known_local_folder_closest_separate_local_folder_imports.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__known_local_folder_closest_separate_local_folder_imports.py.snap index 9d1897dd175a3..bb4f4bbfc60e4 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__known_local_folder_closest_separate_local_folder_imports.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__known_local_folder_closest_separate_local_folder_imports.py.snap @@ -15,12 +15,12 @@ I001 [*] Import block is un-sorted or un-formatted help: Organize imports | 1 + import os -2 | import sys -3 + +2 + import sys +3 + 4 + import leading_prefix -5 + -6 | import ruff - - import leading_prefix - - import os -7 | from . import leading_prefix +5 + +6 + import ruff +7 + from . import leading_prefix +8 + from .. import trailing_prefix +9 + from ruff import check | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__known_local_folder_separate_local_folder_imports.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__known_local_folder_separate_local_folder_imports.py.snap index cfaa6b42c8aee..d0e2a981511b1 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__known_local_folder_separate_local_folder_imports.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__known_local_folder_separate_local_folder_imports.py.snap @@ -15,15 +15,12 @@ I001 [*] Import block is un-sorted or un-formatted help: Organize imports | 1 + import os -2 | import sys -3 + +2 + import sys +3 + 4 + import leading_prefix -5 + -6 | import ruff - - import leading_prefix - - import os +5 + +6 + import ruff 7 + from .. import trailing_prefix -8 | from . import leading_prefix - - from .. import trailing_prefix -9 | from ruff import check +8 + from . import leading_prefix +9 + from ruff import check | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lazy_imports.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lazy_imports.py.snap index 23ebddd7180a1..eec2e02027e39 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lazy_imports.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lazy_imports.py.snap @@ -11,10 +11,8 @@ I001 [*] Import block is un-sorted or un-formatted | |_________^ help: Organize imports | - - lazy from math import pi 1 + import os -2 | from math import pi -3 | lazy import os - - import os +2 + from math import pi +3 + lazy import os 4 + lazy from math import pi | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_from_imports.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_from_imports.py.snap index 52b4750dac3a0..a2f555018d2cf 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_from_imports.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_from_imports.py.snap @@ -11,7 +11,6 @@ I001 [*] Import block is un-sorted or un-formatted help: Organize imports | 1 + from short import b -2 | from mediuuuuuuuuuuum import a - - from short import b -3 | from loooooooooooooooooooooog import c +2 + from mediuuuuuuuuuuum import a +3 + from loooooooooooooooooooooog import c | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_non_ascii_members.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_non_ascii_members.py.snap index d8f31f831063a..2b84e01a77a0a 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_non_ascii_members.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_non_ascii_members.py.snap @@ -18,19 +18,15 @@ I001 [*] Import block is un-sorted or un-formatted | |_^ help: Organize imports | -1 | from module1 import ( - - loooooooooooooong, -2 + short, -3 | σηορτ, -4 + shoort, -5 | mediuuuuum, - - shoort, - - looooooooooooooong, -6 | μεδιυυυυυμ, - - short, -7 | mediuuuuuum, -8 + loooooooooooooong, -9 | λοοοοοοοοοοοοοονγ, + 1 + from module1 import ( + 2 + short, + 3 ~ σηορτ, + 4 + shoort, + 5 + mediuuuuum, + 6 ~ μεδιυυυυυμ, + 7 + mediuuuuuum, + 8 + loooooooooooooong, + 9 ~ λοοοοοοοοοοοοοονγ, 10 + looooooooooooooong, -11 | ) +11 + ) | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_non_ascii_modules.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_non_ascii_modules.py.snap index ad038adb64d96..7c3ac45f48dc5 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_non_ascii_modules.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_non_ascii_modules.py.snap @@ -16,16 +16,13 @@ I001 [*] Import block is un-sorted or un-formatted | |_________________________^ help: Organize imports | - - import loooooooooooooong - - import mediuuuuuum -1 | import short -2 | import σηορτ -3 | import shoort -4 | import mediuuuuum -5 + import μεδιυυυυυμ +1 + import short +2 ~ import σηορτ +3 + import shoort +4 + import mediuuuuum +5 ~ import μεδιυυυυυμ 6 + import mediuuuuuum 7 + import loooooooooooooong -8 | import λοοοοοοοοοοοοοονγ - - import μεδιυυυυυμ -9 | import looooooooooooooong +8 ~ import λοοοοοοοοοοοοοονγ +9 + import looooooooooooooong | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_straight_and_from_imports.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_straight_and_from_imports.py.snap index d969d064fefa0..72bcd2729352f 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_straight_and_from_imports.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_straight_and_from_imports.py.snap @@ -14,12 +14,9 @@ I001 [*] Import block is un-sorted or un-formatted help: Organize imports | 1 + import short -2 | import mediuuuuuum - - import short -3 | import looooooooooooooooong - - from looooooooooooooong import a +2 + import mediuuuuuum +3 + import looooooooooooooooong 4 + from short import b -5 | from mediuuuum import c - - from short import b +5 + from mediuuuum import c 6 + from looooooooooooooong import a | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_straight_imports.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_straight_imports.py.snap index 629a252b9c499..3ff77dcc25559 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_straight_imports.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_straight_imports.py.snap @@ -13,8 +13,6 @@ help: Organize imports | 1 + import short 2 + import mediuuuuuuma -3 | import mediuuuuuumb - - import short -4 | import looooooooooooooooong - - import mediuuuuuuma +3 + import mediuuuuuumb +4 + import looooooooooooooooong | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_with_relative_imports.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_with_relative_imports.py.snap index f9eae0c402b3e..93fdf9017c301 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_with_relative_imports.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort__length_sort_with_relative_imports.py.snap @@ -14,14 +14,11 @@ I001 [*] Import block is un-sorted or un-formatted | |_________________________^ help: Organize imports | - - from ..looooooooooooooong import a - - from ...mediuuuum import b 1 + from . import d -2 | from .short import c -3 | from ....short import c - - from . import d -4 | from .mediuuuum import a -5 | from ......short import b +2 + from .short import c +3 + from ....short import c +4 + from .mediuuuum import a +5 + from ......short import b 6 + from ...mediuuuum import b 7 + from ..looooooooooooooong import a | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort_straight__length_sort_from_imports.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort_straight__length_sort_from_imports.py.snap index dde79e759427a..e572b93d96d35 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort_straight__length_sort_from_imports.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort_straight__length_sort_from_imports.py.snap @@ -11,7 +11,6 @@ I001 [*] Import block is un-sorted or un-formatted help: Organize imports | 1 + from loooooooooooooooooooooog import c -2 | from mediuuuuuuuuuuum import a -3 | from short import b - - from loooooooooooooooooooooog import c +2 + from mediuuuuuuuuuuum import a +3 + from short import b | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort_straight__length_sort_straight_and_from_imports.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort_straight__length_sort_straight_and_from_imports.py.snap index 3299b6f541b78..28fff86bfb051 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort_straight__length_sort_straight_and_from_imports.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort_straight__length_sort_straight_and_from_imports.py.snap @@ -14,7 +14,9 @@ I001 [*] Import block is un-sorted or un-formatted help: Organize imports | 1 + import short -2 | import mediuuuuuum - - import short -3 | import looooooooooooooooong +2 + import mediuuuuuum +3 + import looooooooooooooooong +4 + from looooooooooooooong import a +5 + from mediuuuum import c +6 + from short import b | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort_straight__length_sort_straight_imports.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort_straight__length_sort_straight_imports.py.snap index 629a252b9c499..3ff77dcc25559 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort_straight__length_sort_straight_imports.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__length_sort_straight__length_sort_straight_imports.py.snap @@ -13,8 +13,6 @@ help: Organize imports | 1 + import short 2 + import mediuuuuuuma -3 | import mediuuuuuumb - - import short -4 | import looooooooooooooooong - - import mediuuuuuuma +3 + import mediuuuuuumb +4 + import looooooooooooooooong | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__line_ending_crlf.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__line_ending_crlf.py.snap index d6e945ffebcf4..ff5d6372dbe6d 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__line_ending_crlf.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__line_ending_crlf.py.snap @@ -8,13 +8,11 @@ I001 [*] Import block is un-sorted or un-formatted | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Organize imports | - - from long_module_name import member_one, member_two, member_three, member_four, member_five -1 + from long_module_name import ( -2 + member_five, -3 + member_four, -4 + member_one, -5 + member_three, -6 + member_two, -7 + ) -8 | +1 ~ from long_module_name import ( +2 ~ member_five, +3 ~ member_four, +4 ~ member_one, +5 ~ member_three, +6 ~ member_two, +7 + )␍ | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__line_ending_lf.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__line_ending_lf.py.snap index 5ff5c8e84a4ab..b2c395f51b1e0 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__line_ending_lf.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__line_ending_lf.py.snap @@ -8,7 +8,6 @@ I001 [*] Import block is un-sorted or un-formatted | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Organize imports | - - from long_module_name import member_one, member_two, member_three, member_four, member_five 1 + from long_module_name import ( 2 + member_five, 3 + member_four, @@ -16,5 +15,4 @@ help: Organize imports 5 + member_three, 6 + member_two, 7 + ) -8 | | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports.pyi.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports.pyi.snap index 1653128b16a11..db200505c01bf 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports.pyi.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports.pyi.snap @@ -16,14 +16,12 @@ I001 [*] Import block is un-sorted or un-formatted | |____________________________________^ help: Organize imports | -4 | - - from requests import Session - - -5 | from my_first_party import my_first_party_object +1 + from __future__ import annotations +2 + +3 + from typing import Any +4 + +5 + from my_first_party import my_first_party_object 6 + from requests import Session -7 | -8 | from . import my_local_folder_object - - - - -9 | +7 + +8 + from . import my_local_folder_object | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_class_after.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_class_after.py.snap index 96fe2732bc42b..a5dd5080a7961 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_class_after.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_class_after.py.snap @@ -18,15 +18,13 @@ I001 [*] Import block is un-sorted or un-formatted 11 | name: str | help: Organize imports - | -4 | - - from requests import Session - - -5 | from my_first_party import my_first_party_object -6 + from requests import Session -7 | -8 | from . import my_local_folder_object -9 + -10 + -11 | class Thing(object): - | + | +1 + from __future__ import annotations +2 + +3 + from typing import Any +4 + +5 + from my_first_party import my_first_party_object +6 + from requests import Session +7 + +8 + from . import my_local_folder_object + | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_func_after.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_func_after.py.snap index ad9975a69afe0..22b3e85a9060b 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_func_after.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_func_after.py.snap @@ -16,21 +16,12 @@ I001 [*] Import block is un-sorted or un-formatted | |____________________________________^ help: Organize imports | -4 | - - from requests import Session - - -5 | from my_first_party import my_first_party_object +1 + from __future__ import annotations +2 + +3 + from typing import Any +4 + +5 + from my_first_party import my_first_party_object 6 + from requests import Session -7 | -8 | from . import my_local_folder_object - - - - - - - - - - - - - - - - - - -9 | +7 + +8 + from . import my_local_folder_object | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_lines_after_imports.pyi.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_lines_after_imports.pyi.snap index 1653128b16a11..db200505c01bf 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_lines_after_imports.pyi.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_lines_after_imports.pyi.snap @@ -16,14 +16,12 @@ I001 [*] Import block is un-sorted or un-formatted | |____________________________________^ help: Organize imports | -4 | - - from requests import Session - - -5 | from my_first_party import my_first_party_object +1 + from __future__ import annotations +2 + +3 + from typing import Any +4 + +5 + from my_first_party import my_first_party_object 6 + from requests import Session -7 | -8 | from . import my_local_folder_object - - - - -9 | +7 + +8 + from . import my_local_folder_object | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_lines_after_imports_class_after.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_lines_after_imports_class_after.py.snap index 7aec8ed571a0a..a5dd5080a7961 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_lines_after_imports_class_after.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_lines_after_imports_class_after.py.snap @@ -18,16 +18,13 @@ I001 [*] Import block is un-sorted or un-formatted 11 | name: str | help: Organize imports - | -4 | -5 + from my_first_party import my_first_party_object -6 | from requests import Session -7 | - - from my_first_party import my_first_party_object -8 + from . import my_local_folder_object -9 + -10 + -11 | - - from . import my_local_folder_object -12 | class Thing(object): - | + | +1 + from __future__ import annotations +2 + +3 + from typing import Any +4 + +5 + from my_first_party import my_first_party_object +6 + from requests import Session +7 + +8 + from . import my_local_folder_object + | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_lines_after_imports_func_after.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_lines_after_imports_func_after.py.snap index 35fb31db47e81..22b3e85a9060b 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_lines_after_imports_func_after.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_lines_after_imports_func_after.py.snap @@ -16,20 +16,12 @@ I001 [*] Import block is un-sorted or un-formatted | |____________________________________^ help: Organize imports | -4 | - - from requests import Session - - -5 | from my_first_party import my_first_party_object +1 + from __future__ import annotations +2 + +3 + from typing import Any +4 + +5 + from my_first_party import my_first_party_object 6 + from requests import Session -7 | -8 | from . import my_local_folder_object - - - - - - - - - - - - - - - - -9 | +7 + +8 + from . import my_local_folder_object | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_lines_after_imports_nothing_after.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_lines_after_imports_nothing_after.py.snap index aa1e760692d5b..1e1d07201abf3 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_lines_after_imports_nothing_after.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_after_imports_lines_after_imports_nothing_after.py.snap @@ -16,10 +16,12 @@ I001 [*] Import block is un-sorted or un-formatted | |____________________________________^ help: Organize imports | -4 | - - from requests import Session - - -5 | from my_first_party import my_first_party_object +1 + from __future__ import annotations +2 + +3 + from typing import Any +4 + +5 + from my_first_party import my_first_party_object 6 + from requests import Session -7 | +7 + +8 + from . import my_local_folder_object | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_between_typeslines_between_types.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_between_typeslines_between_types.py.snap index 890cea62bc991..e3c9d08218cda 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_between_typeslines_between_types.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__lines_between_typeslines_between_types.py.snap @@ -23,9 +23,20 @@ I001 [*] Import block is un-sorted or un-formatted | |______________________^ help: Organize imports | -11 | + 1 + from __future__ import annotations + 2 + + 3 + import datetime + 4 + import json + 5 + + 6 + + 7 + from binascii import hexlify + 8 + + 9 + import requests +10 + +11 + 12 + from loguru import Logger -13 | from sanic import Sanic - - from loguru import Logger -14 | +13 + from sanic import Sanic +14 + +15 + from . import config +16 + from .data import Data | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__magic_trailing_comma.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__magic_trailing_comma.py.snap index ac554299c2de8..64d406be291a4 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__magic_trailing_comma.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__magic_trailing_comma.py.snap @@ -45,53 +45,35 @@ I001 [*] Import block is un-sorted or un-formatted | |_^ help: Organize imports | -1 | # This has a magic trailing comma, will be sorted, but not rolled into one line - - from sys import ( - - stderr, - - argv, - - stdout, - - exit, -2 + from glob import ( -3 + escape, # Ends with a comment, should still treat as magic trailing comma. -4 + glob, -5 + iglob, -6 | ) -7 | -8 | # No magic comma, this will be rolled into one line. - - from os import ( - - path, - - environ, - - execl, - - execv - - ) - - - - from glob import ( - - glob, - - iglob, - - escape, # Ends with a comment, should still treat as magic trailing comma. -9 + from os import environ, execl, execv, path + 2 + from glob import ( + 3 + escape, # Ends with a comment, should still treat as magic trailing comma. + 4 + glob, + 5 + iglob, + 6 + ) + 7 + + 8 + # No magic comma, this will be rolled into one line. + 9 + from os import environ, execl, execv, path 10 + from sys import ( 11 + argv, 12 + exit, 13 + stderr, 14 + stdout, -15 | ) -16 | -17 | # These will be combined, but without a trailing comma. - - from foo import bar - - from foo import baz +15 + ) +16 + +17 + # These will be combined, but without a trailing comma. 18 + from foo import bar, baz -19 | -20 | # These will be combined, _with_ a trailing comma. - - from module1 import member1 -21 | from module1 import ( +19 + +20 + # These will be combined, _with_ a trailing comma. +21 + from module1 import ( 22 + member1, -23 | member2, --------------------------------------------------------------------------------- -27 | # These will be combined, _with_ a trailing comma. - - from module2 import member1, member2 -28 | from module2 import ( +23 + member2, +24 + member3, +25 + ) +26 + +27 + # These will be combined, _with_ a trailing comma. +28 + from module2 import ( 29 + member1, 30 + member2, -31 | member3, +31 + member3, +32 + ) | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__match_case.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__match_case.py.snap index 435058e786a68..1baeda56e3066 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__match_case.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__match_case.py.snap @@ -14,11 +14,8 @@ I001 [*] Import block is un-sorted or un-formatted | help: Organize imports | -2 | case 1: 3 + import os -4 | import sys - - import os -5 | case 2: +4 + import sys | I001 [*] Import block is un-sorted or un-formatted @@ -31,8 +28,6 @@ I001 [*] Import block is un-sorted or un-formatted | |__________________^ help: Organize imports | -5 | case 2: 6 + import abc -7 | import collections - - import abc +7 + import collections | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__natural_order.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__natural_order.py.snap index 9df996f9bbce3..b75fe91aac63d 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__natural_order.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__natural_order.py.snap @@ -23,21 +23,20 @@ I001 [*] Import block is un-sorted or un-formatted | |_^ help: Organize imports | -1 | import numpy1 -2 + import numpy2 -3 | import numpy10 - - import numpy2 -4 | from numpy import ( -5 | cos, -6 | int8, - - sin, -7 + int16, -8 | int32, -9 | int64, + 1 + import numpy1 + 2 + import numpy2 + 3 + import numpy10 + 4 + from numpy import ( + 5 + cos, + 6 + int8, + 7 + int16, + 8 + int32, + 9 + int64, 10 + sin, -11 | tan, -12 | uint8, -13 | uint16, - - int16, -14 | uint32, +11 + tan, +12 + uint8, +13 + uint16, +14 + uint32, +15 + uint64, +16 + ) | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_detect_same_package.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_detect_same_package.snap index 5c7538732e37b..2ee04dd69ad34 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_detect_same_package.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_detect_same_package.snap @@ -10,9 +10,8 @@ I001 [*] Import block is un-sorted or un-formatted | |______________^ help: Organize imports | -1 | import os - - import pandas -2 + -3 | import foo.baz +1 + import os +2 + +3 + import foo.baz 4 + import pandas | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_lines_before.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_lines_before.py.snap index 9a01d87bf60a0..7a4d1cee94a46 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_lines_before.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_lines_before.py.snap @@ -16,10 +16,12 @@ I001 [*] Import block is un-sorted or un-formatted | |____________________________________^ help: Organize imports | -4 | - - from requests import Session - - -5 | from my_first_party import my_first_party_object +1 + from __future__ import annotations +2 + +3 + from typing import Any +4 + +5 + from my_first_party import my_first_party_object 6 + from requests import Session -7 | +7 + +8 + from . import my_local_folder_object | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_lines_before.py_no_lines_before.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_lines_before.py_no_lines_before.py.snap index 1f491b556f367..29e899ad80bb1 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_lines_before.py_no_lines_before.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_lines_before.py_no_lines_before.py.snap @@ -16,14 +16,9 @@ I001 [*] Import block is un-sorted or un-formatted | |____________________________________^ help: Organize imports | -1 | from __future__ import annotations - - -2 | from typing import Any - - +1 + from __future__ import annotations +2 + from typing import Any 3 + from my_first_party import my_first_party_object -4 | from requests import Session - - - - from my_first_party import my_first_party_object - - -5 | from . import my_local_folder_object +4 + from requests import Session +5 + from . import my_local_folder_object | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_lines_before_with_empty_sections.py_no_lines_before_with_empty_sections.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_lines_before_with_empty_sections.py_no_lines_before_with_empty_sections.py.snap index f400356b5c0b2..f9c8b01e596bc 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_lines_before_with_empty_sections.py_no_lines_before_with_empty_sections.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_lines_before_with_empty_sections.py_no_lines_before_with_empty_sections.py.snap @@ -10,7 +10,4 @@ I001 [*] Import block is un-sorted or un-formatted | |____________________________________^ help: Organize imports | -2 | from typing import Any -3 + -4 | from . import my_local_folder_object | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_standard_library_no_standard_library.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_standard_library_no_standard_library.py.snap index 2329492ec61bd..41b83051adf59 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_standard_library_no_standard_library.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_standard_library_no_standard_library.py.snap @@ -16,14 +16,13 @@ I001 [*] Import block is un-sorted or un-formatted | |__________^ help: Organize imports | -2 | - - import os -3 | import django.settings -4 | from library import foo +1 + from __future__ import annotations +2 + +3 + import django.settings +4 + from library import foo 5 + import os -6 | import pytz +6 + import pytz 7 + import sys -8 | -9 | from . import local - - import sys +8 + +9 + from . import local | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_wrap_star.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_wrap_star.py.snap index 5f930fa4cf574..ae51c96586098 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_wrap_star.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__no_wrap_star.py.snap @@ -8,6 +8,5 @@ I001 [*] Import block is un-sorted or un-formatted | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Organize imports | - - from .subscription import * # type: ignore # some very long comment explaining why this needs a type ignore -1 + from .subscription import * # type: ignore # some very long comment explaining why this needs a type ignore - | +1 | from .subscription import * # type: ignore # some very long comment explaining why this needs a type ignore + | + diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type.py.snap index a5c6c7f57dd1e..5877b44d3bef8 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type.py.snap @@ -19,18 +19,15 @@ I001 [*] Import block is un-sorted or un-formatted | |__________^ help: Organize imports | - - import StringIO -1 | import glob --------------------------------------------------------------------------------- -5 | import time - - from subprocess import PIPE, Popen, STDOUT - - from module import Class, CONSTANT, function, BASIC, Apple - - import foo - - import FOO -6 + from subprocess import PIPE, STDOUT, Popen -7 + -8 | import BAR -9 | import bar + 1 + import glob + 2 + import os + 3 + import shutil + 4 + import tempfile + 5 + import time + 6 + from subprocess import PIPE, STDOUT, Popen + 7 + + 8 + import BAR + 9 + import bar 10 + import FOO 11 + import foo 12 + import StringIO diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_false_order_by_type.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_false_order_by_type.py.snap index 56f6cd71c8dfb..076b7e3718163 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_false_order_by_type.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_false_order_by_type.py.snap @@ -19,16 +19,15 @@ I001 [*] Import block is un-sorted or un-formatted | |__________^ help: Organize imports | - - import StringIO -1 | import glob --------------------------------------------------------------------------------- -6 | from subprocess import PIPE, Popen, STDOUT - - from module import Class, CONSTANT, function, BASIC, Apple - - import foo - - import FOO -7 + -8 | import BAR -9 | import bar + 1 + import glob + 2 + import os + 3 + import shutil + 4 + import tempfile + 5 + import time + 6 + from subprocess import PIPE, Popen, STDOUT + 7 + + 8 + import BAR + 9 + import bar 10 + import FOO 11 + import foo 12 + import StringIO diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_classes.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_classes.py.snap index 6c6d57a9e0fb3..77e5c1dab54b6 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_classes.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_classes.py.snap @@ -11,12 +11,8 @@ I001 [*] Import block is un-sorted or un-formatted | |_____________________________________________^ help: Organize imports | - - from sklearn.svm import func, SVC, CONST, Klass - - from subprocess import N_CLASS, PIPE, Popen, STDOUT - - from module import CLASS, Class, CONSTANT, function, BASIC, Apple - - from torch.nn import SELU, AClass, A_CONSTANT 1 + from subprocess import N_CLASS, PIPE, STDOUT, Popen -2 + +2 + 3 + from module import BASIC, CLASS, CONSTANT, Apple, Class, function 4 + from sklearn.svm import CONST, SVC, Klass, func 5 + from torch.nn import A_CONSTANT, SELU, AClass diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_classes_order_by_type_with_custom_classes.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_classes_order_by_type_with_custom_classes.py.snap index 13bfb34aeacdd..f4fd79d7481ac 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_classes_order_by_type_with_custom_classes.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_classes_order_by_type_with_custom_classes.py.snap @@ -11,12 +11,8 @@ I001 [*] Import block is un-sorted or un-formatted | |_____________________________________________^ help: Organize imports | - - from sklearn.svm import func, SVC, CONST, Klass - - from subprocess import N_CLASS, PIPE, Popen, STDOUT - - from module import CLASS, Class, CONSTANT, function, BASIC, Apple - - from torch.nn import SELU, AClass, A_CONSTANT 1 + from subprocess import PIPE, STDOUT, N_CLASS, Popen -2 + +2 + 3 + from module import BASIC, CONSTANT, Apple, CLASS, Class, function 4 + from sklearn.svm import CONST, Klass, SVC, func 5 + from torch.nn import A_CONSTANT, AClass, SELU diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_constants.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_constants.py.snap index 47c84868ef4a3..fd7e621964c39 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_constants.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_constants.py.snap @@ -9,9 +9,7 @@ I001 [*] Import block is un-sorted or un-formatted | |_______________________________________________________________________________^ help: Organize imports | - - from sklearn.svm import XYZ, func, variable, Const, Klass, constant - - from subprocess import First, var, func, Class, konst, A_constant, Last, STDOUT 1 + from subprocess import STDOUT, A_constant, Class, First, Last, func, konst, var -2 + +2 + 3 + from sklearn.svm import XYZ, Const, Klass, constant, func, variable | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_constants_order_by_type_with_custom_constants.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_constants_order_by_type_with_custom_constants.py.snap index 424e09e48c1ca..0581db14095a7 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_constants_order_by_type_with_custom_constants.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_constants_order_by_type_with_custom_constants.py.snap @@ -9,9 +9,7 @@ I001 [*] Import block is un-sorted or un-formatted | |_______________________________________________________________________________^ help: Organize imports | - - from sklearn.svm import XYZ, func, variable, Const, Klass, constant - - from subprocess import First, var, func, Class, konst, A_constant, Last, STDOUT 1 + from subprocess import A_constant, First, konst, Last, STDOUT, Class, func, var -2 + +2 + 3 + from sklearn.svm import Const, constant, XYZ, Klass, func, variable | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_variables.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_variables.py.snap index 6a5a853dde659..84ebcf0877db3 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_variables.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_variables.py.snap @@ -9,9 +9,7 @@ I001 [*] Import block is un-sorted or un-formatted | |_____________________________________________________________________^ help: Organize imports | - - from sklearn.svm import VAR, Class, MyVar, CONST, abc - - from subprocess import utils, var_ABC, Variable, Klass, CONSTANT, exe 1 + from subprocess import CONSTANT, Klass, Variable, exe, utils, var_ABC -2 + +2 + 3 + from sklearn.svm import CONST, VAR, Class, MyVar, abc | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_variables_order_by_type_with_custom_variables.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_variables_order_by_type_with_custom_variables.py.snap index f14d7b908142f..40674bf471c72 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_variables_order_by_type_with_custom_variables.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_by_type_with_custom_variables_order_by_type_with_custom_variables.py.snap @@ -9,9 +9,7 @@ I001 [*] Import block is un-sorted or un-formatted | |_____________________________________________________________________^ help: Organize imports | - - from sklearn.svm import VAR, Class, MyVar, CONST, abc - - from subprocess import utils, var_ABC, Variable, Klass, CONSTANT, exe 1 + from subprocess import CONSTANT, Klass, exe, utils, var_ABC, Variable -2 + +2 + 3 + from sklearn.svm import CONST, Class, abc, MyVar, VAR | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_relative_imports_by_level.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_relative_imports_by_level.py.snap index 9cea317ea3c4c..e8b90fec4886c 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_relative_imports_by_level.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__order_relative_imports_by_level.py.snap @@ -11,9 +11,8 @@ I001 [*] Import block is un-sorted or un-formatted | |________________^ help: Organize imports | - - from .a import a -1 | from ..a import a -2 | from ..b import a +1 + from ..a import a +2 + from ..b import a 3 + from .a import a -4 | from .b import a +4 + from .b import a | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__preserve_comment_order.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__preserve_comment_order.py.snap index 72714ceb927db..b7ab099049c31 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__preserve_comment_order.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__preserve_comment_order.py.snap @@ -18,11 +18,16 @@ I001 [*] Import block is un-sorted or un-formatted | |__________^ help: Organize imports | -1 + import abc -2 | import io -3 + -4 | # Old MacDonald had a farm, --------------------------------------------------------------------------------- -12 | from errno import EIO - - import abc + 1 + import abc + 2 + import io + 3 + + 4 + # Old MacDonald had a farm, + 5 + # EIEIO + 6 + # And on his farm he had a cow, + 7 + # EIEIO + 8 + # With a moo-moo here and a moo-moo there + 9 + # Here a moo, there a moo, everywhere moo-moo +10 + # Old MacDonald had a farm, +11 + # EIEIO +12 + from errno import EIO | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__preserve_import_star.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__preserve_import_star.py.snap index 775915d45b472..e3a6ec25d9b3a 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__preserve_import_star.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__preserve_import_star.py.snap @@ -13,13 +13,9 @@ I001 [*] Import block is un-sorted or un-formatted | |_________________________^ help: Organize imports | - - from some_other_module import some_class - - from some_other_module import * -1 | # Above - - from some_module import some_class # Aside - - # Above -2 | from some_module import * # Aside -3 + +1 + # Above +2 + from some_module import * # Aside +3 + 4 + # Above 5 + from some_module import some_class # Aside 6 + from some_other_module import * diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__preserve_indentation.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__preserve_indentation.py.snap index 50cfe29752e53..f288f6848ff74 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__preserve_indentation.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__preserve_indentation.py.snap @@ -13,11 +13,8 @@ I001 [*] Import block is un-sorted or un-formatted | help: Organize imports | -1 | if True: 2 + import os -3 | import sys - - import os -4 | else: +3 + import sys | I001 [*] Import block is un-sorted or un-formatted @@ -30,8 +27,6 @@ I001 [*] Import block is un-sorted or un-formatted | |_____________^ help: Organize imports | -4 | else: 5 + import os -6 | import sys - - import os +6 + import sys | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__propagate_inline_comments_propagate_inline_comments.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__propagate_inline_comments_propagate_inline_comments.py.snap index c9c8f7b9de93e..26c7465b39521 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__propagate_inline_comments_propagate_inline_comments.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__propagate_inline_comments_propagate_inline_comments.py.snap @@ -11,8 +11,8 @@ I001 [*] Import block is un-sorted or un-formatted | |_^ help: Organize imports | -2 | a_long_variable_name_that_causes_problems, - - items, -3 | ) +1 + from mypackage.subpackage import ( # long comment that seems to be a problem +2 + a_long_variable_name_that_causes_problems, +3 + ) 4 + from mypackage.subpackage import items # long comment that seems to be a problem | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__reorder_within_section.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__reorder_within_section.py.snap index 296be519a13fb..bcf4d377f8899 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__reorder_within_section.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__reorder_within_section.py.snap @@ -10,6 +10,5 @@ I001 [*] Import block is un-sorted or un-formatted help: Organize imports | 1 + import os -2 | import sys - - import os +2 + import sys | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_comment.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_comment.py.snap index cbd561a21a30a..766e698128bd4 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_comment.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_comment.py.snap @@ -5,6 +5,7 @@ I002 [*] Missing required import: `from __future__ import annotations` --> comment.py:1:1 help: Insert required import: `from __future__ import annotations` | +1 | #!/usr/bin/env python3 2 | 3 + from __future__ import annotations 4 | x = 1 diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_comments_and_newlines.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_comments_and_newlines.py.snap index 5a8ffd125a77c..eb2b0779d2a4d 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_comments_and_newlines.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_comments_and_newlines.py.snap @@ -5,6 +5,8 @@ I002 [*] Missing required import: `from __future__ import annotations` --> comments_and_newlines.py:1:1 help: Insert required import: `from __future__ import annotations` | +3 | +4 | # A linter directive could go here 5 | 6 + from __future__ import annotations 7 | x = 1 diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_docstring.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_docstring.py.snap index dc245b0faa3ec..66d5d3d2bdc78 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_docstring.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_docstring.py.snap @@ -7,5 +7,6 @@ help: Insert required import: `from __future__ import annotations` | 1 | """Hello, world!""" 2 + from __future__ import annotations -3 | +3 + +4 | x = 1 | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_docstring_followed_by_continuation.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_docstring_followed_by_continuation.py.snap index 493240b4bd8b8..c1bf75b7528d1 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_docstring_followed_by_continuation.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_docstring_followed_by_continuation.py.snap @@ -5,6 +5,7 @@ I002 [*] Missing required import: `from __future__ import annotations` --> docstring_followed_by_continuation.py:1:1 help: Insert required import: `from __future__ import annotations` | +1 | """Hello, world!"""\ 2 | 3 + from __future__ import annotations 4 | x = 1; y = 2 diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_docstring_with_continuation.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_docstring_with_continuation.py.snap index 7446eb22a9d40..8b7425ec3d279 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_docstring_with_continuation.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_docstring_with_continuation.py.snap @@ -5,7 +5,6 @@ I002 [*] Missing required import: `from __future__ import annotations` --> docstring_with_continuation.py:1:1 help: Insert required import: `from __future__ import annotations` | - - """Hello, world!"""; x = \ -1 + """Hello, world!"""; from __future__ import annotations; x = \ +1 ~ """Hello, world!"""; from __future__ import annotations; x = \ 2 | 1; y = 2 | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_docstring_with_multiple_continuations.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_docstring_with_multiple_continuations.py.snap index fed47f70086fe..716802f778081 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_docstring_with_multiple_continuations.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_docstring_with_multiple_continuations.py.snap @@ -5,6 +5,8 @@ I002 [*] Missing required import: `from __future__ import annotations` --> docstring_with_multiple_continuations.py:1:1 help: Insert required import: `from __future__ import annotations` | +1 | """Hello, world!"""\ +2 | \ 3 | 4 + from __future__ import annotations 5 | x = 1; y = 2 diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_docstring_with_semicolon.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_docstring_with_semicolon.py.snap index 953bf61d5cea0..09ff8fccf8cfb 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_docstring_with_semicolon.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_docstring_with_semicolon.py.snap @@ -5,6 +5,5 @@ I002 [*] Missing required import: `from __future__ import annotations` --> docstring_with_semicolon.py:1:1 help: Insert required import: `from __future__ import annotations` | - - """Hello, world!"""; x = 1 -1 + """Hello, world!"""; from __future__ import annotations; x = 1 - | +1 | """Hello, world!"""; from __future__ import annotations; x = 1 + | +++++++++++++++++++++++++++++++++++ diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_multiline_docstring.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_multiline_docstring.py.snap index 42b61ec4fd7a4..68f6645ba519e 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_multiline_docstring.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_multiline_docstring.py.snap @@ -5,6 +5,8 @@ I002 [*] Missing required import: `from __future__ import annotations` --> multiline_docstring.py:1:1 help: Insert required import: `from __future__ import annotations` | +1 | """a +2 | b""" 3 | # b 4 + from __future__ import annotations 5 | import os diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_off.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_off.py.snap index 4ca427ea70767..6295692a95229 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_off.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_off.py.snap @@ -5,7 +5,9 @@ I002 [*] Missing required import: `from __future__ import annotations` --> off.py:1:1 help: Insert required import: `from __future__ import annotations` | +1 | # isort: off 2 | 3 + from __future__ import annotations 4 | x = 1 +5 | # isort: on | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_unused.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_unused.py.snap index 647a31e56e459..779262ed32252 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_unused.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_unused.py.snap @@ -12,9 +12,7 @@ F401 [*] `sys` imported but unused | help: Remove unused import: `sys` | -4 | # Unused, _not_ marked as required. - - import sys -5 | +5 - import sys | F401 [*] `pathlib` imported but unused @@ -28,7 +26,5 @@ F401 [*] `pathlib` imported but unused | help: Remove unused import: `pathlib` | -7 | # Unused, _not_ marked as required (due to the alias). - - import pathlib as non_alias -8 | +8 - import pathlib as non_alias | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_whitespace.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_whitespace.py.snap index b727b87185e0d..37cb28b393795 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_whitespace.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_whitespace.py.snap @@ -5,8 +5,9 @@ I002 [*] Missing required import: `from __future__ import annotations` --> whitespace.py:1:1 help: Insert required import: `from __future__ import annotations` | +1 | # This is a regression test for https://github.com/astral-sh/ruff/issues/19310 2 | # there is a (potentially invisible) unicode formfeed character (000C) between "docstring" and the semicolon - - "docstring" ; print( -3 + "docstring" ; from __future__ import annotations; print( +3 ~ "docstring"␌; from __future__ import annotations; print( 4 | f"{__doc__=}", +5 | ) | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_comment.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_comment.py.snap index 5fa6ed07ba8b9..1f880b3f3d32e 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_comment.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_comment.py.snap @@ -5,6 +5,7 @@ I002 [*] Missing required import: `from __future__ import annotations as _annota --> comment.py:1:1 help: Insert required import: `from __future__ import annotations as _annotations` | +1 | #!/usr/bin/env python3 2 | 3 + from __future__ import annotations as _annotations 4 | x = 1 diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_comments_and_newlines.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_comments_and_newlines.py.snap index aaac3f2ae65e7..6f78fdaf5b088 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_comments_and_newlines.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_comments_and_newlines.py.snap @@ -5,6 +5,8 @@ I002 [*] Missing required import: `from __future__ import annotations as _annota --> comments_and_newlines.py:1:1 help: Insert required import: `from __future__ import annotations as _annotations` | +3 | +4 | # A linter directive could go here 5 | 6 + from __future__ import annotations as _annotations 7 | x = 1 diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_docstring.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_docstring.py.snap index b22a521fa5a1a..0a72cd4850e6b 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_docstring.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_docstring.py.snap @@ -7,5 +7,6 @@ help: Insert required import: `from __future__ import annotations as _annotation | 1 | """Hello, world!""" 2 + from __future__ import annotations as _annotations -3 | +3 + +4 | x = 1 | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_docstring_followed_by_continuation.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_docstring_followed_by_continuation.py.snap index 4dc7ebc32d582..baf3ca2ef6f7d 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_docstring_followed_by_continuation.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_docstring_followed_by_continuation.py.snap @@ -5,6 +5,7 @@ I002 [*] Missing required import: `from __future__ import annotations as _annota --> docstring_followed_by_continuation.py:1:1 help: Insert required import: `from __future__ import annotations as _annotations` | +1 | """Hello, world!"""\ 2 | 3 + from __future__ import annotations as _annotations 4 | x = 1; y = 2 diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_docstring_with_continuation.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_docstring_with_continuation.py.snap index a4012a3425613..5ba602228e61b 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_docstring_with_continuation.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_docstring_with_continuation.py.snap @@ -5,7 +5,6 @@ I002 [*] Missing required import: `from __future__ import annotations as _annota --> docstring_with_continuation.py:1:1 help: Insert required import: `from __future__ import annotations as _annotations` | - - """Hello, world!"""; x = \ -1 + """Hello, world!"""; from __future__ import annotations as _annotations; x = \ +1 ~ """Hello, world!"""; from __future__ import annotations as _annotations; x = \ 2 | 1; y = 2 | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_docstring_with_multiple_continuations.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_docstring_with_multiple_continuations.py.snap index 6bf1ea8c9da9f..579df5a47b872 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_docstring_with_multiple_continuations.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_docstring_with_multiple_continuations.py.snap @@ -5,6 +5,8 @@ I002 [*] Missing required import: `from __future__ import annotations as _annota --> docstring_with_multiple_continuations.py:1:1 help: Insert required import: `from __future__ import annotations as _annotations` | +1 | """Hello, world!"""\ +2 | \ 3 | 4 + from __future__ import annotations as _annotations 5 | x = 1; y = 2 diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_docstring_with_semicolon.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_docstring_with_semicolon.py.snap index 14efbb4d4c826..47b4e06236cf0 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_docstring_with_semicolon.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_docstring_with_semicolon.py.snap @@ -5,6 +5,5 @@ I002 [*] Missing required import: `from __future__ import annotations as _annota --> docstring_with_semicolon.py:1:1 help: Insert required import: `from __future__ import annotations as _annotations` | - - """Hello, world!"""; x = 1 -1 + """Hello, world!"""; from __future__ import annotations as _annotations; x = 1 - | +1 | """Hello, world!"""; from __future__ import annotations as _annotations; x = 1 + | +++++++++++++++++++++++++++++++++++++++++++++++++++ diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_multiline_docstring.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_multiline_docstring.py.snap index 7b0a8040e2a9f..f5fc892125f94 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_multiline_docstring.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_multiline_docstring.py.snap @@ -5,6 +5,8 @@ I002 [*] Missing required import: `from __future__ import annotations as _annota --> multiline_docstring.py:1:1 help: Insert required import: `from __future__ import annotations as _annotations` | +1 | """a +2 | b""" 3 | # b 4 + from __future__ import annotations as _annotations 5 | import os diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_off.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_off.py.snap index 151a67708d445..2514f6a717ef9 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_off.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_alias_off.py.snap @@ -5,7 +5,9 @@ I002 [*] Missing required import: `from __future__ import annotations as _annota --> off.py:1:1 help: Insert required import: `from __future__ import annotations as _annotations` | +1 | # isort: off 2 | 3 + from __future__ import annotations as _annotations 4 | x = 1 +5 | # isort: on | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_future_import_docstring_future_import.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_future_import_docstring_future_import.py.snap index 3924a830c7e28..17cb1e3678f37 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_future_import_docstring_future_import.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_import_with_future_import_docstring_future_import.py.snap @@ -5,6 +5,7 @@ I002 [*] Missing required import: `import this` --> docstring_future_import.py:1:1 help: Insert required import: `import this` | +1 | "a docstring" 2 | from __future__ import annotations 3 + import this 4 | # EOF diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_imports_docstring.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_imports_docstring.py.snap index 4411e6a48222e..7d781ae7dcaad 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_imports_docstring.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_imports_docstring.py.snap @@ -7,7 +7,8 @@ help: Insert required import: `from __future__ import generator_stop` | 1 | """Hello, world!""" 2 + from __future__ import generator_stop -3 | +3 + +4 | x = 1 | I002 [*] Missing required import: `from __future__ import annotations` @@ -16,5 +17,6 @@ help: Insert required import: `from __future__ import annotations` | 1 | """Hello, world!""" 2 + from __future__ import annotations -3 | +3 + +4 | x = 1 | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_imports_multiple_strings.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_imports_multiple_strings.py.snap index 8a70014673aea..780feb16be657 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_imports_multiple_strings.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__required_imports_multiple_strings.py.snap @@ -8,6 +8,9 @@ help: Insert required import: `from __future__ import generator_stop` 1 | """This is a docstring.""" 2 + from __future__ import generator_stop 3 | "This is not a docstring." +4 | "This is also not a docstring." +5 | +6 | x = 1 | I002 [*] Missing required import: `from __future__ import annotations` @@ -17,4 +20,7 @@ help: Insert required import: `from __future__ import annotations` 1 | """This is a docstring.""" 2 + from __future__ import annotations 3 | "This is not a docstring." +4 | "This is also not a docstring." +5 | +6 | x = 1 | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__section_order_sections.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__section_order_sections.py.snap index e8e384d0cff83..39ff75dc39cfb 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__section_order_sections.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__section_order_sections.py.snap @@ -14,16 +14,16 @@ I001 [*] Import block is un-sorted or un-formatted | |___________________^ help: Organize imports | -1 | from __future__ import annotations -2 + -3 | import os -4 | import sys -5 + -6 | import pytz -7 + -8 | import django.settings -9 + -10 | from library import foo -11 + -12 | from . import local + 1 + from __future__ import annotations + 2 + + 3 + import os + 4 + import sys + 5 + + 6 + import pytz + 7 + + 8 + import django.settings + 9 + +10 + from library import foo +11 + +12 + from . import local | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__sections_main_first_party.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__sections_main_first_party.py.snap index b942eecab3a0f..8e1c6dacb805c 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__sections_main_first_party.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__sections_main_first_party.py.snap @@ -16,10 +16,10 @@ I001 [*] Import block is un-sorted or un-formatted | help: Organize imports | -2 | - - import __main__ -3 | import third_party -4 | +1 + import os +2 + +3 + import third_party +4 + 5 + import __main__ -6 | import first_party +6 + import first_party | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__sections_sections.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__sections_sections.py.snap index 6d24a6547eb1e..91b1b8a026e4a 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__sections_sections.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__sections_sections.py.snap @@ -14,16 +14,15 @@ I001 [*] Import block is un-sorted or un-formatted | |___________________^ help: Organize imports | -1 | from __future__ import annotations -2 + -3 | import os -4 | import sys -5 + -6 | import pytz - - import django.settings -7 | from library import foo -8 + -9 | from . import local -10 + + 1 + from __future__ import annotations + 2 + + 3 + import os + 4 + import sys + 5 + + 6 + import pytz + 7 + from library import foo + 8 + + 9 + from . import local +10 + 11 + import django.settings | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__separate_first_party_imports.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__separate_first_party_imports.py.snap index 2999a9b2cb438..e6cd4164175d4 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__separate_first_party_imports.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__separate_first_party_imports.py.snap @@ -13,12 +13,10 @@ I001 [*] Import block is un-sorted or un-formatted help: Organize imports | 1 + import os -2 | import sys -3 + +2 + import sys +3 + 4 + import numpy as np -5 + -6 | import leading_prefix - - import numpy as np - - import os -7 | from leading_prefix import Class +5 + +6 + import leading_prefix +7 + from leading_prefix import Class | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__separate_future_imports.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__separate_future_imports.py.snap index 1c9049487b7ad..3ab70a26f1b06 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__separate_future_imports.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__separate_future_imports.py.snap @@ -10,10 +10,8 @@ I001 [*] Import block is un-sorted or un-formatted | |__________________________________^ help: Organize imports | - - import sys - - import os -1 | from __future__ import annotations -2 + +1 + from __future__ import annotations +2 + 3 + import os 4 + import sys | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__separate_local_folder_imports.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__separate_local_folder_imports.py.snap index 62e21c5a6659e..ce37e0b8eee2f 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__separate_local_folder_imports.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__separate_local_folder_imports.py.snap @@ -14,17 +14,14 @@ I001 [*] Import block is un-sorted or un-formatted | |______________________^ help: Organize imports | -1 + import os -2 | import sys -3 + -4 | import ruff -5 + from ruff import check -6 + -7 | import leading_prefix - - import os -8 + -9 + from .. import trailing_prefix -10 | from . import leading_prefix - - from .. import trailing_prefix - - from ruff import check + 1 + import os + 2 + import sys + 3 + + 4 + import ruff + 5 + from ruff import check + 6 + + 7 + import leading_prefix + 8 + + 9 + from .. import trailing_prefix +10 + from . import leading_prefix | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__separate_third_party_imports.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__separate_third_party_imports.py.snap index f931ab534b9b2..410fa343e9f21 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__separate_third_party_imports.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__separate_third_party_imports.py.snap @@ -11,11 +11,9 @@ I001 [*] Import block is un-sorted or un-formatted | |_________^ help: Organize imports | - - import pandas as pd 1 + import os -2 | import sys -3 + -4 | import numpy as np - - import os +2 + import sys +3 + +4 + import numpy as np 5 + import pandas as pd | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__skip.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__skip.py.snap index 6f8bc5b4db8a1..3ceadc44b44e4 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__skip.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__skip.py.snap @@ -11,11 +11,8 @@ I001 [*] Import block is un-sorted or un-formatted | |______________^ help: Organize imports | -19 | import os # isort: skip 20 + import abc -21 | import collections - - import abc -22 | +21 + import collections | I001 [*] Import block is un-sorted or un-formatted @@ -28,11 +25,8 @@ I001 [*] Import block is un-sorted or un-formatted | |______________^ help: Organize imports | -26 | import os # isort:skip 27 + import abc -28 | import collections - - import abc -29 | +28 + import collections | I001 [*] Import block is un-sorted or un-formatted @@ -44,8 +38,6 @@ I001 [*] Import block is un-sorted or un-formatted | ^^^^^^^^^^^^^^^^^^^^^ help: Organize imports | -33 | import sys; import os # isort:skip # isort:skip - - import sys; import os 34 + import os 35 + import sys | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__sort_similar_imports.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__sort_similar_imports.py.snap index 6964d1f719664..2432411835543 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__sort_similar_imports.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__sort_similar_imports.py.snap @@ -33,44 +33,26 @@ I001 [*] Import block is un-sorted or un-formatted | |_____________^ help: Organize imports | - - from a import b -1 + import A -2 + import a -3 + import B -4 + import b -5 + import x -6 + import x as A -7 + import x as Y -8 + import x as a -9 + import x as y -10 | from a import BAD as DEF - - from a import B - - from a import Boo as DEF + 1 + import A + 2 + import a + 3 + import B + 4 + import b + 5 + import x + 6 + import x as A + 7 + import x as Y + 8 + import x as a + 9 + import x as y +10 + from a import BAD as DEF 11 + from a import B, b 12 + from a import B as A -13 | from a import B as Abc - - from a import B as A -14 | from a import B as DEF +13 + from a import B as Abc +14 + from a import B as DEF 15 + from a import Boo as DEF -16 | from a import b as a - - from a import b as x -17 | from a import b as c - - from b import c -18 | from a import b as d +16 + from a import b as a +17 + from a import b as c +18 + from a import b as d 19 + from a import b as x -20 | from a import b as y - - from b import C +20 + from a import b as y 21 + from b import C, c -22 | from b import c as d - - - - import A - - import a - - import b - - import B - - - - import x as y - - import x as A - - import x as Y - - import x - - import x as a +22 + from b import c as d | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__split.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__split.py.snap index 65bd1fcdf646e..476bca1c270a0 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__split.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__split.py.snap @@ -13,11 +13,8 @@ I001 [*] Import block is un-sorted or un-formatted | help: Organize imports | -14 | if True: 15 + import A -16 | import C - - import A -17 | +16 + import C | I001 [*] Import block is un-sorted or un-formatted @@ -30,11 +27,8 @@ I001 [*] Import block is un-sorted or un-formatted | |____________^ help: Organize imports | -19 | 20 + import B -21 | import D - - import B -22 | +21 + import D | I001 [*] Import block is un-sorted or un-formatted @@ -47,8 +41,6 @@ I001 [*] Import block is un-sorted or un-formatted | |________^ help: Organize imports | -29 | 30 + import c -31 | import d - - import c +31 + import d | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__split_on_trailing_comma_magic_trailing_comma.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__split_on_trailing_comma_magic_trailing_comma.py.snap index 2d3ec8531f519..a1c3dda439fa3 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__split_on_trailing_comma_magic_trailing_comma.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__split_on_trailing_comma_magic_trailing_comma.py.snap @@ -45,50 +45,22 @@ I001 [*] Import block is un-sorted or un-formatted | |_^ help: Organize imports | -1 | # This has a magic trailing comma, will be sorted, but not rolled into one line - - from sys import ( - - stderr, - - argv, - - stdout, - - exit, - - ) - - - - # No magic comma, this will be rolled into one line. - - from os import ( - - path, - - environ, - - execl, - - execv - - ) - - -2 | from glob import ( -3 + escape, # Ends with a comment, should still treat as magic trailing comma. -4 | glob, -5 | iglob, - - escape, # Ends with a comment, should still treat as magic trailing comma. -6 | ) -7 | -8 + # No magic comma, this will be rolled into one line. -9 + from os import environ, execl, execv, path + 2 + from glob import ( + 3 + escape, # Ends with a comment, should still treat as magic trailing comma. + 4 + glob, + 5 + iglob, + 6 + ) + 7 + + 8 + # No magic comma, this will be rolled into one line. + 9 + from os import environ, execl, execv, path 10 + from sys import argv, exit, stderr, stdout -11 + -12 | # These will be combined, but without a trailing comma. - - from foo import bar - - from foo import baz +11 + +12 + # These will be combined, but without a trailing comma. 13 + from foo import bar, baz -14 | -15 | # These will be combined, _with_ a trailing comma. - - from module1 import member1 - - from module1 import ( - - member2, - - member3, - - ) +14 + +15 + # These will be combined, _with_ a trailing comma. 16 + from module1 import member1, member2, member3 -17 | -18 | # These will be combined, _with_ a trailing comma. - - from module2 import member1, member2 - - from module2 import ( - - member3, - - ) +17 + +18 + # These will be combined, _with_ a trailing comma. 19 + from module2 import member1, member2, member3 | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__star_before_others.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__star_before_others.py.snap index 109bbf659730a..bd9f964cc35f1 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__star_before_others.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__star_before_others.py.snap @@ -10,8 +10,7 @@ I001 [*] Import block is un-sorted or un-formatted | |_______________________^ help: Organize imports | -1 | from .logging import config_logging +1 + from .logging import config_logging 2 + from .settings import * -3 | from .settings import ENV - - from .settings import * +3 + from .settings import ENV | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__straight_required_import_docstring.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__straight_required_import_docstring.py.snap index e8350f74f43aa..7d44ece516b92 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__straight_required_import_docstring.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__straight_required_import_docstring.py.snap @@ -7,5 +7,6 @@ help: Insert required import: `import os` | 1 | """Hello, world!""" 2 + import os -3 | +3 + +4 | x = 1 | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__straight_required_import_docstring.pyi.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__straight_required_import_docstring.pyi.snap index 4a69fb26894f7..cc8d770d20874 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__straight_required_import_docstring.pyi.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__straight_required_import_docstring.pyi.snap @@ -7,5 +7,6 @@ help: Insert required import: `import os` | 1 | """Hello, world!""" 2 + import os -3 | +3 + +4 | x = 1 | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__trailing_comment.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__trailing_comment.py.snap index b28c3f020d2c8..644fa1988fd58 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__trailing_comment.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__trailing_comment.py.snap @@ -18,16 +18,11 @@ I001 [*] Import block is un-sorted or un-formatted | help: Organize imports | -7 | -8 + from foo import bar # some comment -9 | from mylib import ( -10 | MyClient, -11 | MyMgmtClient, - - ); from foo import ( - - bar - - )# some comment + 8 + from foo import bar # some comment + 9 + from mylib import ( +10 + MyClient, +11 + MyMgmtClient, 12 + ) -13 | | I001 [*] Import block is un-sorted or un-formatted @@ -49,12 +44,12 @@ I001 [*] Import block is un-sorted or un-formatted | help: Organize imports | -16 | - - from foo import ( - - bar - - ) 17 + from foo import bar -18 | from mylib import ( +18 + from mylib import ( +19 + MyClient, +20 + MyMgmtClient, +21 + # some comment +22 + ) | I001 [*] Import block is un-sorted or un-formatted @@ -72,13 +67,13 @@ I001 [*] Import block is un-sorted or un-formatted | help: Organize imports | -34 | - - from mylib import ( - - MyClient - - # some comment - - ) +35 - from mylib import ( +36 - MyClient +37 - # some comment +38 - ) +39 - +40 - pass 35 + from mylib import MyClient # some comment -36 | | I001 [*] Import block is un-sorted or un-formatted @@ -96,13 +91,13 @@ I001 [*] Import block is un-sorted or un-formatted | help: Organize imports | -41 | - - from mylib import ( - - # some comment - - MyClient - - ) +42 - from mylib import ( +43 - # some comment +44 - MyClient +45 - ) +46 - +47 - pass 42 + from mylib import MyClient # some comment -43 | | I001 [*] Import block is un-sorted or un-formatted @@ -117,11 +112,10 @@ I001 [*] Import block is un-sorted or un-formatted | |_^ help: Organize imports | -49 | # a - - from mylib import ( # b - - # c - - MyClient # d - - # e - - ) # f +50 - from mylib import ( # b +51 - # c +52 - MyClient # d +53 - # e +54 - ) # f 50 + from mylib import MyClient # b # c # d # e # f | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__two_space.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__two_space.py.snap index 3f7c84ce74c8b..eef499a475503 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__two_space.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__two_space.py.snap @@ -18,13 +18,11 @@ I001 [*] Import block is un-sorted or un-formatted | help: Organize imports | -2 | from math import ( - - sin, - - tan, -3 | cos, -4 | nan, -5 | pi, +2 + from math import ( +3 + cos, +4 + nan, +5 + pi, 6 + sin, 7 + tan, -8 | ) +8 + ) | diff --git a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__unicode.py.snap b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__unicode.py.snap index 7821e0b83a881..62e3c23c89666 100644 --- a/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__unicode.py.snap +++ b/crates/ruff_linter/src/rules/isort/snapshots/ruff_linter__rules__isort__tests__unicode.py.snap @@ -14,11 +14,8 @@ I001 [*] Import block is un-sorted or un-formatted | help: Organize imports | -1 + import numpy as CƐgHHHhIILlNZΩZKÅBCeEFio -2 + import numpy as ℂℇℊℋℌℍℎℐℑℒℓℕℤΩℨKÅℬℭℯℰℱℹℴ -3 | from astropy.constants import hbar as ℏ -4 | from numpy import pi as π - - import numpy as ℂℇℊℋℌℍℎℐℑℒℓℕℤΩℨKÅℬℭℯℰℱℹℴ - - import numpy as CƐgHHHhIILlNZΩZKÅBCeEFio -5 | +1 ~ import numpy as CƐgHHHhIILlNZΩZKÅBCeEFio +2 ~ import numpy as ℂℇℊℋℌℍℎℐℑℒℓℕℤΩℨKÅℬℭℯℰℱℹℴ +3 ~ from astropy.constants import hbar as ℏ +4 ~ from numpy import pi as π | diff --git a/crates/ruff_linter/src/rules/numpy/snapshots/ruff_linter__rules__numpy__tests__numpy-deprecated-function_NPY003.py.snap b/crates/ruff_linter/src/rules/numpy/snapshots/ruff_linter__rules__numpy__tests__numpy-deprecated-function_NPY003.py.snap index 1a7b461cdfd0d..865d0c55f7969 100644 --- a/crates/ruff_linter/src/rules/numpy/snapshots/ruff_linter__rules__numpy__tests__numpy-deprecated-function_NPY003.py.snap +++ b/crates/ruff_linter/src/rules/numpy/snapshots/ruff_linter__rules__numpy__tests__numpy-deprecated-function_NPY003.py.snap @@ -13,10 +13,9 @@ NPY003 [*] `np.round_` is deprecated; use `np.round` instead | help: Replace with `np.round` | +2 ~ import numpy as np 3 | - - np.round_(np.random.rand(5, 5), 2) -4 + np.round(np.random.rand(5, 5), 2) -5 | np.product(np.random.rand(5, 5)) +4 ~ np.round(np.random.rand(5, 5), 2) | NPY003 [*] `np.product` is deprecated; use `np.prod` instead @@ -30,10 +29,10 @@ NPY003 [*] `np.product` is deprecated; use `np.prod` instead | help: Replace with `np.prod` | +2 ~ import numpy as np +3 | 4 | np.round_(np.random.rand(5, 5), 2) - - np.product(np.random.rand(5, 5)) -5 + np.prod(np.random.rand(5, 5)) -6 | np.cumproduct(np.random.rand(5, 5)) +5 ~ np.prod(np.random.rand(5, 5)) | NPY003 [*] `np.cumproduct` is deprecated; use `np.cumprod` instead @@ -48,10 +47,11 @@ NPY003 [*] `np.cumproduct` is deprecated; use `np.cumprod` instead | help: Replace with `np.cumprod` | +2 ~ import numpy as np +3 | +4 | np.round_(np.random.rand(5, 5), 2) 5 | np.product(np.random.rand(5, 5)) - - np.cumproduct(np.random.rand(5, 5)) -6 + np.cumprod(np.random.rand(5, 5)) -7 | np.sometrue(np.random.rand(5, 5)) +6 ~ np.cumprod(np.random.rand(5, 5)) | NPY003 [*] `np.sometrue` is deprecated; use `np.any` instead @@ -65,10 +65,11 @@ NPY003 [*] `np.sometrue` is deprecated; use `np.any` instead | help: Replace with `np.any` | +2 ~ import numpy as np +3 | +… 6 | np.cumproduct(np.random.rand(5, 5)) - - np.sometrue(np.random.rand(5, 5)) -7 + np.any(np.random.rand(5, 5)) -8 | np.alltrue(np.random.rand(5, 5)) +7 ~ np.any(np.random.rand(5, 5)) | NPY003 [*] `np.alltrue` is deprecated; use `np.all` instead @@ -80,10 +81,11 @@ NPY003 [*] `np.alltrue` is deprecated; use `np.all` instead | ^^^^^^^^^^ help: Replace with `np.all` | +2 ~ import numpy as np +3 | +… 7 | np.sometrue(np.random.rand(5, 5)) - - np.alltrue(np.random.rand(5, 5)) -8 + np.all(np.random.rand(5, 5)) -9 | +8 ~ np.all(np.random.rand(5, 5)) | NPY003 [*] `np.round_` is deprecated; use `np.round` instead @@ -98,13 +100,12 @@ NPY003 [*] `np.round_` is deprecated; use `np.round` instead | help: Replace with `np.round` | -1 + from numpy import round -2 | def func(): --------------------------------------------------------------------------------- + 1 + from numpy import round + 2 | def func(): + 3 | import numpy as np + … 14 | - - round_(np.random.rand(5, 5), 2) -15 + round(np.random.rand(5, 5), 2) -16 | product(np.random.rand(5, 5)) +15 ~ round(np.random.rand(5, 5), 2) | NPY003 [*] `np.product` is deprecated; use `np.prod` instead @@ -118,13 +119,12 @@ NPY003 [*] `np.product` is deprecated; use `np.prod` instead | help: Replace with `np.prod` | -1 + from numpy import prod -2 | def func(): --------------------------------------------------------------------------------- + 1 + from numpy import prod + 2 | def func(): + 3 | import numpy as np + … 15 | round_(np.random.rand(5, 5), 2) - - product(np.random.rand(5, 5)) -16 + prod(np.random.rand(5, 5)) -17 | cumproduct(np.random.rand(5, 5)) +16 ~ prod(np.random.rand(5, 5)) | NPY003 [*] `np.cumproduct` is deprecated; use `np.cumprod` instead @@ -139,13 +139,12 @@ NPY003 [*] `np.cumproduct` is deprecated; use `np.cumprod` instead | help: Replace with `np.cumprod` | -1 + from numpy import cumprod -2 | def func(): --------------------------------------------------------------------------------- + 1 + from numpy import cumprod + 2 | def func(): + 3 | import numpy as np + … 16 | product(np.random.rand(5, 5)) - - cumproduct(np.random.rand(5, 5)) -17 + cumprod(np.random.rand(5, 5)) -18 | sometrue(np.random.rand(5, 5)) +17 ~ cumprod(np.random.rand(5, 5)) | NPY003 [*] `np.sometrue` is deprecated; use `np.any` instead @@ -159,13 +158,12 @@ NPY003 [*] `np.sometrue` is deprecated; use `np.any` instead | help: Replace with `np.any` | -1 + from numpy import any -2 | def func(): --------------------------------------------------------------------------------- + 1 + from numpy import any + 2 | def func(): + 3 | import numpy as np + … 17 | cumproduct(np.random.rand(5, 5)) - - sometrue(np.random.rand(5, 5)) -18 + any(np.random.rand(5, 5)) -19 | alltrue(np.random.rand(5, 5)) +18 ~ any(np.random.rand(5, 5)) | NPY003 [*] `np.alltrue` is deprecated; use `np.all` instead @@ -177,10 +175,10 @@ NPY003 [*] `np.alltrue` is deprecated; use `np.all` instead | ^^^^^^^ help: Replace with `np.all` | -1 + from numpy import all -2 | def func(): --------------------------------------------------------------------------------- + 1 + from numpy import all + 2 | def func(): + 3 | import numpy as np + … 18 | sometrue(np.random.rand(5, 5)) - - alltrue(np.random.rand(5, 5)) -19 + all(np.random.rand(5, 5)) +19 ~ all(np.random.rand(5, 5)) | diff --git a/crates/ruff_linter/src/rules/numpy/snapshots/ruff_linter__rules__numpy__tests__numpy-deprecated-type-alias_NPY001.py.snap b/crates/ruff_linter/src/rules/numpy/snapshots/ruff_linter__rules__numpy__tests__numpy-deprecated-type-alias_NPY001.py.snap index e215442bc4aad..dfca243fe5f23 100644 --- a/crates/ruff_linter/src/rules/numpy/snapshots/ruff_linter__rules__numpy__tests__numpy-deprecated-type-alias_NPY001.py.snap +++ b/crates/ruff_linter/src/rules/numpy/snapshots/ruff_linter__rules__numpy__tests__numpy-deprecated-type-alias_NPY001.py.snap @@ -11,10 +11,8 @@ NPY001 [*] Type alias `np.float` is deprecated, replace with builtin type | help: Replace `np.float` with builtin type | -5 | # Error - - npy.float +6 - npy.float 6 + float -7 | npy.int | NPY001 [*] Type alias `np.int` is deprecated, replace with builtin type @@ -29,10 +27,8 @@ NPY001 [*] Type alias `np.int` is deprecated, replace with builtin type | help: Replace `np.int` with builtin type | -6 | npy.float - - npy.int +7 - npy.int 7 + int -8 | | NPY001 [*] Type alias `np.object` is deprecated, replace with builtin type @@ -45,12 +41,10 @@ NPY001 [*] Type alias `np.object` is deprecated, replace with builtin type 10 | ... | help: Replace `np.object` with builtin type - | -8 | - - if dtype == np.object: -9 + if dtype == object: -10 | ... - | + | +9 - if dtype == np.object: +9 + if dtype == object: + | NPY001 [*] Type alias `np.int` is deprecated, replace with builtin type --> NPY001.py:12:72 @@ -64,10 +58,8 @@ NPY001 [*] Type alias `np.int` is deprecated, replace with builtin type | help: Replace `np.int` with builtin type | -11 | - - result = result.select_dtypes([np.byte, np.ubyte, np.short, np.ushort, np.int, np.complex]) +12 - result = result.select_dtypes([np.byte, np.ubyte, np.short, np.ushort, np.int, np.complex]) 12 + result = result.select_dtypes([np.byte, np.ubyte, np.short, np.ushort, int, np.complex]) -13 | | NPY001 [*] Type alias `np.complex` is deprecated, replace with builtin type @@ -82,10 +74,8 @@ NPY001 [*] Type alias `np.complex` is deprecated, replace with builtin type | help: Replace `np.complex` with builtin type | -11 | - - result = result.select_dtypes([np.byte, np.ubyte, np.short, np.ushort, np.int, np.complex]) +12 - result = result.select_dtypes([np.byte, np.ubyte, np.short, np.ushort, np.int, np.complex]) 12 + result = result.select_dtypes([np.byte, np.ubyte, np.short, np.ushort, np.int, complex]) -13 | | NPY001 [*] Type alias `np.object` is deprecated, replace with builtin type @@ -99,10 +89,8 @@ NPY001 [*] Type alias `np.object` is deprecated, replace with builtin type | help: Replace `np.object` with builtin type | -16 | columns=["a", "b", "c"], - - dtype=numpy.object, +17 - dtype=numpy.object, 17 + dtype=object, -18 | ) | NPY001 [*] Type alias `np.int` is deprecated, replace with builtin type @@ -117,10 +105,8 @@ NPY001 [*] Type alias `np.int` is deprecated, replace with builtin type | help: Replace `np.int` with builtin type | -19 | - - _ = arr.astype(np.int) +20 - _ = arr.astype(np.int) 20 + _ = arr.astype(int) -21 | | NPY001 [*] Type alias `np.float` is deprecated, replace with builtin type @@ -132,9 +118,7 @@ NPY001 [*] Type alias `np.float` is deprecated, replace with builtin type | ^^^^^ help: Replace `np.float` with builtin type | -23 | from numpy import float 24 + import builtins -25 | - - float(1) -26 + builtins.float(1) +25 + +26 ~ builtins.float(1) | diff --git a/crates/ruff_linter/src/rules/numpy/snapshots/ruff_linter__rules__numpy__tests__numpy2-deprecation_NPY201.py.snap b/crates/ruff_linter/src/rules/numpy/snapshots/ruff_linter__rules__numpy__tests__numpy2-deprecation_NPY201.py.snap index 515d21052ab61..81f29b1cc6536 100644 --- a/crates/ruff_linter/src/rules/numpy/snapshots/ruff_linter__rules__numpy__tests__numpy2-deprecation_NPY201.py.snap +++ b/crates/ruff_linter/src/rules/numpy/snapshots/ruff_linter__rules__numpy__tests__numpy2-deprecation_NPY201.py.snap @@ -17,9 +17,7 @@ help: Replace with `numpy.lib.add_docstring` 2 | def func(): 3 | import numpy as np 4 | - - np.add_docstring -5 + add_docstring -6 | +5 ~ add_docstring | NPY201 [*] `np.add_newdoc` will be removed in NumPy 2.0. Use `numpy.lib.add_newdoc` instead. @@ -36,11 +34,10 @@ help: Replace with `numpy.lib.add_newdoc` | 1 + from numpy.lib import add_newdoc 2 | def func(): --------------------------------------------------------------------------------- +3 | import numpy as np +… 6 | - - np.add_newdoc -7 + add_newdoc -8 | +7 ~ add_newdoc | NPY201 `np.add_newdoc_ufunc` will be removed in NumPy 2.0. `add_newdoc_ufunc` is an internal function. @@ -77,13 +74,12 @@ NPY201 [*] `np.byte_bounds` will be removed in NumPy 2.0. Use `numpy.lib.array_u | help: Replace with `numpy.lib.array_utils.byte_bounds` (requires NumPy 2.0 or greater) | -1 + from numpy.lib.array_utils import byte_bounds -2 | def func(): --------------------------------------------------------------------------------- + 1 + from numpy.lib.array_utils import byte_bounds + 2 | def func(): + 3 | import numpy as np + … 12 | - - np.byte_bounds(np.array([1,2,3])) -13 + byte_bounds(np.array([1,2,3])) -14 | +13 ~ byte_bounds(np.array([1,2,3])) | note: This is an unsafe fix and may change runtime behavior @@ -110,10 +106,11 @@ NPY201 [*] `np.cfloat` will be removed in NumPy 2.0. Use `numpy.complex128` inst | help: Replace with `numpy.complex128` | + 2 ~ import numpy as np + 3 | + … 15 | - - np.cfloat(12+34j) -16 + np.complex128(12+34j) -17 | +16 ~ np.complex128(12+34j) | NPY201 [*] `np.clongfloat` will be removed in NumPy 2.0. Use `numpy.clongdouble` instead. @@ -128,10 +125,11 @@ NPY201 [*] `np.clongfloat` will be removed in NumPy 2.0. Use `numpy.clongdouble` | help: Replace with `numpy.clongdouble` | + 2 ~ import numpy as np + 3 | + … 17 | - - np.clongfloat(12+34j) -18 + np.clongdouble(12+34j) -19 | +18 ~ np.clongdouble(12+34j) | NPY201 `np.compat` will be removed in NumPy 2.0. Python 2 is no longer supported. @@ -157,10 +155,11 @@ NPY201 [*] `np.complex_` will be removed in NumPy 2.0. Use `numpy.complex128` in | help: Replace with `numpy.complex128` | + 2 ~ import numpy as np + 3 | + … 21 | - - np.complex_(12+34j) -22 + np.complex128(12+34j) -23 | +22 ~ np.complex128(12+34j) | NPY201 [*] `np.DataSource` will be removed in NumPy 2.0. Use `numpy.lib.npyio.DataSource` instead. @@ -175,13 +174,12 @@ NPY201 [*] `np.DataSource` will be removed in NumPy 2.0. Use `numpy.lib.npyio.Da | help: Replace with `numpy.lib.npyio.DataSource` | -1 + from numpy.lib.npyio import DataSource -2 | def func(): --------------------------------------------------------------------------------- + 1 + from numpy.lib.npyio import DataSource + 2 | def func(): + 3 | import numpy as np + … 24 | - - np.DataSource -25 + DataSource -26 | +25 ~ DataSource | NPY201 `np.deprecate` will be removed in NumPy 2.0. Emit `DeprecationWarning` with `warnings.warn` directly, or use `typing.deprecated`. @@ -262,10 +260,11 @@ NPY201 [*] `np.float_` will be removed in NumPy 2.0. Use `numpy.float64` instead | help: Replace with `numpy.float64` | + 2 ~ import numpy as np + 3 | + … 37 | - - np.float_ -38 + np.float64 -39 | +38 ~ np.float64 | NPY201 `np.geterrobj` will be removed in NumPy 2.0. Use the `np.errstate` context manager instead. @@ -291,10 +290,11 @@ NPY201 [*] `np.Inf` will be removed in NumPy 2.0. Use `numpy.inf` instead. | help: Replace with `numpy.inf` | + 2 ~ import numpy as np + 3 | + … 41 | - - np.Inf -42 + np.inf -43 | +42 ~ np.inf | NPY201 [*] `np.Infinity` will be removed in NumPy 2.0. Use `numpy.inf` instead. @@ -309,10 +309,11 @@ NPY201 [*] `np.Infinity` will be removed in NumPy 2.0. Use `numpy.inf` instead. | help: Replace with `numpy.inf` | + 2 ~ import numpy as np + 3 | + … 43 | - - np.Infinity -44 + np.inf -45 | +44 ~ np.inf | NPY201 [*] `np.infty` will be removed in NumPy 2.0. Use `numpy.inf` instead. @@ -327,10 +328,11 @@ NPY201 [*] `np.infty` will be removed in NumPy 2.0. Use `numpy.inf` instead. | help: Replace with `numpy.inf` | + 2 ~ import numpy as np + 3 | + … 45 | - - np.infty -46 + np.inf -47 | +46 ~ np.inf | NPY201 `np.issctype` will be removed without replacement in NumPy 2.0 @@ -356,10 +358,8 @@ NPY201 [*] `np.issubclass_` will be removed in NumPy 2.0. Use `issubclass` inste | help: Replace with `issubclass` | -49 | - - np.issubclass_(np.int32, np.integer) +50 - np.issubclass_(np.int32, np.integer) 50 + issubclass(np.int32, np.integer) -51 | | NPY201 [*] `np.issubsctype` will be removed in NumPy 2.0. Use `numpy.issubdtype` instead. @@ -374,10 +374,11 @@ NPY201 [*] `np.issubsctype` will be removed in NumPy 2.0. Use `numpy.issubdtype` | help: Replace with `numpy.issubdtype` | + 2 ~ import numpy as np + 3 | + … 51 | - - np.issubsctype -52 + np.issubdtype -53 | +52 ~ np.issubdtype | NPY201 [*] `np.mat` will be removed in NumPy 2.0. Use `numpy.asmatrix` instead. @@ -392,10 +393,11 @@ NPY201 [*] `np.mat` will be removed in NumPy 2.0. Use `numpy.asmatrix` instead. | help: Replace with `numpy.asmatrix` | + 2 ~ import numpy as np + 3 | + … 53 | - - np.mat -54 + np.asmatrix -55 | +54 ~ np.asmatrix | NPY201 `np.maximum_sctype` will be removed without replacement in NumPy 2.0 @@ -421,10 +423,11 @@ NPY201 [*] `np.NaN` will be removed in NumPy 2.0. Use `numpy.nan` instead. | help: Replace with `numpy.nan` | + 2 ~ import numpy as np + 3 | + … 57 | - - np.NaN -58 + np.nan -59 | +58 ~ np.nan | NPY201 `np.nbytes` will be removed in NumPy 2.0. Use `np.dtype().itemsize` instead. @@ -450,10 +453,8 @@ NPY201 [*] `np.NINF` will be removed in NumPy 2.0. Use `-np.inf` instead. | help: Replace with `-np.inf` | -61 | - - np.NINF +62 - np.NINF 62 + -np.inf -63 | | NPY201 [*] `np.NZERO` will be removed in NumPy 2.0. Use `-0.0` instead. @@ -468,10 +469,8 @@ NPY201 [*] `np.NZERO` will be removed in NumPy 2.0. Use `-0.0` instead. | help: Replace with `-0.0` | -63 | - - np.NZERO +64 - np.NZERO 64 + -0.0 -65 | | NPY201 [*] `np.longcomplex` will be removed in NumPy 2.0. Use `numpy.clongdouble` instead. @@ -486,10 +485,11 @@ NPY201 [*] `np.longcomplex` will be removed in NumPy 2.0. Use `numpy.clongdouble | help: Replace with `numpy.clongdouble` | + 2 ~ import numpy as np + 3 | + … 65 | - - np.longcomplex(12+34j) -66 + np.clongdouble(12+34j) -67 | +66 ~ np.clongdouble(12+34j) | NPY201 [*] `np.longfloat` will be removed in NumPy 2.0. Use `numpy.longdouble` instead. @@ -504,10 +504,11 @@ NPY201 [*] `np.longfloat` will be removed in NumPy 2.0. Use `numpy.longdouble` i | help: Replace with `numpy.longdouble` | + 2 ~ import numpy as np + 3 | + … 67 | - - np.longfloat(12+34j) -68 + np.longdouble(12+34j) -69 | +68 ~ np.longdouble(12+34j) | NPY201 `np.lookfor` will be removed in NumPy 2.0. Search NumPy’s documentation directly. @@ -533,8 +534,9 @@ NPY201 [*] `np.NAN` will be removed in NumPy 2.0. Use `numpy.nan` instead. | help: Replace with `numpy.nan` | + 2 ~ import numpy as np + 3 | + … 71 | - - np.NAN -72 + np.nan -73 | +72 ~ np.nan | diff --git a/crates/ruff_linter/src/rules/numpy/snapshots/ruff_linter__rules__numpy__tests__numpy2-deprecation_NPY201_2.py.snap b/crates/ruff_linter/src/rules/numpy/snapshots/ruff_linter__rules__numpy__tests__numpy2-deprecation_NPY201_2.py.snap index ecc91ce8c2cb6..c5fc70e66dade 100644 --- a/crates/ruff_linter/src/rules/numpy/snapshots/ruff_linter__rules__numpy__tests__numpy2-deprecation_NPY201_2.py.snap +++ b/crates/ruff_linter/src/rules/numpy/snapshots/ruff_linter__rules__numpy__tests__numpy2-deprecation_NPY201_2.py.snap @@ -24,10 +24,11 @@ NPY201 [*] `np.PINF` will be removed in NumPy 2.0. Use `numpy.inf` instead. | help: Replace with `numpy.inf` | +2 ~ import numpy as np +3 | +4 | np.obj2sctype(int) 5 | - - np.PINF -6 + np.inf -7 | +6 ~ np.inf | NPY201 [*] `np.PZERO` will be removed in NumPy 2.0. Use `0.0` instead. @@ -42,10 +43,8 @@ NPY201 [*] `np.PZERO` will be removed in NumPy 2.0. Use `0.0` instead. | help: Replace with `0.0` | -7 | - - np.PZERO +8 - np.PZERO 8 + 0.0 -9 | | NPY201 `np.recfromcsv` will be removed in NumPy 2.0. Use `np.genfromtxt` with comma delimiter instead. @@ -82,10 +81,11 @@ NPY201 [*] `np.round_` will be removed in NumPy 2.0. Use `numpy.round` instead. | help: Replace with `numpy.round` | + 2 ~ import numpy as np + 3 | + … 13 | - - np.round_(12.34) -14 + np.round(12.34) -15 | +14 ~ np.round(12.34) | NPY201 [*] `np.safe_eval` will be removed in NumPy 2.0. Use `ast.literal_eval` instead. @@ -100,13 +100,12 @@ NPY201 [*] `np.safe_eval` will be removed in NumPy 2.0. Use `ast.literal_eval` i | help: Replace with `ast.literal_eval` | -1 + from ast import literal_eval -2 | def func(): --------------------------------------------------------------------------------- + 1 + from ast import literal_eval + 2 | def func(): + 3 | import numpy as np + … 16 | - - np.safe_eval -17 + literal_eval -18 | +17 ~ literal_eval | NPY201 `np.sctype2char` will be removed without replacement in NumPy 2.0 @@ -165,10 +164,11 @@ NPY201 [*] `np.singlecomplex` will be removed in NumPy 2.0. Use `numpy.complex64 | help: Replace with `numpy.complex64` | + 2 ~ import numpy as np + 3 | + … 27 | - - np.singlecomplex(12+1j) -28 + np.complex64(12+1j) -29 | +28 ~ np.complex64(12+1j) | NPY201 [*] `np.string_` will be removed in NumPy 2.0. Use `numpy.bytes_` instead. @@ -183,10 +183,11 @@ NPY201 [*] `np.string_` will be removed in NumPy 2.0. Use `numpy.bytes_` instead | help: Replace with `numpy.bytes_` | + 2 ~ import numpy as np + 3 | + … 29 | - - np.string_("asdf") -30 + np.bytes_("asdf") -31 | +30 ~ np.bytes_("asdf") | NPY201 [*] `np.source` will be removed in NumPy 2.0. Use `inspect.getsource` instead. @@ -201,13 +202,12 @@ NPY201 [*] `np.source` will be removed in NumPy 2.0. Use `inspect.getsource` ins | help: Replace with `inspect.getsource` | -1 + from inspect import getsource -2 | def func(): --------------------------------------------------------------------------------- + 1 + from inspect import getsource + 2 | def func(): + 3 | import numpy as np + … 32 | - - np.source -33 + getsource -34 | +33 ~ getsource | NPY201 [*] `np.tracemalloc_domain` will be removed in NumPy 2.0. Use `numpy.lib.tracemalloc_domain` instead. @@ -222,13 +222,12 @@ NPY201 [*] `np.tracemalloc_domain` will be removed in NumPy 2.0. Use `numpy.lib. | help: Replace with `numpy.lib.tracemalloc_domain` | -1 + from numpy.lib import tracemalloc_domain -2 | def func(): --------------------------------------------------------------------------------- + 1 + from numpy.lib import tracemalloc_domain + 2 | def func(): + 3 | import numpy as np + … 34 | - - np.tracemalloc_domain -35 + tracemalloc_domain -36 | +35 ~ tracemalloc_domain | NPY201 [*] `np.unicode_` will be removed in NumPy 2.0. Use `numpy.str_` instead. @@ -243,10 +242,11 @@ NPY201 [*] `np.unicode_` will be removed in NumPy 2.0. Use `numpy.str_` instead. | help: Replace with `numpy.str_` | + 2 ~ import numpy as np + 3 | + … 35 | - - np.unicode_("asf") -36 + np.str_("asf") -37 | +36 ~ np.str_("asf") | NPY201 `np.who` will be removed in NumPy 2.0. Use an IDE variable explorer or `locals()` instead. @@ -272,10 +272,11 @@ NPY201 [*] `np.row_stack` will be removed in NumPy 2.0. Use `numpy.vstack` inste | help: Replace with `numpy.vstack` | + 2 ~ import numpy as np + 3 | + … 39 | - - np.row_stack(([1,2], [3,4])) -40 + np.vstack(([1,2], [3,4])) -41 | +40 ~ np.vstack(([1,2], [3,4])) | NPY201 [*] `np.alltrue` will be removed in NumPy 2.0. Use `numpy.all` instead. @@ -290,10 +291,11 @@ NPY201 [*] `np.alltrue` will be removed in NumPy 2.0. Use `numpy.all` instead. | help: Replace with `numpy.all` | + 2 ~ import numpy as np + 3 | + … 41 | - - np.alltrue([True, True]) -42 + np.all([True, True]) -43 | +42 ~ np.all([True, True]) | NPY201 [*] `np.sometrue` will be removed in NumPy 2.0. Use `numpy.any` instead. @@ -308,10 +310,11 @@ NPY201 [*] `np.sometrue` will be removed in NumPy 2.0. Use `numpy.any` instead. | help: Replace with `numpy.any` | + 2 ~ import numpy as np + 3 | + … 43 | - - np.sometrue([True, False]) -44 + np.any([True, False]) -45 | +44 ~ np.any([True, False]) | NPY201 [*] `np.cumproduct` will be removed in NumPy 2.0. Use `numpy.cumprod` instead. @@ -326,10 +329,11 @@ NPY201 [*] `np.cumproduct` will be removed in NumPy 2.0. Use `numpy.cumprod` ins | help: Replace with `numpy.cumprod` | + 2 ~ import numpy as np + 3 | + … 45 | - - np.cumproduct([1, 2, 3]) -46 + np.cumprod([1, 2, 3]) -47 | +46 ~ np.cumprod([1, 2, 3]) | NPY201 [*] `np.product` will be removed in NumPy 2.0. Use `numpy.prod` instead. @@ -344,10 +348,11 @@ NPY201 [*] `np.product` will be removed in NumPy 2.0. Use `numpy.prod` instead. | help: Replace with `numpy.prod` | + 2 ~ import numpy as np + 3 | + … 47 | - - np.product([1, 2, 3]) -48 + np.prod([1, 2, 3]) -49 | +48 ~ np.prod([1, 2, 3]) | NPY201 [*] `np.trapz` will be removed in NumPy 2.0. Use `numpy.trapezoid` on NumPy 2.0, or ignore this warning on earlier versions. @@ -362,10 +367,11 @@ NPY201 [*] `np.trapz` will be removed in NumPy 2.0. Use `numpy.trapezoid` on Num | help: Replace with `numpy.trapezoid` (requires NumPy 2.0 or greater) | + 2 ~ import numpy as np + 3 | + … 49 | - - np.trapz([1, 2, 3]) -50 + np.trapezoid([1, 2, 3]) -51 | +50 ~ np.trapezoid([1, 2, 3]) | note: This is an unsafe fix and may change runtime behavior @@ -392,13 +398,12 @@ NPY201 [*] `np.AxisError` will be removed in NumPy 2.0. Use `numpy.exceptions.Ax | help: Replace with `numpy.exceptions.AxisError` | -1 + from numpy.exceptions import AxisError -2 | def func(): --------------------------------------------------------------------------------- + 1 + from numpy.exceptions import AxisError + 2 | def func(): + 3 | import numpy as np + … 54 | - - np.AxisError -55 + AxisError -56 | +55 ~ AxisError | NPY201 [*] `np.ComplexWarning` will be removed in NumPy 2.0. Use `numpy.exceptions.ComplexWarning` instead. @@ -413,13 +418,12 @@ NPY201 [*] `np.ComplexWarning` will be removed in NumPy 2.0. Use `numpy.exceptio | help: Replace with `numpy.exceptions.ComplexWarning` | -1 + from numpy.exceptions import ComplexWarning -2 | def func(): --------------------------------------------------------------------------------- + 1 + from numpy.exceptions import ComplexWarning + 2 | def func(): + 3 | import numpy as np + … 56 | - - np.ComplexWarning -57 + ComplexWarning -58 | +57 ~ ComplexWarning | NPY201 [*] `np.compare_chararrays` will be removed in NumPy 2.0. Use `numpy.char.compare_chararrays` instead. @@ -434,13 +438,12 @@ NPY201 [*] `np.compare_chararrays` will be removed in NumPy 2.0. Use `numpy.char | help: Replace with `numpy.char.compare_chararrays` | -1 + from numpy.char import compare_chararrays -2 | def func(): --------------------------------------------------------------------------------- + 1 + from numpy.char import compare_chararrays + 2 | def func(): + 3 | import numpy as np + … 58 | - - np.compare_chararrays -59 + compare_chararrays -60 | +59 ~ compare_chararrays | NPY201 [*] `np.alltrue` will be removed in NumPy 2.0. Use `numpy.all` instead. @@ -455,10 +458,11 @@ NPY201 [*] `np.alltrue` will be removed in NumPy 2.0. Use `numpy.all` instead. | help: Replace with `numpy.all` | + 2 ~ import numpy as np + 3 | + … 62 | except TypeError: - - np.alltrue([True, True]) # Should emit a warning here (`except TypeError`, not `except AttributeError`) -63 + np.all([True, True]) # Should emit a warning here (`except TypeError`, not `except AttributeError`) -64 | +63 ~ np.all([True, True]) # Should emit a warning here (`except TypeError`, not `except AttributeError`) | NPY201 [*] `np.sometrue` will be removed in NumPy 2.0. Use `numpy.any` instead. @@ -472,8 +476,9 @@ NPY201 [*] `np.sometrue` will be removed in NumPy 2.0. Use `numpy.any` instead. | help: Replace with `numpy.any` | + 2 ~ import numpy as np + 3 | + … 67 | except AttributeError: - - np.sometrue([True, True]) # Should emit a warning here -68 + np.any([True, True]) # Should emit a warning here -69 | # (must have an attribute access of the undeprecated name in the `try` body for it to be ignored) +68 ~ np.any([True, True]) # Should emit a warning here | diff --git a/crates/ruff_linter/src/rules/numpy/snapshots/ruff_linter__rules__numpy__tests__numpy2-deprecation_NPY201_3.py.snap b/crates/ruff_linter/src/rules/numpy/snapshots/ruff_linter__rules__numpy__tests__numpy2-deprecation_NPY201_3.py.snap index 10bb6c129ca86..a2aae623fd1fb 100644 --- a/crates/ruff_linter/src/rules/numpy/snapshots/ruff_linter__rules__numpy__tests__numpy2-deprecation_NPY201_3.py.snap +++ b/crates/ruff_linter/src/rules/numpy/snapshots/ruff_linter__rules__numpy__tests__numpy2-deprecation_NPY201_3.py.snap @@ -17,9 +17,7 @@ help: Replace with `numpy.exceptions.DTypePromotionError` 2 | def func(): 3 | import numpy as np 4 | - - np.DTypePromotionError -5 + DTypePromotionError -6 | +5 ~ DTypePromotionError | NPY201 [*] `np.ModuleDeprecationWarning` will be removed in NumPy 2.0. Use `numpy.exceptions.ModuleDeprecationWarning` instead. @@ -36,11 +34,10 @@ help: Replace with `numpy.exceptions.ModuleDeprecationWarning` | 1 + from numpy.exceptions import ModuleDeprecationWarning 2 | def func(): --------------------------------------------------------------------------------- +3 | import numpy as np +… 6 | - - np.ModuleDeprecationWarning -7 + ModuleDeprecationWarning -8 | +7 ~ ModuleDeprecationWarning | NPY201 [*] `np.RankWarning` will be removed in NumPy 2.0. Use `numpy.exceptions.RankWarning` on NumPy 2.0, or ignore this warning on earlier versions. @@ -54,15 +51,14 @@ NPY201 [*] `np.RankWarning` will be removed in NumPy 2.0. Use `numpy.exceptions. 10 | np.TooHardError | help: Replace with `numpy.exceptions.RankWarning` (requires NumPy 2.0 or greater) - | -1 + from numpy.exceptions import RankWarning -2 | def func(): --------------------------------------------------------------------------------- -8 | - - np.RankWarning -9 + RankWarning -10 | - | + | +1 + from numpy.exceptions import RankWarning +2 | def func(): +3 | import numpy as np +… +8 | +9 ~ RankWarning + | note: This is an unsafe fix and may change runtime behavior NPY201 [*] `np.TooHardError` will be removed in NumPy 2.0. Use `numpy.exceptions.TooHardError` instead. @@ -77,13 +73,12 @@ NPY201 [*] `np.TooHardError` will be removed in NumPy 2.0. Use `numpy.exceptions | help: Replace with `numpy.exceptions.TooHardError` | -1 + from numpy.exceptions import TooHardError -2 | def func(): --------------------------------------------------------------------------------- + 1 + from numpy.exceptions import TooHardError + 2 | def func(): + 3 | import numpy as np + … 10 | - - np.TooHardError -11 + TooHardError -12 | +11 ~ TooHardError | NPY201 [*] `np.VisibleDeprecationWarning` will be removed in NumPy 2.0. Use `numpy.exceptions.VisibleDeprecationWarning` instead. @@ -98,13 +93,12 @@ NPY201 [*] `np.VisibleDeprecationWarning` will be removed in NumPy 2.0. Use `num | help: Replace with `numpy.exceptions.VisibleDeprecationWarning` | -1 + from numpy.exceptions import VisibleDeprecationWarning -2 | def func(): --------------------------------------------------------------------------------- + 1 + from numpy.exceptions import VisibleDeprecationWarning + 2 | def func(): + 3 | import numpy as np + … 12 | - - np.VisibleDeprecationWarning -13 + VisibleDeprecationWarning -14 | +13 ~ VisibleDeprecationWarning | NPY201 [*] `np.chararray` will be removed in NumPy 2.0. Use `numpy.char.chararray` instead. @@ -119,13 +113,12 @@ NPY201 [*] `np.chararray` will be removed in NumPy 2.0. Use `numpy.char.chararra | help: Replace with `numpy.char.chararray` | -1 + from numpy.char import chararray -2 | def func(): --------------------------------------------------------------------------------- + 1 + from numpy.char import chararray + 2 | def func(): + 3 | import numpy as np + … 14 | - - np.chararray -15 + chararray -16 | +15 ~ chararray | NPY201 [*] `np.format_parser` will be removed in NumPy 2.0. Use `numpy.rec.format_parser` instead. @@ -137,10 +130,10 @@ NPY201 [*] `np.format_parser` will be removed in NumPy 2.0. Use `numpy.rec.forma | ^^^^^^^^^^^^^^^^ help: Replace with `numpy.rec.format_parser` | -1 + from numpy.rec import format_parser -2 | def func(): --------------------------------------------------------------------------------- + 1 + from numpy.rec import format_parser + 2 | def func(): + 3 | import numpy as np + … 16 | - - np.format_parser -17 + format_parser +17 ~ format_parser | diff --git a/crates/ruff_linter/src/rules/pandas_vet/snapshots/ruff_linter__rules__pandas_vet__tests__PD002_PD002.py.snap b/crates/ruff_linter/src/rules/pandas_vet/snapshots/ruff_linter__rules__pandas_vet__tests__PD002_PD002.py.snap index 08635627a0eee..625e8d608339b 100644 --- a/crates/ruff_linter/src/rules/pandas_vet/snapshots/ruff_linter__rules__pandas_vet__tests__PD002_PD002.py.snap +++ b/crates/ruff_linter/src/rules/pandas_vet/snapshots/ruff_linter__rules__pandas_vet__tests__PD002_PD002.py.snap @@ -13,10 +13,8 @@ PD002 [*] `inplace=True` should be avoided; it has inconsistent behavior | help: Assign to variable; remove `inplace` arg | -4 | - - x.drop(["a"], axis=1, inplace=True) +5 - x.drop(["a"], axis=1, inplace=True) 5 + x = x.drop(["a"], axis=1) -6 | | note: This is an unsafe fix and may change runtime behavior @@ -32,10 +30,8 @@ PD002 [*] `inplace=True` should be avoided; it has inconsistent behavior | help: Assign to variable; remove `inplace` arg | -6 | - - x.y.drop(["a"], axis=1, inplace=True) +7 - x.y.drop(["a"], axis=1, inplace=True) 7 + x.y = x.y.drop(["a"], axis=1) -8 | | note: This is an unsafe fix and may change runtime behavior @@ -50,12 +46,10 @@ PD002 [*] `inplace=True` should be avoided; it has inconsistent behavior 11 | x.drop( | help: Assign to variable; remove `inplace` arg - | -8 | - - x["y"].drop(["a"], axis=1, inplace=True) -9 + x["y"] = x["y"].drop(["a"], axis=1) -10 | - | + | +9 - x["y"].drop(["a"], axis=1, inplace=True) +9 + x["y"] = x["y"].drop(["a"], axis=1) + | note: This is an unsafe fix and may change runtime behavior PD002 [*] `inplace=True` should be avoided; it has inconsistent behavior @@ -69,11 +63,8 @@ PD002 [*] `inplace=True` should be avoided; it has inconsistent behavior | help: Assign to variable; remove `inplace` arg | -10 | - - x.drop( - - inplace=True, -11 + x = x.drop( -12 | columns=["a"], +11 ~ x = x.drop( +12 ~ columns=["a"], | note: This is an unsafe fix and may change runtime behavior @@ -89,11 +80,8 @@ PD002 [*] `inplace=True` should be avoided; it has inconsistent behavior | help: Assign to variable; remove `inplace` arg | -17 | if True: - - x.drop( - - inplace=True, -18 + x = x.drop( -19 | columns=["a"], +18 ~ x = x.drop( +19 ~ columns=["a"], | note: This is an unsafe fix and may change runtime behavior @@ -109,10 +97,8 @@ PD002 [*] `inplace=True` should be avoided; it has inconsistent behavior | help: Assign to variable; remove `inplace` arg | -23 | - - x.drop(["a"], axis=1, **kwargs, inplace=True) +24 - x.drop(["a"], axis=1, **kwargs, inplace=True) 24 + x = x.drop(["a"], axis=1, **kwargs) -25 | x.drop(["a"], axis=1, inplace=True, **kwargs) | note: This is an unsafe fix and may change runtime behavior @@ -161,9 +147,7 @@ PD002 [*] `inplace=True` should be avoided; it has inconsistent behavior | help: Assign to variable; remove `inplace` arg | -32 | - - (x.drop(["a"], axis=1, inplace=True)) +33 - (x.drop(["a"], axis=1, inplace=True)) 33 + x = (x.drop(["a"], axis=1)) -34 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pandas_vet/snapshots/ruff_linter__rules__pandas_vet__tests__PD002_fail.snap b/crates/ruff_linter/src/rules/pandas_vet/snapshots/ruff_linter__rules__pandas_vet__tests__PD002_fail.snap index f07b80f849c66..0176dd668e0f8 100644 --- a/crates/ruff_linter/src/rules/pandas_vet/snapshots/ruff_linter__rules__pandas_vet__tests__PD002_fail.snap +++ b/crates/ruff_linter/src/rules/pandas_vet/snapshots/ruff_linter__rules__pandas_vet__tests__PD002_fail.snap @@ -10,8 +10,7 @@ PD002 [*] `inplace=True` should be avoided; it has inconsistent behavior | ^^^^^^^^^^^^ help: Assign to variable; remove `inplace` arg | -3 | x = pd.DataFrame() - - x.drop(["a"], axis=1, inplace=True) +4 - x.drop(["a"], axis=1, inplace=True) 4 + x = x.drop(["a"], axis=1) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__N804_N804.py.snap b/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__N804_N804.py.snap index e925e765118da..a8b70935195e3 100644 --- a/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__N804_N804.py.snap +++ b/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__N804_N804.py.snap @@ -12,10 +12,8 @@ N804 [*] First argument of a class method should be named `cls` | help: Rename `self` to `cls` | -29 | - - def __init_subclass__(self, default_name, **kwargs): +30 - def __init_subclass__(self, default_name, **kwargs): 30 + def __init_subclass__(cls, default_name, **kwargs): -31 | ... | note: This is an unsafe fix and may change runtime behavior @@ -29,10 +27,8 @@ N804 [*] First argument of a class method should be named `cls` | help: Rename `self` to `cls` | -37 | @classmethod - - def bad_class_method_with_positional_only_argument(self, x, /, other): +38 - def bad_class_method_with_positional_only_argument(self, x, /, other): 38 + def bad_class_method_with_positional_only_argument(cls, x, /, other): -39 | ... | note: This is an unsafe fix and may change runtime behavior @@ -46,10 +42,8 @@ N804 [*] First argument of a class method should be named `cls` | help: Rename `self` to `cls` | -42 | class MetaClass(ABCMeta): - - def bad_method(self): +43 - def bad_method(self): 43 + def bad_method(cls): -44 | pass | note: This is an unsafe fix and may change runtime behavior @@ -118,14 +112,9 @@ N804 [*] First argument of a class method should be named `cls` | help: Rename `this` to `cls` | -69 | class RenamingInMethodBodyClass(ABCMeta): - - def bad_method(this): - - this = this - - this -70 + def bad_method(cls): -71 + cls = cls -72 + cls -73 | +70 ~ def bad_method(cls): +71 ~ cls = cls +72 ~ cls | note: This is an unsafe fix and may change runtime behavior @@ -140,12 +129,8 @@ N804 [*] First argument of a class method should be named `cls` | help: Rename `this` to `cls` | -73 | - - def bad_method(this): - - self = this -74 + def bad_method(cls): -75 + self = cls -76 | +74 ~ def bad_method(cls): +75 ~ self = cls | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__N805_N805.py.snap b/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__N805_N805.py.snap index 5a365770ebf17..611c2a161b977 100644 --- a/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__N805_N805.py.snap +++ b/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__N805_N805.py.snap @@ -11,10 +11,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `this` to `self` | -6 | class Class: - - def bad_method(this): +7 - def bad_method(this): 7 + def bad_method(self): -8 | pass | note: This is an unsafe fix and may change runtime behavior @@ -28,10 +26,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `this` to `self` | -10 | if False: - - def extra_bad_method(this): +11 - def extra_bad_method(this): 11 + def extra_bad_method(self): -12 | pass | note: This is an unsafe fix and may change runtime behavior @@ -45,10 +41,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `cls` to `self` | -29 | @pydantic.validator - - def lower(cls, my_field: str) -> str: +30 - def lower(cls, my_field: str) -> str: 30 + def lower(self, my_field: str) -> str: -31 | pass | note: This is an unsafe fix and may change runtime behavior @@ -62,10 +56,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `cls` to `self` | -33 | @pydantic.validator("my_field") - - def lower(cls, my_field: str) -> str: +34 - def lower(cls, my_field: str) -> str: 34 + def lower(self, my_field: str) -> str: -35 | pass | note: This is an unsafe fix and may change runtime behavior @@ -80,10 +72,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `this` to `self` | -62 | - - def bad_method_pos_only(this, blah, /, something: str): +63 - def bad_method_pos_only(this, blah, /, something: str): 63 + def bad_method_pos_only(self, blah, /, something: str): -64 | pass | note: This is an unsafe fix and may change runtime behavior @@ -98,10 +88,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `cls` to `self` | -68 | @hybrid_property - - def bad(cls): +69 - def bad(cls): 69 + def bad(self): -70 | pass | note: This is an unsafe fix and may change runtime behavior @@ -115,10 +103,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `cls` to `self` | -76 | @bad.wtf - - def bad(cls): +77 - def bad(cls): 77 + def bad(self): -78 | pass | note: This is an unsafe fix and may change runtime behavior @@ -132,10 +118,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `cls` to `self` | -84 | @good.expression - - def good(cls): +85 - def good(cls): 85 + def good(self): -86 | pass | note: This is an unsafe fix and may change runtime behavior @@ -149,10 +133,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `foo` to `self` | -92 | @foobar.thisisstatic - - def badstatic(foo): +93 - def badstatic(foo): 93 + def badstatic(self): -94 | pass | note: This is an unsafe fix and may change runtime behavior @@ -221,14 +203,9 @@ N805 [*] First argument of a method should be named `self` | help: Rename `this` to `self` | -114 | class RenamingInMethodBodyClass: - - def bad_method(this): - - this = this - - this -115 + def bad_method(self): -116 + self = self -117 + self -118 | +115 ~ def bad_method(self): +116 ~ self = self +117 ~ self | note: This is an unsafe fix and may change runtime behavior @@ -253,12 +230,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `household` to `self` | -123 | class RenamingWithNFKC: - - def formula(household): - - hºusehold(1) -124 + def formula(self): -125 + self(1) -126 | +124 ~ def formula(self): +125 ~ self(1) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__classmethod_decorators.snap b/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__classmethod_decorators.snap index 3cabc67c5c770..518d638a4db84 100644 --- a/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__classmethod_decorators.snap +++ b/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__classmethod_decorators.snap @@ -11,10 +11,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `this` to `self` | -6 | class Class: - - def bad_method(this): +7 - def bad_method(this): 7 + def bad_method(self): -8 | pass | note: This is an unsafe fix and may change runtime behavior @@ -28,10 +26,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `this` to `self` | -10 | if False: - - def extra_bad_method(this): +11 - def extra_bad_method(this): 11 + def extra_bad_method(self): -12 | pass | note: This is an unsafe fix and may change runtime behavior @@ -46,10 +42,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `this` to `self` | -62 | - - def bad_method_pos_only(this, blah, /, something: str): +63 - def bad_method_pos_only(this, blah, /, something: str): 63 + def bad_method_pos_only(self, blah, /, something: str): -64 | pass | note: This is an unsafe fix and may change runtime behavior @@ -64,10 +58,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `cls` to `self` | -68 | @hybrid_property - - def bad(cls): +69 - def bad(cls): 69 + def bad(self): -70 | pass | note: This is an unsafe fix and may change runtime behavior @@ -81,10 +73,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `cls` to `self` | -76 | @bad.wtf - - def bad(cls): +77 - def bad(cls): 77 + def bad(self): -78 | pass | note: This is an unsafe fix and may change runtime behavior @@ -98,10 +88,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `foo` to `self` | -92 | @foobar.thisisstatic - - def badstatic(foo): +93 - def badstatic(foo): 93 + def badstatic(self): -94 | pass | note: This is an unsafe fix and may change runtime behavior @@ -170,14 +158,9 @@ N805 [*] First argument of a method should be named `self` | help: Rename `this` to `self` | -114 | class RenamingInMethodBodyClass: - - def bad_method(this): - - this = this - - this -115 + def bad_method(self): -116 + self = self -117 + self -118 | +115 ~ def bad_method(self): +116 ~ self = self +117 ~ self | note: This is an unsafe fix and may change runtime behavior @@ -202,12 +185,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `household` to `self` | -123 | class RenamingWithNFKC: - - def formula(household): - - hºusehold(1) -124 + def formula(self): -125 + self(1) -126 | +124 ~ def formula(self): +125 ~ self(1) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__ignore_names_N804_N804.py.snap b/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__ignore_names_N804_N804.py.snap index 9be3d65bb2d21..c37f4a0835572 100644 --- a/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__ignore_names_N804_N804.py.snap +++ b/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__ignore_names_N804_N804.py.snap @@ -11,10 +11,8 @@ N804 [*] First argument of a class method should be named `cls` | help: Rename `self` to `cls` | -4 | class Class: - - def __init_subclass__(self, default_name, **kwargs): +5 - def __init_subclass__(self, default_name, **kwargs): 5 + def __init_subclass__(cls, default_name, **kwargs): -6 | ... | note: This is an unsafe fix and may change runtime behavior @@ -27,12 +25,10 @@ N804 [*] First argument of a class method should be named `cls` 10 | ... | help: Rename `self` to `cls` - | -8 | @classmethod - - def badAllowed(self, x, /, other): -9 + def badAllowed(cls, x, /, other): -10 | ... - | + | +9 - def badAllowed(self, x, /, other): +9 + def badAllowed(cls, x, /, other): + | note: This is an unsafe fix and may change runtime behavior N804 [*] First argument of a class method should be named `cls` @@ -45,10 +41,8 @@ N804 [*] First argument of a class method should be named `cls` | help: Rename `self` to `cls` | -12 | @classmethod - - def stillBad(self, x, /, other): +13 - def stillBad(self, x, /, other): 13 + def stillBad(cls, x, /, other): -14 | ... | note: This is an unsafe fix and may change runtime behavior @@ -62,10 +56,8 @@ N804 [*] First argument of a class method should be named `cls` | help: Rename `self` to `cls` | -17 | class MetaClass(ABCMeta): - - def badAllowed(self): +18 - def badAllowed(self): 18 + def badAllowed(cls): -19 | pass | note: This is an unsafe fix and may change runtime behavior @@ -80,9 +72,7 @@ N804 [*] First argument of a class method should be named `cls` | help: Rename `self` to `cls` | -20 | - - def stillBad(self): +21 - def stillBad(self): 21 + def stillBad(cls): -22 | pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__ignore_names_N805_N805.py.snap b/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__ignore_names_N805_N805.py.snap index b9fb032f0c616..cfbb9318161d1 100644 --- a/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__ignore_names_N805_N805.py.snap +++ b/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__ignore_names_N805_N805.py.snap @@ -11,10 +11,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `this` to `self` | -6 | class Class: - - def badAllowed(this): +7 - def badAllowed(this): 7 + def badAllowed(self): -8 | pass | note: This is an unsafe fix and may change runtime behavior @@ -29,10 +27,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `this` to `self` | -9 | - - def stillBad(this): +10 - def stillBad(this): 10 + def stillBad(self): -11 | pass | note: This is an unsafe fix and may change runtime behavior @@ -47,10 +43,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `this` to `self` | -14 | - - def badAllowed(this): +15 - def badAllowed(this): 15 + def badAllowed(self): -16 | pass | note: This is an unsafe fix and may change runtime behavior @@ -65,10 +59,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `this` to `self` | -17 | - - def stillBad(this): +18 - def stillBad(this): 18 + def stillBad(self): -19 | pass | note: This is an unsafe fix and may change runtime behavior @@ -82,10 +74,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `cls` to `self` | -21 | @pydantic.validator - - def badAllowed(cls, my_field: str) -> str: +22 - def badAllowed(cls, my_field: str) -> str: 22 + def badAllowed(self, my_field: str) -> str: -23 | pass | note: This is an unsafe fix and may change runtime behavior @@ -99,10 +89,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `cls` to `self` | -25 | @pydantic.validator - - def stillBad(cls, my_field: str) -> str: +26 - def stillBad(cls, my_field: str) -> str: 26 + def stillBad(self, my_field: str) -> str: -27 | pass | note: This is an unsafe fix and may change runtime behavior @@ -116,10 +104,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `cls` to `self` | -29 | @pydantic.validator("my_field") - - def badAllowed(cls, my_field: str) -> str: +30 - def badAllowed(cls, my_field: str) -> str: 30 + def badAllowed(self, my_field: str) -> str: -31 | pass | note: This is an unsafe fix and may change runtime behavior @@ -133,10 +119,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `cls` to `self` | -33 | @pydantic.validator("my_field") - - def stillBad(cls, my_field: str) -> str: +34 - def stillBad(cls, my_field: str) -> str: 34 + def stillBad(self, my_field: str) -> str: -35 | pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__staticmethod_decorators.snap b/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__staticmethod_decorators.snap index 2644422e4f16a..f75383fe3f5e6 100644 --- a/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__staticmethod_decorators.snap +++ b/crates/ruff_linter/src/rules/pep8_naming/snapshots/ruff_linter__rules__pep8_naming__tests__staticmethod_decorators.snap @@ -11,10 +11,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `this` to `self` | -6 | class Class: - - def bad_method(this): +7 - def bad_method(this): 7 + def bad_method(self): -8 | pass | note: This is an unsafe fix and may change runtime behavior @@ -28,10 +26,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `this` to `self` | -10 | if False: - - def extra_bad_method(this): +11 - def extra_bad_method(this): 11 + def extra_bad_method(self): -12 | pass | note: This is an unsafe fix and may change runtime behavior @@ -45,10 +41,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `cls` to `self` | -29 | @pydantic.validator - - def lower(cls, my_field: str) -> str: +30 - def lower(cls, my_field: str) -> str: 30 + def lower(self, my_field: str) -> str: -31 | pass | note: This is an unsafe fix and may change runtime behavior @@ -62,10 +56,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `cls` to `self` | -33 | @pydantic.validator("my_field") - - def lower(cls, my_field: str) -> str: +34 - def lower(cls, my_field: str) -> str: 34 + def lower(self, my_field: str) -> str: -35 | pass | note: This is an unsafe fix and may change runtime behavior @@ -80,10 +72,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `this` to `self` | -62 | - - def bad_method_pos_only(this, blah, /, something: str): +63 - def bad_method_pos_only(this, blah, /, something: str): 63 + def bad_method_pos_only(self, blah, /, something: str): -64 | pass | note: This is an unsafe fix and may change runtime behavior @@ -98,10 +88,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `cls` to `self` | -68 | @hybrid_property - - def bad(cls): +69 - def bad(cls): 69 + def bad(self): -70 | pass | note: This is an unsafe fix and may change runtime behavior @@ -115,10 +103,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `cls` to `self` | -76 | @bad.wtf - - def bad(cls): +77 - def bad(cls): 77 + def bad(self): -78 | pass | note: This is an unsafe fix and may change runtime behavior @@ -132,10 +118,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `cls` to `self` | -84 | @good.expression - - def good(cls): +85 - def good(cls): 85 + def good(self): -86 | pass | note: This is an unsafe fix and may change runtime behavior @@ -204,14 +188,9 @@ N805 [*] First argument of a method should be named `self` | help: Rename `this` to `self` | -114 | class RenamingInMethodBodyClass: - - def bad_method(this): - - this = this - - this -115 + def bad_method(self): -116 + self = self -117 + self -118 | +115 ~ def bad_method(self): +116 ~ self = self +117 ~ self | note: This is an unsafe fix and may change runtime behavior @@ -236,12 +215,8 @@ N805 [*] First argument of a method should be named `self` | help: Rename `household` to `self` | -123 | class RenamingWithNFKC: - - def formula(household): - - hºusehold(1) -124 + def formula(self): -125 + self(1) -126 | +124 ~ def formula(self): +125 ~ self(1) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/perflint/snapshots/ruff_linter__rules__perflint__tests__PERF101_PERF101.py.snap b/crates/ruff_linter/src/rules/perflint/snapshots/ruff_linter__rules__perflint__tests__PERF101_PERF101.py.snap index 68b38af60c5a5..5d6c05b59638b 100644 --- a/crates/ruff_linter/src/rules/perflint/snapshots/ruff_linter__rules__perflint__tests__PERF101_PERF101.py.snap +++ b/crates/ruff_linter/src/rules/perflint/snapshots/ruff_linter__rules__perflint__tests__PERF101_PERF101.py.snap @@ -12,10 +12,8 @@ PERF101 [*] Do not cast an iterable to `list` before iterating over it | help: Remove `list()` cast | -6 | - - for i in list(foo_tuple): # PERF101 +7 - for i in list(foo_tuple): # PERF101 7 + for i in foo_tuple: # PERF101 -8 | pass | PERF101 [*] Do not cast an iterable to `list` before iterating over it @@ -29,10 +27,8 @@ PERF101 [*] Do not cast an iterable to `list` before iterating over it | help: Remove `list()` cast | -9 | - - for i in list(foo_list): # PERF101 +10 - for i in list(foo_list): # PERF101 10 + for i in foo_list: # PERF101 -11 | pass | PERF101 [*] Do not cast an iterable to `list` before iterating over it @@ -46,10 +42,8 @@ PERF101 [*] Do not cast an iterable to `list` before iterating over it | help: Remove `list()` cast | -12 | - - for i in list(foo_set): # PERF101 +13 - for i in list(foo_set): # PERF101 13 + for i in foo_set: # PERF101 -14 | pass | PERF101 [*] Do not cast an iterable to `list` before iterating over it @@ -63,10 +57,8 @@ PERF101 [*] Do not cast an iterable to `list` before iterating over it | help: Remove `list()` cast | -15 | - - for i in list((1, 2, 3)): # PERF101 +16 - for i in list((1, 2, 3)): # PERF101 16 + for i in (1, 2, 3): # PERF101 -17 | pass | PERF101 [*] Do not cast an iterable to `list` before iterating over it @@ -80,10 +72,8 @@ PERF101 [*] Do not cast an iterable to `list` before iterating over it | help: Remove `list()` cast | -18 | - - for i in list([1, 2, 3]): # PERF101 +19 - for i in list([1, 2, 3]): # PERF101 19 + for i in [1, 2, 3]: # PERF101 -20 | pass | PERF101 [*] Do not cast an iterable to `list` before iterating over it @@ -97,10 +87,8 @@ PERF101 [*] Do not cast an iterable to `list` before iterating over it | help: Remove `list()` cast | -21 | - - for i in list({1, 2, 3}): # PERF101 +22 - for i in list({1, 2, 3}): # PERF101 22 + for i in {1, 2, 3}: # PERF101 -23 | pass | PERF101 [*] Do not cast an iterable to `list` before iterating over it @@ -121,17 +109,11 @@ PERF101 [*] Do not cast an iterable to `list` before iterating over it | help: Remove `list()` cast | -24 | - - for i in list( - - { -25 + for i in { -26 | 1, -27 | 2, -28 | 3, - - } - - ): -29 + }: -30 | pass +25 ~ for i in { +26 + 1, +27 + 2, +28 + 3, +29 ~ }: | PERF101 [*] Do not cast an iterable to `list` before iterating over it @@ -148,12 +130,10 @@ PERF101 [*] Do not cast an iterable to `list` before iterating over it | help: Remove `list()` cast | -33 | - - for i in list( # Comment - - {1, 2, 3} - - ): # PERF101 +34 - for i in list( # Comment +35 - {1, 2, 3} +36 - ): # PERF101 34 + for i in {1, 2, 3}: # PERF101 -35 | pass | note: This is an unsafe fix and may change runtime behavior @@ -169,10 +149,8 @@ PERF101 [*] Do not cast an iterable to `list` before iterating over it | help: Remove `list()` cast | -56 | - - for i in list(foo_list): # PERF101 +57 - for i in list(foo_list): # PERF101 57 + for i in foo_list: # PERF101 -58 | # Make sure we match the correct list | PERF101 [*] Do not cast an iterable to `list` before iterating over it @@ -186,10 +164,8 @@ PERF101 [*] Do not cast an iterable to `list` before iterating over it | help: Remove `list()` cast | -68 | - - for i in list(nested_tuple): # PERF101 +69 - for i in list(nested_tuple): # PERF101 69 + for i in nested_tuple: # PERF101 -70 | pass | PERF101 [*] Do not cast an iterable to `list` before iterating over it @@ -203,10 +179,8 @@ PERF101 [*] Do not cast an iterable to `list` before iterating over it | help: Remove `list()` cast | -85 | - - for i in builtins.list(nested_tuple): # PERF101 +86 - for i in builtins.list(nested_tuple): # PERF101 86 + for i in nested_tuple: # PERF101 -87 | pass | PERF101 [*] Do not cast an iterable to `list` before iterating over it @@ -220,10 +194,8 @@ PERF101 [*] Do not cast an iterable to `list` before iterating over it | help: Remove `list()` cast | -90 | items = (1, 2, 3) - - for i in(list)(items): +91 - for i in(list)(items): 91 + for i in items: -92 | print(i) | PERF101 [*] Do not cast an iterable to `list` before iterating over it @@ -243,16 +215,14 @@ PERF101 [*] Do not cast an iterable to `list` before iterating over it 103 | print(i) | help: Remove `list()` cast - | -95 | items = (1, 2, 3) - - for i in ( # 1 - - list # 2 - - # 3 - - )( # 4 - - items # 5 - - # 6 - - ): -96 + for i in items: -97 | print(i) - | + | + 96 - for i in ( # 1 + 97 - list # 2 + 98 - # 3 + 99 - )( # 4 +100 - items # 5 +101 - # 6 +102 - ): + 96 + for i in items: + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/perflint/snapshots/ruff_linter__rules__perflint__tests__PERF102_PERF102.py.snap b/crates/ruff_linter/src/rules/perflint/snapshots/ruff_linter__rules__perflint__tests__PERF102_PERF102.py.snap index f66e0f1307323..202ace269b085 100644 --- a/crates/ruff_linter/src/rules/perflint/snapshots/ruff_linter__rules__perflint__tests__PERF102_PERF102.py.snap +++ b/crates/ruff_linter/src/rules/perflint/snapshots/ruff_linter__rules__perflint__tests__PERF102_PERF102.py.snap @@ -11,10 +11,8 @@ PERF102 [*] When using only the values of a dict use the `values()` method | help: Replace `.items()` with `.values()` | -4 | def f(): - - for _, value in some_dict.items(): # PERF102 +5 - for _, value in some_dict.items(): # PERF102 5 + for value in some_dict.values(): # PERF102 -6 | print(value) | note: This is an unsafe fix and may change runtime behavior @@ -28,10 +26,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -9 | def f(): - - for key, _ in some_dict.items(): # PERF102 +10 - for key, _ in some_dict.items(): # PERF102 10 + for key in some_dict.keys(): # PERF102 -11 | print(key) | note: This is an unsafe fix and may change runtime behavior @@ -45,10 +41,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -14 | def f(): - - for weird_arg_name, _ in some_dict.items(): # PERF102 +15 - for weird_arg_name, _ in some_dict.items(): # PERF102 15 + for weird_arg_name in some_dict.keys(): # PERF102 -16 | print(weird_arg_name) | note: This is an unsafe fix and may change runtime behavior @@ -62,10 +56,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -19 | def f(): - - for name, (_, _) in some_dict.items(): # PERF102 +20 - for name, (_, _) in some_dict.items(): # PERF102 20 + for name in some_dict.keys(): # PERF102 -21 | print(name) | note: This is an unsafe fix and may change runtime behavior @@ -79,10 +71,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -29 | def f(): - - for (key1, _), (_, _) in some_dict.items(): # PERF102 +30 - for (key1, _), (_, _) in some_dict.items(): # PERF102 30 + for (key1, _) in some_dict.keys(): # PERF102 -31 | print(key1) | note: This is an unsafe fix and may change runtime behavior @@ -96,10 +86,8 @@ PERF102 [*] When using only the values of a dict use the `values()` method | help: Replace `.items()` with `.values()` | -34 | def f(): - - for (_, (_, _)), (value, _) in some_dict.items(): # PERF102 +35 - for (_, (_, _)), (value, _) in some_dict.items(): # PERF102 35 + for (value, _) in some_dict.values(): # PERF102 -36 | print(value) | note: This is an unsafe fix and may change runtime behavior @@ -113,10 +101,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -49 | def f(): - - for ((_, key2), (_, _)) in some_dict.items(): # PERF102 +50 - for ((_, key2), (_, _)) in some_dict.items(): # PERF102 50 + for (_, key2) in some_dict.keys(): # PERF102 -51 | print(key2) | note: This is an unsafe fix and may change runtime behavior @@ -130,10 +116,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -84 | def f(): - - for name, (_, _) in (some_function()).items(): # PERF102 +85 - for name, (_, _) in (some_function()).items(): # PERF102 85 + for name in (some_function()).keys(): # PERF102 -86 | print(name) | note: This is an unsafe fix and may change runtime behavior @@ -147,10 +131,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -89 | def f(): - - for name, (_, _) in (some_function().some_attribute).items(): # PERF102 +90 - for name, (_, _) in (some_function().some_attribute).items(): # PERF102 90 + for name in (some_function().some_attribute).keys(): # PERF102 -91 | print(name) | note: This is an unsafe fix and may change runtime behavior @@ -164,10 +146,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -94 | def f(): - - for name, unused_value in some_dict.items(): # PERF102 +95 - for name, unused_value in some_dict.items(): # PERF102 95 + for name in some_dict.keys(): # PERF102 -96 | print(name) | note: This is an unsafe fix and may change runtime behavior @@ -181,10 +161,8 @@ PERF102 [*] When using only the values of a dict use the `values()` method | help: Replace `.items()` with `.values()` | -99 | def f(): - - for unused_name, value in some_dict.items(): # PERF102 +100 - for unused_name, value in some_dict.items(): # PERF102 100 + for value in some_dict.values(): # PERF102 -101 | print(value) | note: This is an unsafe fix and may change runtime behavior @@ -199,9 +177,7 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -105 | def _create_context(name_to_value): - - for(B,D)in A.items(): +106 - for(B,D)in A.items(): 106 + for B in A.keys(): -107 | if(C:=name_to_value.get(B.name)):A.run(B.set,C) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/perflint/snapshots/ruff_linter__rules__perflint__tests__preview__PERF102_PERF102.py.snap b/crates/ruff_linter/src/rules/perflint/snapshots/ruff_linter__rules__perflint__tests__preview__PERF102_PERF102.py.snap index 26d75f1234f98..1672e5e8b0889 100644 --- a/crates/ruff_linter/src/rules/perflint/snapshots/ruff_linter__rules__perflint__tests__preview__PERF102_PERF102.py.snap +++ b/crates/ruff_linter/src/rules/perflint/snapshots/ruff_linter__rules__perflint__tests__preview__PERF102_PERF102.py.snap @@ -11,10 +11,8 @@ PERF102 [*] When using only the values of a dict use the `values()` method | help: Replace `.items()` with `.values()` | -4 | def f(): - - for _, value in some_dict.items(): # PERF102 +5 - for _, value in some_dict.items(): # PERF102 5 + for value in some_dict.values(): # PERF102 -6 | print(value) | note: This is an unsafe fix and may change runtime behavior @@ -28,10 +26,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -9 | def f(): - - for key, _ in some_dict.items(): # PERF102 +10 - for key, _ in some_dict.items(): # PERF102 10 + for key in some_dict.keys(): # PERF102 -11 | print(key) | note: This is an unsafe fix and may change runtime behavior @@ -45,10 +41,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -14 | def f(): - - for weird_arg_name, _ in some_dict.items(): # PERF102 +15 - for weird_arg_name, _ in some_dict.items(): # PERF102 15 + for weird_arg_name in some_dict.keys(): # PERF102 -16 | print(weird_arg_name) | note: This is an unsafe fix and may change runtime behavior @@ -62,10 +56,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -19 | def f(): - - for name, (_, _) in some_dict.items(): # PERF102 +20 - for name, (_, _) in some_dict.items(): # PERF102 20 + for name in some_dict.keys(): # PERF102 -21 | print(name) | note: This is an unsafe fix and may change runtime behavior @@ -79,10 +71,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -29 | def f(): - - for (key1, _), (_, _) in some_dict.items(): # PERF102 +30 - for (key1, _), (_, _) in some_dict.items(): # PERF102 30 + for (key1, _) in some_dict.keys(): # PERF102 -31 | print(key1) | note: This is an unsafe fix and may change runtime behavior @@ -96,10 +86,8 @@ PERF102 [*] When using only the values of a dict use the `values()` method | help: Replace `.items()` with `.values()` | -34 | def f(): - - for (_, (_, _)), (value, _) in some_dict.items(): # PERF102 +35 - for (_, (_, _)), (value, _) in some_dict.items(): # PERF102 35 + for (value, _) in some_dict.values(): # PERF102 -36 | print(value) | note: This is an unsafe fix and may change runtime behavior @@ -113,10 +101,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -49 | def f(): - - for ((_, key2), (_, _)) in some_dict.items(): # PERF102 +50 - for ((_, key2), (_, _)) in some_dict.items(): # PERF102 50 + for (_, key2) in some_dict.keys(): # PERF102 -51 | print(key2) | note: This is an unsafe fix and may change runtime behavior @@ -130,10 +116,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -84 | def f(): - - for name, (_, _) in (some_function()).items(): # PERF102 +85 - for name, (_, _) in (some_function()).items(): # PERF102 85 + for name in (some_function()).keys(): # PERF102 -86 | print(name) | note: This is an unsafe fix and may change runtime behavior @@ -147,10 +131,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -89 | def f(): - - for name, (_, _) in (some_function().some_attribute).items(): # PERF102 +90 - for name, (_, _) in (some_function().some_attribute).items(): # PERF102 90 + for name in (some_function().some_attribute).keys(): # PERF102 -91 | print(name) | note: This is an unsafe fix and may change runtime behavior @@ -164,10 +146,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -94 | def f(): - - for name, unused_value in some_dict.items(): # PERF102 +95 - for name, unused_value in some_dict.items(): # PERF102 95 + for name in some_dict.keys(): # PERF102 -96 | print(name) | note: This is an unsafe fix and may change runtime behavior @@ -181,10 +161,8 @@ PERF102 [*] When using only the values of a dict use the `values()` method | help: Replace `.items()` with `.values()` | -99 | def f(): - - for unused_name, value in some_dict.items(): # PERF102 +100 - for unused_name, value in some_dict.items(): # PERF102 100 + for value in some_dict.values(): # PERF102 -101 | print(value) | note: This is an unsafe fix and may change runtime behavior @@ -199,10 +177,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -105 | def _create_context(name_to_value): - - for(B,D)in A.items(): +106 - for(B,D)in A.items(): 106 + for B in A.keys(): -107 | if(C:=name_to_value.get(B.name)):A.run(B.set,C) | note: This is an unsafe fix and may change runtime behavior @@ -217,10 +193,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -110 | # Comprehensions and generators — errors (https://github.com/astral-sh/ruff/issues/6638) - - _ = [k for k, _ in some_dict.items()] # PERF102 +111 - _ = [k for k, _ in some_dict.items()] # PERF102 111 + _ = [k for k in some_dict.keys()] # PERF102 -112 | _ = {k for k, _ in some_dict.items()} # PERF102 | note: This is an unsafe fix and may change runtime behavior @@ -236,10 +210,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -111 | _ = [k for k, _ in some_dict.items()] # PERF102 - - _ = {k for k, _ in some_dict.items()} # PERF102 +112 - _ = {k for k, _ in some_dict.items()} # PERF102 112 + _ = {k for k in some_dict.keys()} # PERF102 -113 | _ = {k: "v" for k, _ in some_dict.items()} # PERF102 | note: This is an unsafe fix and may change runtime behavior @@ -255,10 +227,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -112 | _ = {k for k, _ in some_dict.items()} # PERF102 - - _ = {k: "v" for k, _ in some_dict.items()} # PERF102 +113 - _ = {k: "v" for k, _ in some_dict.items()} # PERF102 113 + _ = {k: "v" for k in some_dict.keys()} # PERF102 -114 | _ = (k for k, _ in some_dict.items()) # PERF102 | note: This is an unsafe fix and may change runtime behavior @@ -274,10 +244,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -113 | _ = {k: "v" for k, _ in some_dict.items()} # PERF102 - - _ = (k for k, _ in some_dict.items()) # PERF102 +114 - _ = (k for k, _ in some_dict.items()) # PERF102 114 + _ = (k for k in some_dict.keys()) # PERF102 -115 | _ = [v for _, v in some_dict.items()] # PERF102 | note: This is an unsafe fix and may change runtime behavior @@ -293,10 +261,8 @@ PERF102 [*] When using only the values of a dict use the `values()` method | help: Replace `.items()` with `.values()` | -114 | _ = (k for k, _ in some_dict.items()) # PERF102 - - _ = [v for _, v in some_dict.items()] # PERF102 +115 - _ = [v for _, v in some_dict.items()] # PERF102 115 + _ = [v for v in some_dict.values()] # PERF102 -116 | _ = [k for k, v in some_dict.items()] # PERF102 (v unused) | note: This is an unsafe fix and may change runtime behavior @@ -311,10 +277,8 @@ PERF102 [*] When using only the keys of a dict use the `keys()` method | help: Replace `.items()` with `.keys()` | -115 | _ = [v for _, v in some_dict.items()] # PERF102 - - _ = [k for k, v in some_dict.items()] # PERF102 (v unused) +116 - _ = [k for k, v in some_dict.items()] # PERF102 (v unused) 116 + _ = [k for k in some_dict.keys()] # PERF102 (v unused) -117 | _ = [v for x in range(1) for _, v in some_dict.items()] # PERF102 | note: This is an unsafe fix and may change runtime behavior @@ -330,9 +294,7 @@ PERF102 [*] When using only the values of a dict use the `values()` method | help: Replace `.items()` with `.values()` | -116 | _ = [k for k, v in some_dict.items()] # PERF102 (v unused) - - _ = [v for x in range(1) for _, v in some_dict.items()] # PERF102 +117 - _ = [v for x in range(1) for _, v in some_dict.items()] # PERF102 117 + _ = [v for x in range(1) for v in some_dict.values()] # PERF102 -118 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/perflint/snapshots/ruff_linter__rules__perflint__tests__preview__PERF401_PERF401.py.snap b/crates/ruff_linter/src/rules/perflint/snapshots/ruff_linter__rules__perflint__tests__preview__PERF401_PERF401.py.snap index 11c02e0081e2f..33bb3e196e02d 100644 --- a/crates/ruff_linter/src/rules/perflint/snapshots/ruff_linter__rules__perflint__tests__preview__PERF401_PERF401.py.snap +++ b/crates/ruff_linter/src/rules/perflint/snapshots/ruff_linter__rules__perflint__tests__preview__PERF401_PERF401.py.snap @@ -10,13 +10,8 @@ PERF401 [*] Use a list comprehension to create a transformed list | ^^^^^^^^^^^^^^^^ help: Replace for loop with list comprehension | -2 | items = [1, 2, 3, 4] - - result = [] - - for i in items: - - if i % 2: - - result.append(i) # PERF401 -3 + result = [i for i in items if i % 2] # PERF401 -4 | +3 + +4 ~ result = [i for i in items if i % 2] # PERF401 | note: This is an unsafe fix and may change runtime behavior @@ -29,12 +24,8 @@ PERF401 [*] Use a list comprehension to create a transformed list | ^^^^^^^^^^^^^^^^^^^^ help: Replace for loop with list comprehension | -10 | items = [1, 2, 3, 4] - - result = [] - - for i in items: - - result.append(i * i) # PERF401 -11 + result = [i * i for i in items] # PERF401 -12 | +11 + +12 ~ result = [i * i for i in items] # PERF401 | note: This is an unsafe fix and may change runtime behavior @@ -47,13 +38,8 @@ PERF401 [*] Use an async list comprehension to create a transformed list | ^^^^^^^^^^^^^^^^ help: Replace for loop with list comprehension | -78 | items = [1, 2, 3, 4] - - result = [] - - async for i in items: - - if i % 2: - - result.append(i) # PERF401 -79 + result = [i async for i in items if i % 2] # PERF401 -80 | +79 + +80 ~ result = [i async for i in items if i % 2] # PERF401 | note: This is an unsafe fix and may change runtime behavior @@ -66,12 +52,8 @@ PERF401 [*] Use an async list comprehension to create a transformed list | ^^^^^^^^^^^^^^^^ help: Replace for loop with list comprehension | -86 | items = [1, 2, 3, 4] - - result = [] - - async for i in items: - - result.append(i) # PERF401 -87 + result = [i async for i in items] # PERF401 -88 | +87 + +88 ~ result = [i async for i in items] # PERF401 | note: This is an unsafe fix and may change runtime behavior @@ -84,11 +66,9 @@ PERF401 [*] Use `list.extend` with an async comprehension to create a transforme | ^^^^^^^^^^^^^^^^ help: Replace for loop with list.extend | -94 | result = [1, 2] - - async for i in items: - - result.append(i) # PERF401 +95 - async for i in items: +96 - result.append(i) # PERF401 95 + result.extend([i async for i in items]) # PERF401 -96 | | note: This is an unsafe fix and may change runtime behavior @@ -101,11 +81,9 @@ PERF401 [*] Use `list.extend` to create a transformed list | ^^^^^^^^^^^^^^^^^^^^ help: Replace for loop with list.extend | -100 | result, _ = [1, 2, 3, 4], ... - - for i in range(10): - - result.append(i * 2) # PERF401 +101 - for i in range(10): +102 - result.append(i * 2) # PERF401 101 + result.extend(i * 2 for i in range(10)) # PERF401 -102 | | note: This is an unsafe fix and may change runtime behavior @@ -118,16 +96,10 @@ PERF401 [*] Use `list.extend` to create a transformed list | ^^^^^^^^^^^^^^^^ help: Replace for loop with list.extend | -107 | if True: - - for i in range(10): # single-line comment 1 should be protected - - # single-line comment 2 should be protected - - if i % 2: # single-line comment 3 should be protected - - result.append(i) # PERF401 -108 + # single-line comment 1 should be protected +108 ~ # single-line comment 1 should be protected 109 + # single-line comment 2 should be protected 110 + # single-line comment 3 should be protected -111 + result.extend(i for i in range(10) if i % 2) # PERF401 -112 | +111 ~ result.extend(i for i in range(10) if i % 2) # PERF401 | note: This is an unsafe fix and may change runtime behavior @@ -140,18 +112,12 @@ PERF401 [*] Use a list comprehension to create a transformed list | ^^^^^^^^^^^^^^^^ help: Replace for loop with list comprehension | -114 | def f(): - - result = [] # comment after assignment should be protected - - for i in range(10): # single-line comment 1 should be protected - - # single-line comment 2 should be protected - - if i % 2: # single-line comment 3 should be protected - - result.append(i) # PERF401 -115 + # comment after assignment should be protected -116 + # single-line comment 1 should be protected -117 + # single-line comment 2 should be protected -118 + # single-line comment 3 should be protected -119 + result = [i for i in range(10) if i % 2] # PERF401 -120 | +115 + +116 ~ # comment after assignment should be protected +117 + # single-line comment 1 should be protected +118 + # single-line comment 2 should be protected +119 + # single-line comment 3 should be protected +120 ~ result = [i for i in range(10) if i % 2] # PERF401 | note: This is an unsafe fix and may change runtime behavior @@ -164,12 +130,8 @@ PERF401 [*] Use a list comprehension to create a transformed list | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace for loop with list comprehension | -132 | if param: - - new_layers = [] - - for value in param: - - new_layers.append(value * 3) -133 + new_layers = [value * 3 for value in param] -134 | +133 + +134 ~ new_layers = [value * 3 for value in param] | note: This is an unsafe fix and may change runtime behavior @@ -182,13 +144,9 @@ PERF401 [*] Use a list comprehension to create a transformed list | ^^^^^^^^^^^^^^^^^^^^^^ help: Replace for loop with list comprehension | -138 | def f(): - - result = [] -139 | var = 1 - - for _ in range(10): - - result.append(var + 1) # PERF401 -140 + result = [var + 1 for _ in range(10)] # PERF401 -141 | +139 + +140 | var = 1 +141 ~ result = [var + 1 for _ in range(10)] # PERF401 | note: This is an unsafe fix and may change runtime behavior @@ -201,13 +159,8 @@ PERF401 [*] Use a list comprehension to create a transformed list | ^^^^^^^^^^^^^^^^^^^^ help: Replace for loop with list comprehension | -146 | # make sure that `tmp` is not deleted - - tmp = 1; result = [] # comment should be protected - - for i in range(10): - - result.append(i + 1) # PERF401 -147 + tmp = 1 # comment should be protected -148 + result = [i + 1 for i in range(10)] # PERF401 -149 | +147 ~ tmp = 1 # comment should be protected +148 ~ result = [i + 1 for i in range(10)] # PERF401 | note: This is an unsafe fix and may change runtime behavior @@ -220,13 +173,8 @@ PERF401 [*] Use a list comprehension to create a transformed list | ^^^^^^^^^^^^^^^^^^^^ help: Replace for loop with list comprehension | -153 | # make sure that `tmp` is not deleted - - result = []; tmp = 1 # comment should be protected - - for i in range(10): - - result.append(i + 1) # PERF401 -154 + tmp = 1 # comment should be protected -155 + result = [i + 1 for i in range(10)] # PERF401 -156 | +154 ~ tmp = 1 # comment should be protected +155 ~ result = [i + 1 for i in range(10)] # PERF401 | note: This is an unsafe fix and may change runtime behavior @@ -239,13 +187,9 @@ PERF401 [*] Use a list comprehension to create a transformed list | ^^^^^^^^^^^^^^^^^^^^ help: Replace for loop with list comprehension | -159 | def f(): - - result = [] # comment should be protected - - for i in range(10): - - result.append(i * 2) # PERF401 -160 + # comment should be protected -161 + result = [i * 2 for i in range(10)] # PERF401 -162 | +160 + +161 ~ # comment should be protected +162 ~ result = [i * 2 for i in range(10)] # PERF401 | note: This is an unsafe fix and may change runtime behavior @@ -258,11 +202,9 @@ PERF401 [*] Use `list.extend` to create a transformed list | ^^^^^^^^^^^^^^^^^^^^ help: Replace for loop with list.extend | -167 | result.append(1) - - for i in range(10): - - result.append(i * 2) # PERF401 +168 - for i in range(10): +169 - result.append(i * 2) # PERF401 168 + result.extend(i * 2 for i in range(10)) # PERF401 -169 | | note: This is an unsafe fix and may change runtime behavior @@ -278,12 +220,8 @@ PERF401 [*] Use a list comprehension to create a transformed list | help: Replace for loop with list comprehension | -186 | def f(): - - result = [] - - for val in range(5): - - result.append(val * 2) # PERF401 -187 + result = [val * 2 for val in range(5)] # PERF401 -188 | val = 1 +187 + +188 ~ result = [val * 2 for val in range(5)] # PERF401 | note: This is an unsafe fix and may change runtime behavior @@ -296,12 +234,8 @@ PERF401 [*] Use a list comprehension to create a transformed list | ^^^^^^^^^^^^^^^^^^^^ help: Replace for loop with list comprehension | -195 | i = [1, 2, 3] - - result = [] - - for i in i: - - result.append(i + 1) # PERF401 -196 + result = [i + 1 for i in i] # PERF401 -197 | +196 + +197 ~ result = [i + 1 for i in i] # PERF401 | note: This is an unsafe fix and may change runtime behavior @@ -320,31 +254,19 @@ PERF401 [*] Use a list comprehension to create a transformed list | |_____________^ help: Replace for loop with list comprehension | -201 | def f(): - - result = [] - - for i in range( # Comment 1 should not be duplicated -202 + # Comment 3 -203 + # Comment 4 -204 + result = [( -205 + i + 1, -206 + # Comment 5 -207 + 2, -208 + ) for i in range( # Comment 1 should not be duplicated -209 | ( -210 | 2 # Comment 2 -211 | + 1 -212 | ) - - ): # Comment 3 - - if i % 2: # Comment 4 - - result.append( - - ( - - i + 1, - - # Comment 5 - - 2, - - ) - - ) # PERF401 -213 + ) if i % 2] # PERF401 -214 | +202 + +203 ~ # Comment 3 +204 + # Comment 4 +205 + result = [( +206 + i + 1, +207 + # Comment 5 +208 + 2, +209 + ) for i in range( # Comment 1 should not be duplicated +210 + ( +211 + 2 # Comment 2 +212 + + 1 +213 + ) +214 ~ ) if i % 2] # PERF401 | note: This is an unsafe fix and may change runtime behavior @@ -357,12 +279,8 @@ PERF401 [*] Use a list comprehension to create a transformed list | ^^^^^^^^^^^^^^^^^^^^ help: Replace for loop with list comprehension | -219 | def f(): - - result: list[int] = [] - - for i in range(10): - - result.append(i * 2) # PERF401 -220 + result: list[int] = [i * 2 for i in range(10)] # PERF401 -221 | +220 + +221 ~ result: list[int] = [i * 2 for i in range(10)] # PERF401 | note: This is an unsafe fix and may change runtime behavior @@ -377,12 +295,8 @@ PERF401 [*] Use a list comprehension to create a transformed list | help: Replace for loop with list comprehension | -226 | a, b = [1, 2, 3], [4, 5, 6] - - result = [] - - for i in a, b: - - result.append(i[0] + i[1]) # PERF401 -227 + result = [i[0] + i[1] for i in (a, b)] # PERF401 -228 | return result +227 + +228 ~ result = [i[0] + i[1] for i in (a, b)] # PERF401 | note: This is an unsafe fix and may change runtime behavior @@ -398,14 +312,10 @@ PERF401 [*] Use a list comprehension to create a transformed list | help: Replace for loop with list comprehension | -234 | values = [1, 2, 3] - - result = [] -235 | for a in values: -236 | print(a) - - for a in values: - - result.append(a + 1) # PERF401 -237 + result = [a + 1 for a in values] # PERF401 -238 | +235 + +236 | for a in values: +237 | print(a) +238 ~ result = [a + 1 for a in values] # PERF401 | note: This is an unsafe fix and may change runtime behavior @@ -420,11 +330,9 @@ PERF401 [*] Use `list.extend` to create a transformed list | help: Replace for loop with list.extend | -243 | def g(): - - for a in values: - - result.append(a + 1) # PERF401 +244 - for a in values: +245 - result.append(a + 1) # PERF401 244 + result.extend(a + 1 for a in values) # PERF401 -245 | result = [] | note: This is an unsafe fix and may change runtime behavior @@ -440,14 +348,9 @@ PERF401 [*] Use a list comprehension to create a transformed list | help: Replace for loop with list comprehension | -257 | def f(): - - items = [] -258 | - - for i in range(5): - - if j := i: - - items.append(j) -259 + items = [j for i in range(5) if (j := i)] -260 | +258 + +259 | +260 ~ items = [j for i in range(5) if (j := i)] | note: This is an unsafe fix and may change runtime behavior @@ -463,13 +366,9 @@ PERF401 [*] Use a list comprehension to create a transformed list | help: Replace for loop with list comprehension | -265 | values = [1, 2, 3] - - result = list() # this should be replaced with a comprehension - - for i in values: - - result.append(i + 1) # PERF401 -266 + # this should be replaced with a comprehension -267 + result = [i + 1 for i in values] # PERF401 -268 | +266 + +267 ~ # this should be replaced with a comprehension +268 ~ result = [i + 1 for i in values] # PERF401 | note: This is an unsafe fix and may change runtime behavior @@ -485,14 +384,9 @@ PERF401 [*] Use a list comprehension to create a transformed list | help: Replace for loop with list comprehension | -271 | src = [1] - - dst = [] -272 | - - for i in src: - - if True if True else False: - - dst.append(i) -273 + dst = [i for i in src if (True if True else False)] -274 | +272 + +273 | +274 ~ dst = [i for i in src if (True if True else False)] | note: This is an unsafe fix and may change runtime behavior @@ -508,12 +402,10 @@ PERF401 [*] Use `list.extend` to create a transformed list | help: Replace for loop with list.extend | -277 | - - for i in src: - - if lambda: 0: - - dst.append(i) +278 - for i in src: +279 - if lambda: 0: +280 - dst.append(i) 278 + dst.extend(i for i in src if (lambda: 0)) -279 | | note: This is an unsafe fix and may change runtime behavior @@ -529,12 +421,8 @@ PERF401 [*] Use a list comprehension to create a transformed list | help: Replace for loop with list comprehension | -283 | i = "xyz" - - result = [] - - for i in range(3): - - result.append(x for x in [i]) -284 + result = [(x for x in [i]) for i in range(3)] -285 | +284 + +285 ~ result = [(x for x in [i]) for i in range(3)] | note: This is an unsafe fix and may change runtime behavior @@ -550,12 +438,8 @@ PERF401 [*] Use a list comprehension to create a transformed list | help: Replace for loop with list comprehension | -289 | i = "xyz" - - result = [] - - for i in range(3): - - result.append((x for x in [i])) -290 + result = [(x for x in [i]) for i in range(3)] -291 | +290 + +291 ~ result = [(x for x in [i]) for i in range(3)] | note: This is an unsafe fix and may change runtime behavior @@ -571,17 +455,9 @@ PERF401 [*] Use a list comprehension to create a transformed list | help: Replace for loop with list comprehension | -311 | original = list(range(10000)) - - filtered = [] - - for i in original: - - if ( - - i - - # comment - - ): - - filtered.append(i) -312 + # comment -313 + filtered = [i for i in original if i] -314 | +312 + +313 ~ # comment +314 + filtered = [i for i in original if i] | note: This is an unsafe fix and may change runtime behavior @@ -594,14 +470,8 @@ PERF401 [*] Use a list comprehension to create a transformed list | ^^^^^^^^^^^^^^^^^^ help: Replace for loop with list comprehension | -322 | original = list(range(10000)) - - filtered = [] - - for ( - - i # comment - - ) in original: - - if i > 0: - - filtered.append(i) -323 + # comment -324 + filtered = [i for i in original if i > 0] +323 + +324 ~ # comment +325 + filtered = [i for i in original if i > 0] | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/perflint/snapshots/ruff_linter__rules__perflint__tests__preview__PERF403_PERF403.py.snap b/crates/ruff_linter/src/rules/perflint/snapshots/ruff_linter__rules__perflint__tests__preview__PERF403_PERF403.py.snap index df2817b12dd29..75c7ff29c89f6 100644 --- a/crates/ruff_linter/src/rules/perflint/snapshots/ruff_linter__rules__perflint__tests__preview__PERF403_PERF403.py.snap +++ b/crates/ruff_linter/src/rules/perflint/snapshots/ruff_linter__rules__perflint__tests__preview__PERF403_PERF403.py.snap @@ -10,12 +10,8 @@ PERF403 [*] Use a dictionary comprehension instead of a for-loop | ^^^^^^^^^^^^^^^^^^ help: Replace for loop with dict comprehension | -2 | fruit = ["apple", "pear", "orange"] - - result = {} - - for idx, name in enumerate(fruit): - - result[idx] = name # PERF403 -3 + result = {idx: name for idx, name in enumerate(fruit)} # PERF403 -4 | +3 + +4 ~ result = {idx: name for idx, name in enumerate(fruit)} # PERF403 | note: This is an unsafe fix and may change runtime behavior @@ -28,13 +24,8 @@ PERF403 [*] Use a dictionary comprehension instead of a for-loop | ^^^^^^^^^^^^^^^^^^ help: Replace for loop with dict comprehension | -9 | fruit = ["apple", "pear", "orange"] - - result = {} - - for idx, name in enumerate(fruit): - - if idx % 2: - - result[idx] = name # PERF403 -10 + result = {idx: name for idx, name in enumerate(fruit) if idx % 2} # PERF403 -11 | +10 + +11 ~ result = {idx: name for idx, name in enumerate(fruit) if idx % 2} # PERF403 | note: This is an unsafe fix and may change runtime behavior @@ -47,14 +38,9 @@ PERF403 [*] Use a dictionary comprehension instead of a for-loop | ^^^^^^^^^^^^^^^^^^ help: Replace for loop with dict comprehension | -28 | def foo(): - - result = {} -29 | fruit = ["apple", "pear", "orange"] - - for idx, name in enumerate(fruit): - - if idx % 2: - - result[idx] = name # PERF403 -30 + result = {idx: name for idx, name in enumerate(fruit) if idx % 2} # PERF403 -31 | +29 + +30 | fruit = ["apple", "pear", "orange"] +31 ~ result = {idx: name for idx, name in enumerate(fruit) if idx % 2} # PERF403 | note: This is an unsafe fix and may change runtime behavior @@ -67,12 +53,10 @@ PERF403 [*] Use `dict.update` instead of a for-loop | ^^^^^^^^^^^^^^^^^^ help: Replace for loop with `dict.update` | -60 | fruit = ["apple", "pear", "orange"] - - for idx, name in enumerate(fruit): - - if idx % 2: - - result[idx] = name # PERF403 +61 - for idx, name in enumerate(fruit): +62 - if idx % 2: +63 - result[idx] = name # PERF403 61 + result.update({idx: name for idx, name in enumerate(fruit) if idx % 2}) # PERF403 -62 | | note: This is an unsafe fix and may change runtime behavior @@ -85,12 +69,8 @@ PERF403 [*] Use a dictionary comprehension instead of a for-loop | ^^^^^^^^^^^^^^^^^^^ help: Replace for loop with dict comprehension | -75 | fruit = ["apple", "pear", "orange"] - - result = {} - - for name in fruit: - - result[name] = name # PERF403 -76 + result = {name: name for name in fruit} # PERF403 -77 | +76 + +77 ~ result = {name: name for name in fruit} # PERF403 | note: This is an unsafe fix and may change runtime behavior @@ -103,12 +83,8 @@ PERF403 [*] Use a dictionary comprehension instead of a for-loop | ^^^^^^^^^^^^^^^^^^ help: Replace for loop with dict comprehension | -82 | fruit = ["apple", "pear", "orange"] - - result = {} - - for idx, name in enumerate(fruit): - - result[name] = idx # PERF403 -83 + result = {name: idx for idx, name in enumerate(fruit)} # PERF403 -84 | +83 + +84 ~ result = {name: idx for idx, name in enumerate(fruit)} # PERF403 | note: This is an unsafe fix and may change runtime behavior @@ -121,12 +97,8 @@ PERF403 [*] Use a dictionary comprehension instead of a for-loop | ^^^^^^^^^^^^^^^^^^ help: Replace for loop with dict comprehension | -91 | fruit = ["apple", "pear", "orange"] - - result = SneakyDict() - - for idx, name in enumerate(fruit): - - result[name] = idx # PERF403 -92 + result = {name: idx for idx, name in enumerate(fruit)} # PERF403 -93 | +92 + +93 ~ result = {name: idx for idx, name in enumerate(fruit)} # PERF403 | note: This is an unsafe fix and may change runtime behavior @@ -141,23 +113,13 @@ PERF403 [*] Use a dictionary comprehension instead of a for-loop | |_______________^ help: Replace for loop with dict comprehension | -98 | fruit = ["apple", "pear", "orange"] - - result: dict[str, int] = { - - # comment 1 - - } - - for idx, name in enumerate( -99 + # comment 1 -100 + # comment 3 -101 + # comment 4 -102 + result: dict[str, int] = {name: idx for idx, name in enumerate( -103 | fruit # comment 2 - - ): - - # comment 3 - - result[ - - name # comment 4 - - ] = idx # PERF403 -104 + )} # PERF403 -105 | + 99 + +100 ~ # comment 1 +101 + # comment 3 +102 + # comment 4 +103 + result: dict[str, int] = {name: idx for idx, name in enumerate( +104 + fruit # comment 2 +105 ~ )} # PERF403 | note: This is an unsafe fix and may change runtime behavior @@ -170,13 +132,8 @@ PERF403 [*] Use a dictionary comprehension instead of a for-loop | ^^^^^^^^^^^^^^^^^^ help: Replace for loop with dict comprehension | -112 | fruit = ["apple", "pear", "orange"] - - a = 1; result = {}; b = 2 - - for idx, name in enumerate(fruit): - - result[name] = idx # PERF403 -113 + a = 1; b = 2 -114 + result = {name: idx for idx, name in enumerate(fruit)} # PERF403 -115 | +113 ~ a = 1; b = 2 +114 ~ result = {name: idx for idx, name in enumerate(fruit)} # PERF403 | note: This is an unsafe fix and may change runtime behavior @@ -189,11 +146,9 @@ PERF403 [*] Use `dict.update` instead of a for-loop | ^^^^^^^^^^^^^^^^^^ help: Replace for loop with `dict.update` | -120 | result = {"kiwi": 3} - - for idx, name in enumerate(fruit): - - result[name] = idx # PERF403 +121 - for idx, name in enumerate(fruit): +122 - result[name] = idx # PERF403 121 + result.update({name: idx for idx, name in enumerate(fruit)}) # PERF403 -122 | | note: This is an unsafe fix and may change runtime behavior @@ -206,11 +161,9 @@ PERF403 [*] Use `dict.update` instead of a for-loop | ^^^^^^^^^^^^^^^^^^ help: Replace for loop with `dict.update` | -127 | (_, result) = (None, {"kiwi": 3}) - - for idx, name in enumerate(fruit): - - result[name] = idx # PERF403 +128 - for idx, name in enumerate(fruit): +129 - result[name] = idx # PERF403 128 + result.update({name: idx for idx, name in enumerate(fruit)}) # PERF403 -129 | | note: This is an unsafe fix and may change runtime behavior @@ -223,11 +176,9 @@ PERF403 [*] Use `dict.update` instead of a for-loop | ^^^^^^^^^^^^^^^^^^ help: Replace for loop with `dict.update` | -135 | print(len(result)) - - for idx, name in enumerate(fruit): - - result[name] = idx # PERF403 +136 - for idx, name in enumerate(fruit): +137 - result[name] = idx # PERF403 136 + result.update({name: idx for idx, name in enumerate(fruit)}) # PERF403 -137 | | note: This is an unsafe fix and may change runtime behavior @@ -240,13 +191,8 @@ PERF403 [*] Use a dictionary comprehension instead of a for-loop | ^^^^^^^^^^^^^^^^^^ help: Replace for loop with dict comprehension | -141 | fruit = ["apple", "pear", "orange"] - - result = {} - - for idx, name in enumerate(fruit): - - if last_idx := idx % 3: - - result[name] = idx # PERF403 -142 + result = {name: idx for idx, name in enumerate(fruit) if (last_idx := idx % 3)} # PERF403 -143 | +142 + +143 ~ result = {name: idx for idx, name in enumerate(fruit) if (last_idx := idx % 3)} # PERF403 | note: This is an unsafe fix and may change runtime behavior @@ -259,12 +205,8 @@ PERF403 [*] Use a dictionary comprehension instead of a for-loop | ^^^^^^^^^^^^^^^^^^ help: Replace for loop with dict comprehension | -150 | indices = [0, 1, 2] - - result = {} - - for idx, name in indices, fruit: - - result[name] = idx # PERF403 -151 + result = {name: idx for idx, name in (indices, fruit)} # PERF403 -152 | +151 + +152 ~ result = {name: idx for idx, name in (indices, fruit)} # PERF403 | note: This is an unsafe fix and may change runtime behavior @@ -280,14 +222,9 @@ PERF403 [*] Use a dictionary comprehension instead of a for-loop | help: Replace for loop with dict comprehension | -157 | src = (("x", 1),) - - dst = {} -158 | - - for k, v in src: - - if True if True else False: - - dst[k] = v -159 + dst = {k: v for k, v in src if (True if True else False)} -160 | +158 + +159 | +160 ~ dst = {k: v for k, v in src if (True if True else False)} | note: This is an unsafe fix and may change runtime behavior @@ -303,12 +240,10 @@ PERF403 [*] Use `dict.update` instead of a for-loop | help: Replace for loop with `dict.update` | -163 | - - for k, v in src: - - if lambda: 0: - - dst[k] = v +164 - for k, v in src: +165 - if lambda: 0: +166 - dst[k] = v 164 + dst.update({k: v for k, v in src if (lambda: 0)}) -165 | | note: This is an unsafe fix and may change runtime behavior @@ -321,12 +256,8 @@ PERF403 [*] Use a dictionary comprehension instead of a for-loop | ^^^^^^^ help: Replace for loop with dict comprehension | -169 | def foo(): - - v = {} - - for o,(x,)in(): - - v[x,]=o -170 + v = {(x,): o for o,(x,) in ()} -171 | +170 + +171 ~ v = {(x,): o for o,(x,) in ()} | note: This is an unsafe fix and may change runtime behavior @@ -341,12 +272,8 @@ PERF403 [*] Use a dictionary comprehension instead of a for-loop | help: Replace for loop with dict comprehension | -197 | def issue_19153_1(): - - v = {} - - for o, (x,) in ["ox"]: - - v[x,] = o -198 + v = {(x,): o for o, (x,) in ["ox"]} -199 | return v +198 + +199 ~ v = {(x,): o for o, (x,) in ["ox"]} | note: This is an unsafe fix and may change runtime behavior @@ -361,12 +288,8 @@ PERF403 [*] Use a dictionary comprehension instead of a for-loop | help: Replace for loop with dict comprehension | -204 | def issue_19153_2(): - - v = {} - - for (o, p), x in [("op", "x")]: - - v[x] = o, p -205 + v = {x: (o, p) for (o, p), x in [("op", "x")]} -206 | return v +205 + +206 ~ v = {x: (o, p) for (o, p), x in [("op", "x")]} | note: This is an unsafe fix and may change runtime behavior @@ -381,12 +304,8 @@ PERF403 [*] Use a dictionary comprehension instead of a for-loop | help: Replace for loop with dict comprehension | -211 | def issue_19153_3(): - - v = {} - - for o, (x,) in ["ox"]: - - v[(x,)] = o -212 + v = {(x,): o for o, (x,) in ["ox"]} -213 | return v +212 + +213 ~ v = {(x,): o for o, (x,) in ["ox"]} | note: This is an unsafe fix and may change runtime behavior @@ -402,17 +321,9 @@ PERF403 [*] Use a dictionary comprehension instead of a for-loop | help: Replace for loop with dict comprehension | -218 | # comment duplication in if test (https://github.com/astral-sh/ruff/issues/18787) - - result = {} - - for k in ["a", "b", "c"]: - - if ( - - k - - # comment - - ): - - result[k] = k -219 + # comment -220 + result = {k: k for k in ["a", "b", "c"] if k} -221 | +219 + +220 ~ # comment +221 + result = {k: k for k in ["a", "b", "c"] if k} | note: This is an unsafe fix and may change runtime behavior @@ -425,13 +336,8 @@ PERF403 [*] Use a dictionary comprehension instead of a for-loop | ^^^^^^^^^^^^^ help: Replace for loop with dict comprehension | -228 | # comment duplication in target (https://github.com/astral-sh/ruff/issues/18787) - - result = {} - - for ( - - k # comment - - ) in ["a", "b", "c"]: - - result[k] = k -229 + # comment -230 + result = {k: k for k in ["a", "b", "c"]} +229 + +230 ~ # comment +231 + result = {k: k for k in ["a", "b", "c"]} | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E201_E20.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E201_E20.py.snap index 2086d815c036b..b4712b3d2c0e9 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E201_E20.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E201_E20.py.snap @@ -12,10 +12,7 @@ E201 [*] Whitespace after '(' | help: Remove whitespace before '(' | -1 | #: E201:1:6 - - spam( ham[1], {eggs: 2}) -2 + spam(ham[1], {eggs: 2}) -3 | #: E201:1:10 +2 | spam(ham[1], {eggs: 2}) | E201 [*] Whitespace after '[' @@ -30,10 +27,7 @@ E201 [*] Whitespace after '[' | help: Remove whitespace before '[' | -3 | #: E201:1:10 - - spam(ham[ 1], {eggs: 2}) -4 + spam(ham[1], {eggs: 2}) -5 | #: E201:1:15 +4 | spam(ham[1], {eggs: 2}) | E201 [*] Whitespace after '{' @@ -48,10 +42,7 @@ E201 [*] Whitespace after '{' | help: Remove whitespace before '{' | -5 | #: E201:1:15 - - spam(ham[1], { eggs: 2}) -6 + spam(ham[1], {eggs: 2}) -7 | #: E201:1:6 +6 | spam(ham[1], {eggs: 2}) | E201 [*] Whitespace after '(' @@ -66,10 +57,7 @@ E201 [*] Whitespace after '(' | help: Remove whitespace before '(' | -7 | #: E201:1:6 - - spam( ham[1], {eggs: 2}) -8 + spam(ham[1], {eggs: 2}) -9 | #: E201:1:10 +8 | spam(ham[1], {eggs: 2}) | E201 [*] Whitespace after '[' @@ -84,10 +72,7 @@ E201 [*] Whitespace after '[' | help: Remove whitespace before '[' | -9 | #: E201:1:10 - - spam(ham[ 1], {eggs: 2}) -10 + spam(ham[1], {eggs: 2}) -11 | #: E201:1:15 +10 | spam(ham[1], {eggs: 2}) | E201 [*] Whitespace after '{' @@ -102,10 +87,7 @@ E201 [*] Whitespace after '{' | help: Remove whitespace before '{' | -11 | #: E201:1:15 - - spam(ham[1], { eggs: 2}) -12 + spam(ham[1], {eggs: 2}) -13 | #: Okay +12 | spam(ham[1], {eggs: 2}) | E201 [*] Whitespace after '[' @@ -119,10 +101,7 @@ E201 [*] Whitespace after '[' | help: Remove whitespace before '[' | -106 | #: E201:1:6 - - spam[ ~ham] -107 + spam[~ham] -108 | +107 | spam[~ham] | E201 [*] Whitespace after '[' @@ -136,10 +115,7 @@ E201 [*] Whitespace after '[' | help: Remove whitespace before '[' | -115 | f"{ {'a': 1} }" - - f"{[ { {'a': 1} } ]}" -116 + f"{[{ {'a': 1} } ]}" -117 | f"normal { {f"{ { [1, 2] } }" } } normal" +116 | f"{[{ {'a': 1} } ]}" | E201 [*] Whitespace after '[' @@ -153,10 +129,7 @@ E201 [*] Whitespace after '[' | help: Remove whitespace before '[' | -144 | #: E201:1:5 - - ham[ : upper] -145 + ham[: upper] -146 | +145 | ham[: upper] | E201 [*] Whitespace after '[' @@ -170,8 +143,5 @@ E201 [*] Whitespace after '[' | help: Remove whitespace before '[' | -194 | t"{ {'a': 1} }" - - t"{[ { {'a': 1} } ]}" -195 + t"{[{ {'a': 1} } ]}" -196 | t"normal { {t"{ { [1, 2] } }" } } normal" +195 | t"{[{ {'a': 1} } ]}" | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E202_E20.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E202_E20.py.snap index eec8cd1fb4cb5..f024dd0699036 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E202_E20.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E202_E20.py.snap @@ -12,10 +12,7 @@ E202 [*] Whitespace before ')' | help: Remove whitespace before ')' | -18 | #: E202:1:23 - - spam(ham[1], {eggs: 2} ) -19 + spam(ham[1], {eggs: 2}) -20 | #: E202:1:22 +19 | spam(ham[1], {eggs: 2}) | E202 [*] Whitespace before '}' @@ -30,10 +27,7 @@ E202 [*] Whitespace before '}' | help: Remove whitespace before '}' | -20 | #: E202:1:22 - - spam(ham[1], {eggs: 2 }) -21 + spam(ham[1], {eggs: 2}) -22 | #: E202:1:11 +21 | spam(ham[1], {eggs: 2}) | E202 [*] Whitespace before ']' @@ -48,10 +42,7 @@ E202 [*] Whitespace before ']' | help: Remove whitespace before ']' | -22 | #: E202:1:11 - - spam(ham[1 ], {eggs: 2}) -23 + spam(ham[1], {eggs: 2}) -24 | #: E202:1:23 +23 | spam(ham[1], {eggs: 2}) | E202 [*] Whitespace before ')' @@ -66,10 +57,7 @@ E202 [*] Whitespace before ')' | help: Remove whitespace before ')' | -24 | #: E202:1:23 - - spam(ham[1], {eggs: 2} ) -25 + spam(ham[1], {eggs: 2}) -26 | #: E202:1:22 +25 | spam(ham[1], {eggs: 2}) | E202 [*] Whitespace before '}' @@ -84,10 +72,7 @@ E202 [*] Whitespace before '}' | help: Remove whitespace before '}' | -26 | #: E202:1:22 - - spam(ham[1], {eggs: 2 }) -27 + spam(ham[1], {eggs: 2}) -28 | #: E202:1:11 +27 | spam(ham[1], {eggs: 2}) | E202 [*] Whitespace before ']' @@ -102,10 +87,7 @@ E202 [*] Whitespace before ']' | help: Remove whitespace before ']' | -28 | #: E202:1:11 - - spam(ham[1 ], {eggs: 2}) -29 + spam(ham[1], {eggs: 2}) -30 | #: Okay +29 | spam(ham[1], {eggs: 2}) | E202 [*] Whitespace before ']' @@ -119,10 +101,7 @@ E202 [*] Whitespace before ']' | help: Remove whitespace before ']' | -115 | f"{ {'a': 1} }" - - f"{[ { {'a': 1} } ]}" -116 + f"{[ { {'a': 1} }]}" -117 | f"normal { {f"{ { [1, 2] } }" } } normal" +116 | f"{[ { {'a': 1} }]}" | E202 [*] Whitespace before ']' @@ -136,10 +115,7 @@ E202 [*] Whitespace before ']' | help: Remove whitespace before ']' | -171 | #: E202:1:12 - - ham[upper : ] -172 + ham[upper :] -173 | +172 | ham[upper :] | E202 [*] Whitespace before ']' @@ -153,8 +129,5 @@ E202 [*] Whitespace before ']' | help: Remove whitespace before ']' | -194 | t"{ {'a': 1} }" - - t"{[ { {'a': 1} } ]}" -195 + t"{[ { {'a': 1} }]}" -196 | t"normal { {t"{ { [1, 2] } }" } } normal" +195 | t"{[ { {'a': 1} }]}" | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E203_E20.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E203_E20.py.snap index b410c5738c60b..9c8b270221337 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E203_E20.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E203_E20.py.snap @@ -12,10 +12,7 @@ E203 [*] Whitespace before ':' | help: Remove whitespace before ':' | -50 | #: E203:1:10 - - if x == 4 : -51 + if x == 4: -52 | print(x, y) +51 | if x == 4: | E203 [*] Whitespace before ':' @@ -30,10 +27,7 @@ E203 [*] Whitespace before ':' | help: Remove whitespace before ':' | -54 | #: E203:1:10 - - if x == 4 : -55 + if x == 4: -56 | print(x, y) +55 | if x == 4: | E203 [*] Whitespace before ';' @@ -48,10 +42,7 @@ E203 [*] Whitespace before ';' | help: Remove whitespace before ';' | -59 | if x == 4: - - print(x, y) ; x, y = y, x -60 + print(x, y); x, y = y, x -61 | #: E203:2:15 E702:2:16 +60 | print(x, y); x, y = y, x | E203 [*] Whitespace before ';' @@ -66,10 +57,7 @@ E203 [*] Whitespace before ';' | help: Remove whitespace before ';' | -62 | if x == 4: - - print(x, y) ; x, y = y, x -63 + print(x, y); x, y = y, x -64 | #: E203:3:13 +63 | print(x, y); x, y = y, x | E203 [*] Whitespace before ',' @@ -84,10 +72,7 @@ E203 [*] Whitespace before ',' | help: Remove whitespace before ',' | -66 | print(x, y) - - x, y = y , x -67 + x, y = y, x -68 | #: E203:3:13 +67 | x, y = y, x | E203 [*] Whitespace before ',' @@ -102,10 +87,7 @@ E203 [*] Whitespace before ',' | help: Remove whitespace before ',' | -70 | print(x, y) - - x, y = y , x -71 + x, y = y, x -72 | #: Okay +71 | x, y = y, x | E203 [*] Whitespace before ':' @@ -119,11 +101,8 @@ E203 [*] Whitespace before ':' | help: Remove whitespace before ':' | -85 | predictions = predictions[ - - len(past_covariates) // datamodule.hparams["downsample"] : -86 + len(past_covariates) // datamodule.hparams["downsample"] : -87 | ] - | +86 | len(past_covariates) // datamodule.hparams["downsample"] : + | + E203 [*] Whitespace before ':' --> E20.py:91:61 @@ -136,11 +115,8 @@ E203 [*] Whitespace before ':' | help: Remove whitespace before ':' | -90 | predictions = predictions[ - - len(past_covariates) // datamodule.hparams["downsample"] : -91 + len(past_covariates) // datamodule.hparams["downsample"] : -92 | ] - | +91 | len(past_covariates) // datamodule.hparams["downsample"] : + | + E203 [*] Whitespace before ':' --> E20.py:101:61 @@ -153,11 +129,8 @@ E203 [*] Whitespace before ':' | help: Remove whitespace before ':' | -100 | predictions = predictions[ - - len(past_covariates) // datamodule.hparams["downsample"] : # Just some comment -101 + len(past_covariates) // datamodule.hparams["downsample"] : # Just some comment -102 | ] - | +101 | len(past_covariates) // datamodule.hparams["downsample"] : # Just some comment + | + E203 [*] Whitespace before ':' --> E20.py:126:16 @@ -170,10 +143,7 @@ E203 [*] Whitespace before ':' | help: Remove whitespace before ':' | -125 | #: E203:1:19 - - {lower + offset : upper + offset} -126 + {lower + offset: upper + offset} -127 | +126 | {lower + offset: upper + offset} | E203 [*] Whitespace before ':' @@ -187,10 +157,7 @@ E203 [*] Whitespace before ':' | help: Remove whitespace before ':' | -128 | #: E203:1:19 - - ham[lower + offset : upper + offset] -129 + ham[lower + offset: upper + offset] -130 | +129 | ham[lower + offset: upper + offset] | E203 [*] Whitespace before ':' @@ -204,10 +171,7 @@ E203 [*] Whitespace before ':' | help: Remove whitespace before ':' | -156 | #: E203:1:21 - - ham[lower + offset : : upper + offset] -157 + ham[lower + offset :: upper + offset] -158 | +157 | ham[lower + offset :: upper + offset] | E203 [*] Whitespace before ':' @@ -221,10 +185,7 @@ E203 [*] Whitespace before ':' | help: Remove whitespace before ':' | -159 | #: E203:1:20 - - ham[lower + offset: :upper + offset] -160 + ham[lower + offset::upper + offset] -161 | +160 | ham[lower + offset::upper + offset] | E203 [*] Whitespace before ':' @@ -238,10 +199,7 @@ E203 [*] Whitespace before ':' | help: Remove whitespace before ':' | -162 | #: E203:1:20 - - ham[{lower + offset : upper + offset} : upper + offset] -163 + ham[{lower + offset: upper + offset} : upper + offset] -164 | +163 | ham[{lower + offset: upper + offset} : upper + offset] | E203 [*] Whitespace before ':' @@ -255,10 +213,7 @@ E203 [*] Whitespace before ':' | help: Remove whitespace before ':' | -174 | #: E203:1:10 - - ham[upper :] -175 + ham[upper:] -176 | +175 | ham[upper:] | E203 [*] Whitespace before ':' @@ -272,10 +227,7 @@ E203 [*] Whitespace before ':' | help: Remove whitespace before ':' | -180 | #: E203:1:13 - - ham[lower + 1 :, "columnname"] -181 + ham[lower + 1:, "columnname"] -182 | +181 | ham[lower + 1:, "columnname"] | E203 [*] Whitespace before ':' @@ -289,10 +241,7 @@ E203 [*] Whitespace before ':' | help: Remove whitespace before ':' | -186 | #: E203:1:13 - - f"{ham[lower + 1 :, "columnname"]}" -187 + f"{ham[lower + 1:, "columnname"]}" -188 | +187 | f"{ham[lower + 1:, "columnname"]}" | E203 [*] Whitespace before ':' @@ -303,8 +252,5 @@ E203 [*] Whitespace before ':' | ^^ help: Remove whitespace before ':' | -204 | #: E203:1:13 - - t"{ham[lower + 1 :, "columnname"]}" -205 + t"{ham[lower + 1:, "columnname"]}" -206 | +205 | t"{ham[lower + 1:, "columnname"]}" | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E204_E204.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E204_E204.py.snap index 293957f8e351d..a92eb8d56a670 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E204_E204.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E204_E204.py.snap @@ -12,10 +12,7 @@ E204 [*] Whitespace after decorator | help: Remove whitespace | -13 | # E204 - - @ foo -14 + @foo -15 | def baz(): +14 | @foo | E204 [*] Whitespace after decorator @@ -29,10 +26,7 @@ E204 [*] Whitespace after decorator | help: Remove whitespace | -24 | # E204 - - @ foo -25 + @foo -26 | def baz(self): +25 | @foo | E204 [*] Whitespace after decorator @@ -46,9 +40,7 @@ E204 [*] Whitespace after decorator | help: Remove whitespace | -30 | # E204 - - @ \ - - foo -31 + @foo -32 | def baz(): +31 - @ \ +32 - foo +31 + @ | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E211_E21.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E211_E21.py.snap index bb4546612da9c..5645a401fbec7 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E211_E21.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E211_E21.py.snap @@ -12,10 +12,7 @@ E211 [*] Whitespace before '(' | help: Removed whitespace before '(' | -1 | #: E211 - - spam (1) -2 + spam(1) -3 | #: E211 E211 +2 | spam(1) | E211 [*] Whitespace before '[' @@ -30,10 +27,7 @@ E211 [*] Whitespace before '[' | help: Removed whitespace before '[' | -3 | #: E211 E211 - - dict ['key'] = list [index] -4 + dict['key'] = list [index] -5 | #: E211 +4 | dict['key'] = list [index] | E211 [*] Whitespace before '[' @@ -48,10 +42,7 @@ E211 [*] Whitespace before '[' | help: Removed whitespace before '[' | -3 | #: E211 E211 - - dict ['key'] = list [index] -4 + dict ['key'] = list[index] -5 | #: E211 +4 | dict ['key'] = list[index] | E211 [*] Whitespace before '[' @@ -66,10 +57,7 @@ E211 [*] Whitespace before '[' | help: Removed whitespace before '[' | -5 | #: E211 - - dict['key'] ['subkey'] = list[index] -6 + dict['key']['subkey'] = list[index] -7 | #: Okay +6 | dict['key']['subkey'] = list[index] | E211 [*] Whitespace before '(' @@ -81,10 +69,7 @@ E211 [*] Whitespace before '(' | help: Removed whitespace before '(' | -16 | - - def fetch_name () -> Union[str, None]: -17 + def fetch_name() -> Union[str, None]: -18 | """Fetch name from --person-name in sys.argv. +17 | def fetch_name() -> Union[str, None]: | E211 [*] Whitespace before '(' @@ -99,10 +84,7 @@ E211 [*] Whitespace before '(' | help: Removed whitespace before '(' | -26 | # Logger.info("test code") - - for i in range (0, len (sys.argv)) : -27 + for i in range(0, len (sys.argv)) : -28 | if sys.argv[i] == "--name" : +27 | for i in range(0, len (sys.argv)) : | E211 [*] Whitespace before '(' @@ -117,8 +99,5 @@ E211 [*] Whitespace before '(' | help: Removed whitespace before '(' | -26 | # Logger.info("test code") - - for i in range (0, len (sys.argv)) : -27 + for i in range (0, len(sys.argv)) : -28 | if sys.argv[i] == "--name" : +27 | for i in range (0, len(sys.argv)) : | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E221_E22.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E221_E22.py.snap index acecfeb505119..51d6392726086 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E221_E22.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E221_E22.py.snap @@ -13,11 +13,8 @@ E221 [*] Multiple spaces before operator | help: Replace with single space | -2 | a = 12 + 3 - - b = 4 + 5 -3 + b = 4 + 5 -4 | #: E221 E221 - | +3 | b = 4 + 5 + | + E221 [*] Multiple spaces before operator --> E22.py:5:2 @@ -31,11 +28,8 @@ E221 [*] Multiple spaces before operator | help: Replace with single space | -4 | #: E221 E221 - - x = 1 -5 + x = 1 -6 | y = 2 - | +5 | x = 1 + | + E221 [*] Multiple spaces before operator --> E22.py:6:2 @@ -49,11 +43,8 @@ E221 [*] Multiple spaces before operator | help: Replace with single space | -5 | x = 1 - - y = 2 -6 + y = 2 -7 | long_variable = 3 - | +6 | y = 2 + | + E221 [*] Multiple spaces before operator --> E22.py:9:5 @@ -66,12 +57,9 @@ E221 [*] Multiple spaces before operator 11 | long_variable = 3 | help: Replace with single space - | -8 | #: E221 E221 - - x[0] = 1 -9 + x[0] = 1 -10 | x[1] = 2 - | + | +9 | x[0] = 1 + | + E221 [*] Multiple spaces before operator --> E22.py:10:5 @@ -85,11 +73,8 @@ E221 [*] Multiple spaces before operator | help: Replace with single space | -9 | x[0] = 1 - - x[1] = 2 -10 + x[1] = 2 -11 | long_variable = 3 - | +10 | x[1] = 2 + | + E221 [*] Multiple spaces before operator --> E22.py:13:9 @@ -103,11 +88,8 @@ E221 [*] Multiple spaces before operator | help: Replace with single space | -12 | #: E221 E221 - - x = f(x) + 1 -13 + x = f(x) + 1 -14 | y = long_variable + 2 - | +13 | x = f(x) + 1 + | + E221 [*] Multiple spaces before operator --> E22.py:15:9 @@ -121,11 +103,8 @@ E221 [*] Multiple spaces before operator | help: Replace with single space | -14 | y = long_variable + 2 - - z = x[0] + 3 -15 + z = x[0] + 3 -16 | #: E221:3:14 - | +15 | z = x[0] + 3 + | + E221 [*] Multiple spaces before operator --> E22.py:19:14 @@ -139,11 +118,8 @@ E221 [*] Multiple spaces before operator | help: Replace with single space | -18 | bar - - foo %s""" % rofl -19 + foo %s""" % rofl -20 | #: Okay - | +19 | foo %s""" % rofl + | + E221 [*] Multiple spaces before operator --> E22.py:184:5 @@ -156,8 +132,5 @@ E221 [*] Multiple spaces before operator | help: Replace with single space | -183 | - - if a == 1: -184 + if a == 1: -185 | print(a) - | +184 | if a == 1: + | + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E222_E22.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E222_E22.py.snap index 1954838d904a4..53638ede1f9e7 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E222_E22.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E222_E22.py.snap @@ -12,11 +12,8 @@ E222 [*] Multiple spaces after operator | help: Replace with single space | -27 | #: E222 - - a = a + 1 -28 + a = a + 1 -29 | b = b + 10 - | +28 | a = a + 1 + | + E222 [*] Multiple spaces after operator --> E22.py:31:4 @@ -30,11 +27,8 @@ E222 [*] Multiple spaces after operator | help: Replace with single space | -30 | #: E222 E222 - - x = -1 -31 + x = -1 -32 | y = -2 - | +31 | x = -1 + | + E222 [*] Multiple spaces after operator --> E22.py:32:4 @@ -48,11 +42,8 @@ E222 [*] Multiple spaces after operator | help: Replace with single space | -31 | x = -1 - - y = -2 -32 + y = -2 -33 | long_variable = 3 - | +32 | y = -2 + | + E222 [*] Multiple spaces after operator --> E22.py:35:7 @@ -66,11 +57,8 @@ E222 [*] Multiple spaces after operator | help: Replace with single space | -34 | #: E222 E222 - - x[0] = 1 -35 + x[0] = 1 -36 | x[1] = 2 - | +35 | x[0] = 1 + | + E222 [*] Multiple spaces after operator --> E22.py:36:7 @@ -84,11 +72,8 @@ E222 [*] Multiple spaces after operator | help: Replace with single space | -35 | x[0] = 1 - - x[1] = 2 -36 + x[1] = 2 -37 | long_variable = 3 - | +36 | x[1] = 2 + | + E222 [*] Multiple spaces after operator --> E22.py:184:9 @@ -101,8 +86,5 @@ E222 [*] Multiple spaces after operator | help: Replace with single space | -183 | - - if a == 1: -184 + if a == 1: -185 | print(a) - | +184 | if a == 1: + | + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E223_E22.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E223_E22.py.snap index 6feeb7886dc7e..7afb66b042217 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E223_E22.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E223_E22.py.snap @@ -12,8 +12,5 @@ E223 [*] Tab before operator | help: Replace with single space | -42 | foobart = 4 - - a = 3 # aligned with tab -43 + a = 3 # aligned with tab -44 | #: - | +43 | a = 3 # aligned with tab + | + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E224_E22.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E224_E22.py.snap index 32bb2fc600774..6de6774d86012 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E224_E22.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E224_E22.py.snap @@ -12,8 +12,5 @@ E224 [*] Tab after operator | help: Replace with single space | -47 | #: E224 - - a += 1 -48 + a += 1 -49 | b += 1000 - | +48 | a += 1 + | + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E225_E22.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E225_E22.py.snap index 3149c68a3e15e..223add625c8cd 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E225_E22.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E225_E22.py.snap @@ -12,11 +12,8 @@ E225 [*] Missing whitespace around operator | help: Add missing whitespace | -53 | #: E225 - - submitted +=1 -54 + submitted += 1 -55 | #: E225 - | +54 | submitted += 1 + | + E225 [*] Missing whitespace around operator --> E22.py:56:10 @@ -30,11 +27,8 @@ E225 [*] Missing whitespace around operator | help: Add missing whitespace | -55 | #: E225 - - submitted+= 1 -56 + submitted += 1 -57 | #: E225 - | +56 | submitted += 1 + | + E225 [*] Missing whitespace around operator --> E22.py:58:3 @@ -48,11 +42,8 @@ E225 [*] Missing whitespace around operator | help: Add missing whitespace | -57 | #: E225 - - c =-1 -58 + c = -1 -59 | #: E225 - | +58 | c = -1 + | + E225 [*] Missing whitespace around operator --> E22.py:76:2 @@ -66,11 +57,8 @@ E225 [*] Missing whitespace around operator | help: Add missing whitespace | -75 | #: E225 E225 - - i=i+ 1 -76 + i = i+ 1 -77 | #: E225 E225 - | +76 | i = i+ 1 + | + + E225 [*] Missing whitespace around operator --> E22.py:78:2 @@ -84,11 +72,8 @@ E225 [*] Missing whitespace around operator | help: Add missing whitespace | -77 | #: E225 E225 - - i=i +1 -78 + i = i +1 -79 | #: E225 - | +78 | i = i +1 + | + + E225 [*] Missing whitespace around operator --> E22.py:80:6 @@ -102,11 +87,8 @@ E225 [*] Missing whitespace around operator | help: Add missing whitespace | -79 | #: E225 - - i = 1and 1 -80 + i = 1 and 1 -81 | #: E225 - | +80 | i = 1 and 1 + | + E225 [*] Missing whitespace around operator --> E22.py:82:6 @@ -120,11 +102,8 @@ E225 [*] Missing whitespace around operator | help: Add missing whitespace | -81 | #: E225 - - i = 1or 0 -82 + i = 1 or 0 -83 | #: E225 - | +82 | i = 1 or 0 + | + E225 [*] Missing whitespace around operator --> E22.py:84:2 @@ -138,11 +117,8 @@ E225 [*] Missing whitespace around operator | help: Add missing whitespace | -83 | #: E225 - - 1is 1 -84 + 1 is 1 -85 | #: E225 - | +84 | 1 is 1 + | + E225 [*] Missing whitespace around operator --> E22.py:86:2 @@ -156,11 +132,8 @@ E225 [*] Missing whitespace around operator | help: Add missing whitespace | -85 | #: E225 - - 1in [] -86 + 1 in [] -87 | #: E225 - | +86 | 1 in [] + | + E225 [*] Missing whitespace around operator --> E22.py:92:2 @@ -174,11 +147,8 @@ E225 [*] Missing whitespace around operator | help: Add missing whitespace | -91 | #: E225 E226 - - i=i+1 -92 + i = i+1 -93 | #: E225 E226 - | +92 | i = i+1 + | + + E225 [*] Missing whitespace around operator --> E22.py:94:3 @@ -192,11 +162,8 @@ E225 [*] Missing whitespace around operator | help: Add missing whitespace | -93 | #: E225 E226 - - i =i+1 -94 + i = i+1 -95 | #: E225 E226 - | +94 | i = i+1 + | + E225 [*] Missing whitespace around operator --> E22.py:96:2 @@ -210,8 +177,5 @@ E225 [*] Missing whitespace around operator | help: Add missing whitespace | -95 | #: E225 E226 - - i= i+1 -96 + i = i+1 -97 | #: E225 E226 - | +96 | i = i+1 + | + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E226_E22.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E226_E22.py.snap index 5fc32d62899a8..69d9ab45cea26 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E226_E22.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E226_E22.py.snap @@ -13,11 +13,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -59 | #: E225 - - x = x /2 - 1 -60 + x = x / 2 - 1 -61 | #: E225 - | +60 | x = x / 2 - 1 + | + E226 [*] Missing whitespace around arithmetic operator --> E22.py:62:11 @@ -31,11 +28,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -61 | #: E225 - - c = alpha -4 -62 + c = alpha - 4 -63 | #: E225 - | +62 | c = alpha - 4 + | + E226 [*] Missing whitespace around arithmetic operator --> E22.py:64:10 @@ -49,11 +43,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -63 | #: E225 - - c = alpha- 4 -64 + c = alpha - 4 -65 | #: E225 - | +64 | c = alpha - 4 + | + E226 [*] Missing whitespace around arithmetic operator --> E22.py:66:7 @@ -67,11 +58,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -65 | #: E225 - - z = x **y -66 + z = x ** y -67 | #: E225 - | +66 | z = x ** y + | + E226 [*] Missing whitespace around arithmetic operator --> E22.py:68:13 @@ -85,11 +73,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -67 | #: E225 - - z = (x + 1) **y -68 + z = (x + 1) ** y -69 | #: E225 - | +68 | z = (x + 1) ** y + | + E226 [*] Missing whitespace around arithmetic operator --> E22.py:70:12 @@ -103,11 +88,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -69 | #: E225 - - z = (x + 1)** y -70 + z = (x + 1) ** y -71 | #: E225 - | +70 | z = (x + 1) ** y + | + E226 [*] Missing whitespace around arithmetic operator --> E22.py:76:4 @@ -121,11 +103,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -75 | #: E225 E225 - - i=i+ 1 -76 + i=i + 1 -77 | #: E225 E225 - | +76 | i=i + 1 + | + E226 [*] Missing whitespace around arithmetic operator --> E22.py:78:5 @@ -139,11 +118,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -77 | #: E225 E225 - - i=i +1 -78 + i=i + 1 -79 | #: E225 - | +78 | i=i + 1 + | + E226 [*] Missing whitespace around arithmetic operator --> E22.py:88:7 @@ -157,11 +133,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -87 | #: E225 - - i = 1 @2 -88 + i = 1 @ 2 -89 | #: E225 - | +88 | i = 1 @ 2 + | + E226 [*] Missing whitespace around arithmetic operator --> E22.py:90:6 @@ -175,11 +148,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -89 | #: E225 - - i = 1@ 2 -90 + i = 1 @ 2 -91 | #: E225 E226 - | +90 | i = 1 @ 2 + | + E226 [*] Missing whitespace around arithmetic operator --> E22.py:92:4 @@ -193,11 +163,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -91 | #: E225 E226 - - i=i+1 -92 + i=i + 1 -93 | #: E225 E226 - | +92 | i=i + 1 + | + + E226 [*] Missing whitespace around arithmetic operator --> E22.py:94:5 @@ -211,11 +178,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -93 | #: E225 E226 - - i =i+1 -94 + i =i + 1 -95 | #: E225 E226 - | +94 | i =i + 1 + | + + E226 [*] Missing whitespace around arithmetic operator --> E22.py:96:5 @@ -229,11 +193,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -95 | #: E225 E226 - - i= i+1 -96 + i= i + 1 -97 | #: E225 E226 - | +96 | i= i + 1 + | + + E226 [*] Missing whitespace around arithmetic operator --> E22.py:98:8 @@ -247,11 +208,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -97 | #: E225 E226 - - c = (a +b)*(a - b) -98 + c = (a + b)*(a - b) -99 | #: E225 E226 - | +98 | c = (a + b)*(a - b) + | + E226 [*] Missing whitespace around arithmetic operator --> E22.py:98:11 @@ -265,11 +223,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -97 | #: E225 E226 - - c = (a +b)*(a - b) -98 + c = (a +b) * (a - b) -99 | #: E225 E226 - | +98 | c = (a +b) * (a - b) + | + + E226 [*] Missing whitespace around arithmetic operator --> E22.py:100:7 @@ -282,11 +237,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -99 | #: E225 E226 - - c = (a+ b)*(a - b) -100 + c = (a + b)*(a - b) -101 | #: - | +100 | c = (a + b)*(a - b) + | + E226 [*] Missing whitespace around arithmetic operator --> E22.py:100:11 @@ -299,11 +251,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -99 | #: E225 E226 - - c = (a+ b)*(a - b) -100 + c = (a+ b) * (a - b) -101 | #: - | +100 | c = (a+ b) * (a - b) + | + + E226 [*] Missing whitespace around arithmetic operator --> E22.py:104:6 @@ -316,11 +265,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -103 | #: E226 - - z = 2//30 -104 + z = 2 // 30 -105 | #: E226 E226 - | +104 | z = 2 // 30 + | + + E226 [*] Missing whitespace around arithmetic operator --> E22.py:106:7 @@ -334,11 +280,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -105 | #: E226 E226 - - c = (a+b) * (a-b) -106 + c = (a + b) * (a-b) -107 | #: E226 - | +106 | c = (a + b) * (a-b) + | + + E226 [*] Missing whitespace around arithmetic operator --> E22.py:106:15 @@ -352,11 +295,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -105 | #: E226 E226 - - c = (a+b) * (a-b) -106 + c = (a+b) * (a - b) -107 | #: E226 - | +106 | c = (a+b) * (a - b) + | + + E226 [*] Missing whitespace around arithmetic operator --> E22.py:110:6 @@ -370,11 +310,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -109 | #: E226 - - x = x*2 - 1 -110 + x = x * 2 - 1 -111 | #: E226 - | +110 | x = x * 2 - 1 + | + + E226 [*] Missing whitespace around arithmetic operator --> E22.py:112:6 @@ -388,11 +325,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -111 | #: E226 - - x = x/2 - 1 -112 + x = x / 2 - 1 -113 | #: E226 E226 - | +112 | x = x / 2 - 1 + | + + E226 [*] Missing whitespace around arithmetic operator --> E22.py:114:11 @@ -406,11 +340,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -113 | #: E226 E226 - - hypot2 = x*x + y*y -114 + hypot2 = x * x + y*y -115 | #: E226 - | +114 | hypot2 = x * x + y*y + | + + E226 [*] Missing whitespace around arithmetic operator --> E22.py:114:17 @@ -424,11 +355,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -113 | #: E226 E226 - - hypot2 = x*x + y*y -114 + hypot2 = x*x + y * y -115 | #: E226 - | +114 | hypot2 = x*x + y * y + | + + E226 [*] Missing whitespace around arithmetic operator --> E22.py:116:12 @@ -442,11 +370,8 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -115 | #: E226 - - c = (a + b)*(a - b) -116 + c = (a + b) * (a - b) -117 | #: E226 - | +116 | c = (a + b) * (a - b) + | + + E226 [*] Missing whitespace around arithmetic operator --> E22.py:119:14 @@ -460,8 +385,5 @@ E226 [*] Missing whitespace around arithmetic operator | help: Add missing whitespace | -118 | def halves(n): - - return (i//2 for i in range(n)) -119 + return (i // 2 for i in range(n)) -120 | #: E227 - | +119 | return (i // 2 for i in range(n)) + | + + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E227_E22.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E227_E22.py.snap index 1f46ca22ee9d5..6ff5632850fb2 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E227_E22.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E227_E22.py.snap @@ -13,11 +13,8 @@ E227 [*] Missing whitespace around bitwise or shift operator | help: Add missing whitespace | -71 | #: E225 - - _1kB = _1MB >>10 -72 + _1kB = _1MB >> 10 -73 | #: E225 - | +72 | _1kB = _1MB >> 10 + | + E227 [*] Missing whitespace around bitwise or shift operator --> E22.py:74:12 @@ -31,11 +28,8 @@ E227 [*] Missing whitespace around bitwise or shift operator | help: Add missing whitespace | -73 | #: E225 - - _1kB = _1MB>> 10 -74 + _1kB = _1MB >> 10 -75 | #: E225 E225 - | +74 | _1kB = _1MB >> 10 + | + E227 [*] Missing whitespace around bitwise or shift operator --> E22.py:121:12 @@ -49,11 +43,8 @@ E227 [*] Missing whitespace around bitwise or shift operator | help: Add missing whitespace | -120 | #: E227 - - _1kB = _1MB>>10 -121 + _1kB = _1MB >> 10 -122 | #: E227 - | +121 | _1kB = _1MB >> 10 + | + + E227 [*] Missing whitespace around bitwise or shift operator --> E22.py:123:12 @@ -67,11 +58,8 @@ E227 [*] Missing whitespace around bitwise or shift operator | help: Add missing whitespace | -122 | #: E227 - - _1MB = _1kB<<10 -123 + _1MB = _1kB << 10 -124 | #: E227 - | +123 | _1MB = _1kB << 10 + | + + E227 [*] Missing whitespace around bitwise or shift operator --> E22.py:125:6 @@ -85,11 +73,8 @@ E227 [*] Missing whitespace around bitwise or shift operator | help: Add missing whitespace | -124 | #: E227 - - a = b|c -125 + a = b | c -126 | #: E227 - | +125 | a = b | c + | + + E227 [*] Missing whitespace around bitwise or shift operator --> E22.py:127:6 @@ -103,11 +88,8 @@ E227 [*] Missing whitespace around bitwise or shift operator | help: Add missing whitespace | -126 | #: E227 - - b = c&a -127 + b = c & a -128 | #: E227 - | +127 | b = c & a + | + + E227 [*] Missing whitespace around bitwise or shift operator --> E22.py:129:6 @@ -121,11 +103,8 @@ E227 [*] Missing whitespace around bitwise or shift operator | help: Add missing whitespace | -128 | #: E227 - - c = b^a -129 + c = b ^ a -130 | #: E228 - | +129 | c = b ^ a + | + + E227 [*] Missing whitespace around bitwise or shift operator --> E22.py:154:11 @@ -139,8 +118,5 @@ E227 [*] Missing whitespace around bitwise or shift operator | help: Add missing whitespace | -153 | if not -5 < x < +5: - - print >>sys.stderr, "x is out of range." -154 + print >> sys.stderr, "x is out of range." -155 | print >> sys.stdout, "x is an integer." - | +154 | print >> sys.stderr, "x is out of range." + | + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E228_E22.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E228_E22.py.snap index b731e02ea46a7..450f4a4165b85 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E228_E22.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E228_E22.py.snap @@ -13,11 +13,8 @@ E228 [*] Missing whitespace around modulo operator | help: Add missing whitespace | -130 | #: E228 - - a = b%c -131 + a = b % c -132 | #: E228 - | +131 | a = b % c + | + + E228 [*] Missing whitespace around modulo operator --> E22.py:133:10 @@ -31,11 +28,8 @@ E228 [*] Missing whitespace around modulo operator | help: Add missing whitespace | -132 | #: E228 - - msg = fmt%(errno, errmsg) -133 + msg = fmt % (errno, errmsg) -134 | #: E228 - | +133 | msg = fmt % (errno, errmsg) + | + + E228 [*] Missing whitespace around modulo operator --> E22.py:135:26 @@ -48,8 +42,5 @@ E228 [*] Missing whitespace around modulo operator | help: Add missing whitespace | -134 | #: E228 - - msg = "Error %d occurred"%errno -135 + msg = "Error %d occurred" % errno -136 | #: - | +135 | msg = "Error %d occurred" % errno + | + + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E231_E23.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E231_E23.py.snap index ae646c1068e2b..db1e49337a9f5 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E231_E23.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E231_E23.py.snap @@ -12,11 +12,8 @@ E231 [*] Missing whitespace after `,` | help: Add missing whitespace | -1 | #: E231 - - a = (1,2) -2 + a = (1, 2) -3 | #: E231 - | +2 | a = (1, 2) + | + E231 [*] Missing whitespace after `,` --> E23.py:4:5 @@ -30,11 +27,8 @@ E231 [*] Missing whitespace after `,` | help: Add missing whitespace | -3 | #: E231 - - a[b1,:] -4 + a[b1, :] -5 | #: E231 - | +4 | a[b1, :] + | + E231 [*] Missing whitespace after `:` --> E23.py:6:10 @@ -48,11 +42,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -5 | #: E231 - - a = [{'a':''}] -6 + a = [{'a': ''}] -7 | #: Okay - | +6 | a = [{'a': ''}] + | + E231 [*] Missing whitespace after `,` --> E23.py:19:10 @@ -65,11 +56,8 @@ E231 [*] Missing whitespace after `,` | help: Add missing whitespace | -18 | #: E231 - - if (1,2): -19 + if (1, 2): -20 | pass - | +19 | if (1, 2): + | + E231 [*] Missing whitespace after `:` --> E23.py:29:20 @@ -82,11 +70,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -28 | 'tag_full': [('mdtype', 'u4'), ('byte_count', 'u4')], - - 'tag_smalldata':[('byte_count_mdtype', 'u4'), ('data', 'S4')], -29 + 'tag_smalldata': [('byte_count_mdtype', 'u4'), ('data', 'S4')], -30 | } - | +29 | 'tag_smalldata': [('byte_count_mdtype', 'u4'), ('data', 'S4')], + | + E231 [*] Missing whitespace after `,` --> E23.py:33:6 @@ -99,11 +84,8 @@ E231 [*] Missing whitespace after `,` | help: Add missing whitespace | -32 | # E231 - - f"{(a,b)}" -33 + f"{(a, b)}" -34 | - | +33 | f"{(a, b)}" + | + E231 [*] Missing whitespace after `:` --> E23.py:47:37 @@ -116,11 +98,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -46 | #: E231 - - {len(f's3://{self.s3_bucket_name}/'):1} -47 + {len(f's3://{self.s3_bucket_name}/'): 1} -48 | - | +47 | {len(f's3://{self.s3_bucket_name}/'): 1} + | + E231 [*] Missing whitespace after `:` --> E23.py:60:13 @@ -134,11 +113,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -59 | "k1": [1], - - "k2":[2], -60 + "k2": [2], -61 | } - | +60 | "k2": [2], + | + E231 [*] Missing whitespace after `:` --> E23.py:65:17 @@ -152,11 +128,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -64 | "k1": [1], - - "k2":[2], -65 + "k2": [2], -66 | }, - | +65 | "k2": [2], + | + E231 [*] Missing whitespace after `:` --> E23.py:71:17 @@ -170,11 +143,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -70 | "k1": [1], - - "k2":[2], -71 + "k2": [2], -72 | } - | +71 | "k2": [2], + | + E231 [*] Missing whitespace after `:` --> E23.py:76:17 @@ -188,11 +158,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -75 | { - - "k2":[2], -76 + "k2": [2], -77 | } - | +76 | "k2": [2], + | + E231 [*] Missing whitespace after `:` --> E23.py:82:13 @@ -206,11 +173,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -81 | { - - "k1":[2], # E231 -82 + "k1": [2], # E231 -83 | "k2": x[2:4], - | +82 | "k1": [2], # E231 + | + E231 [*] Missing whitespace after `:` --> E23.py:84:13 @@ -224,11 +188,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -83 | "k2": x[2:4], - - "k3":[2], # E231 -84 + "k3": [2], # E231 -85 | "k4": [2], - | +84 | "k3": [2], # E231 + | + E231 [*] Missing whitespace after `,` --> E23.py:87:26 @@ -242,11 +203,8 @@ E231 [*] Missing whitespace after `,` | help: Add missing whitespace | -86 | "k5": [2], - - "k6": [1, 2, 3, 4,5,6,7] # E231 -87 + "k6": [1, 2, 3, 4, 5,6,7] # E231 -88 | }, - | +87 | "k6": [1, 2, 3, 4, 5,6,7] # E231 + | + E231 [*] Missing whitespace after `,` --> E23.py:87:28 @@ -260,11 +218,8 @@ E231 [*] Missing whitespace after `,` | help: Add missing whitespace | -86 | "k5": [2], - - "k6": [1, 2, 3, 4,5,6,7] # E231 -87 + "k6": [1, 2, 3, 4,5, 6,7] # E231 -88 | }, - | +87 | "k6": [1, 2, 3, 4,5, 6,7] # E231 + | + E231 [*] Missing whitespace after `,` --> E23.py:87:30 @@ -278,11 +233,8 @@ E231 [*] Missing whitespace after `,` | help: Add missing whitespace | -86 | "k5": [2], - - "k6": [1, 2, 3, 4,5,6,7] # E231 -87 + "k6": [1, 2, 3, 4,5,6, 7] # E231 -88 | }, - | +87 | "k6": [1, 2, 3, 4,5,6, 7] # E231 + | + E231 [*] Missing whitespace after `:` --> E23.py:92:21 @@ -296,11 +248,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -91 | { - - "ka":[2,3], # E231 -92 + "ka": [2,3], # E231 -93 | }, - | +92 | "ka": [2,3], # E231 + | + E231 [*] Missing whitespace after `,` --> E23.py:92:24 @@ -314,11 +263,8 @@ E231 [*] Missing whitespace after `,` | help: Add missing whitespace | -91 | { - - "ka":[2,3], # E231 -92 + "ka":[2, 3], # E231 -93 | }, - | +92 | "ka":[2, 3], # E231 + | + E231 [*] Missing whitespace after `,` --> E23.py:95:25 @@ -332,11 +278,8 @@ E231 [*] Missing whitespace after `,` | help: Add missing whitespace | -94 | { - - "kb": [2,3], # E231 -95 + "kb": [2, 3], # E231 -96 | }, - | +95 | "kb": [2, 3], # E231 + | + E231 [*] Missing whitespace after `:` --> E23.py:98:21 @@ -350,11 +293,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -97 | { - - "ka":[2, 3], # E231 -98 + "ka": [2, 3], # E231 -99 | "kb": [2, 3], # Ok - | +98 | "ka": [2, 3], # E231 + | + E231 [*] Missing whitespace after `,` --> E23.py:101:25 @@ -368,11 +308,8 @@ E231 [*] Missing whitespace after `,` | help: Add missing whitespace | -100 | "kc": [2, 3], # Ok - - "kd": [2,3], # E231 -101 + "kd": [2, 3], # E231 -102 | "ke":[2,3], # E231 - | +101 | "kd": [2, 3], # E231 + | + E231 [*] Missing whitespace after `:` --> E23.py:102:21 @@ -386,11 +323,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -101 | "kd": [2,3], # E231 - - "ke":[2,3], # E231 -102 + "ke": [2,3], # E231 -103 | }, - | +102 | "ke": [2,3], # E231 + | + E231 [*] Missing whitespace after `,` --> E23.py:102:24 @@ -404,11 +338,8 @@ E231 [*] Missing whitespace after `,` | help: Add missing whitespace | -101 | "kd": [2,3], # E231 - - "ke":[2,3], # E231 -102 + "ke":[2, 3], # E231 -103 | }, - | +102 | "ke":[2, 3], # E231 + | + E231 [*] Missing whitespace after `:` --> E23.py:109:18 @@ -421,11 +352,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -108 | # Should be E231 errors on all of these type parameters and function parameters, but not on their (strange) defaults - - def pep_696_bad[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]( -109 + def pep_696_bad[A: object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]( -110 | x:A = "foo"[::-1], - | +109 | def pep_696_bad[A: object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]( + | + E231 [*] Missing whitespace after `:` --> E23.py:109:40 @@ -438,11 +366,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -108 | # Should be E231 errors on all of these type parameters and function parameters, but not on their (strange) defaults - - def pep_696_bad[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]( -109 + def pep_696_bad[A:object="foo"[::-1], B: object =[[["foo", "bar"]]], C:object= bytes]( -110 | x:A = "foo"[::-1], - | +109 | def pep_696_bad[A:object="foo"[::-1], B: object =[[["foo", "bar"]]], C:object= bytes]( + | + E231 [*] Missing whitespace after `:` --> E23.py:109:70 @@ -455,11 +380,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -108 | # Should be E231 errors on all of these type parameters and function parameters, but not on their (strange) defaults - - def pep_696_bad[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]( -109 + def pep_696_bad[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C: object= bytes]( -110 | x:A = "foo"[::-1], - | +109 | def pep_696_bad[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C: object= bytes]( + | + E231 [*] Missing whitespace after `:` --> E23.py:110:6 @@ -473,11 +395,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -109 | def pep_696_bad[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]( - - x:A = "foo"[::-1], -110 + x: A = "foo"[::-1], -111 | y:B = [[["foo", "bar"]]], - | +110 | x: A = "foo"[::-1], + | + E231 [*] Missing whitespace after `:` --> E23.py:111:6 @@ -491,11 +410,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -110 | x:A = "foo"[::-1], - - y:B = [[["foo", "bar"]]], -111 + y: B = [[["foo", "bar"]]], -112 | z:object = "fooo", - | +111 | y: B = [[["foo", "bar"]]], + | + E231 [*] Missing whitespace after `:` --> E23.py:112:6 @@ -509,11 +425,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -111 | y:B = [[["foo", "bar"]]], - - z:object = "fooo", -112 + z: object = "fooo", -113 | ): - | +112 | z: object = "fooo", + | + E231 [*] Missing whitespace after `:` --> E23.py:116:18 @@ -527,11 +440,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -115 | - - class PEP696Bad[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]: -116 + class PEP696Bad[A: object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]: -117 | def pep_696_bad_method[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]( - | +116 | class PEP696Bad[A: object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]: + | + E231 [*] Missing whitespace after `:` --> E23.py:116:40 @@ -545,11 +455,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -115 | - - class PEP696Bad[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]: -116 + class PEP696Bad[A:object="foo"[::-1], B: object =[[["foo", "bar"]]], C:object= bytes]: -117 | def pep_696_bad_method[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]( - | +116 | class PEP696Bad[A:object="foo"[::-1], B: object =[[["foo", "bar"]]], C:object= bytes]: + | + E231 [*] Missing whitespace after `:` --> E23.py:116:70 @@ -563,11 +470,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -115 | - - class PEP696Bad[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]: -116 + class PEP696Bad[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C: object= bytes]: -117 | def pep_696_bad_method[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]( - | +116 | class PEP696Bad[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C: object= bytes]: + | + E231 [*] Missing whitespace after `:` --> E23.py:117:29 @@ -580,11 +484,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -116 | class PEP696Bad[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]: - - def pep_696_bad_method[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]( -117 + def pep_696_bad_method[A: object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]( -118 | self, - | +117 | def pep_696_bad_method[A: object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]( + | + E231 [*] Missing whitespace after `:` --> E23.py:117:51 @@ -597,11 +498,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -116 | class PEP696Bad[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]: - - def pep_696_bad_method[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]( -117 + def pep_696_bad_method[A:object="foo"[::-1], B: object =[[["foo", "bar"]]], C:object= bytes]( -118 | self, - | +117 | def pep_696_bad_method[A:object="foo"[::-1], B: object =[[["foo", "bar"]]], C:object= bytes]( + | + E231 [*] Missing whitespace after `:` --> E23.py:117:81 @@ -614,11 +512,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -116 | class PEP696Bad[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]: - - def pep_696_bad_method[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]( -117 + def pep_696_bad_method[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C: object= bytes]( -118 | self, - | +117 | def pep_696_bad_method[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C: object= bytes]( + | + E231 [*] Missing whitespace after `:` --> E23.py:119:10 @@ -632,11 +527,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -118 | self, - - x:A = "foo"[::-1], -119 + x: A = "foo"[::-1], -120 | y:B = [[["foo", "bar"]]], - | +119 | x: A = "foo"[::-1], + | + E231 [*] Missing whitespace after `:` --> E23.py:120:10 @@ -650,11 +542,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -119 | x:A = "foo"[::-1], - - y:B = [[["foo", "bar"]]], -120 + y: B = [[["foo", "bar"]]], -121 | z:object = "fooo", - | +120 | y: B = [[["foo", "bar"]]], + | + E231 [*] Missing whitespace after `:` --> E23.py:121:10 @@ -668,11 +557,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -120 | y:B = [[["foo", "bar"]]], - - z:object = "fooo", -121 + z: object = "fooo", -122 | ): - | +121 | z: object = "fooo", + | + E231 [*] Missing whitespace after `:` --> E23.py:125:32 @@ -686,11 +572,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -124 | - - class PEP696BadWithEmptyBases[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes](): -125 + class PEP696BadWithEmptyBases[A: object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes](): -126 | class IndentedPEP696BadWithNonEmptyBases[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes](object, something_dynamic[x::-1]): - | +125 | class PEP696BadWithEmptyBases[A: object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes](): + | + E231 [*] Missing whitespace after `:` --> E23.py:125:54 @@ -704,11 +587,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -124 | - - class PEP696BadWithEmptyBases[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes](): -125 + class PEP696BadWithEmptyBases[A:object="foo"[::-1], B: object =[[["foo", "bar"]]], C:object= bytes](): -126 | class IndentedPEP696BadWithNonEmptyBases[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes](object, something_dynamic[x::-1]): - | +125 | class PEP696BadWithEmptyBases[A:object="foo"[::-1], B: object =[[["foo", "bar"]]], C:object= bytes](): + | + E231 [*] Missing whitespace after `:` --> E23.py:125:84 @@ -722,11 +602,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -124 | - - class PEP696BadWithEmptyBases[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes](): -125 + class PEP696BadWithEmptyBases[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C: object= bytes](): -126 | class IndentedPEP696BadWithNonEmptyBases[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes](object, something_dynamic[x::-1]): - | +125 | class PEP696BadWithEmptyBases[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C: object= bytes](): + | + E231 [*] Missing whitespace after `:` --> E23.py:126:47 @@ -738,11 +615,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -125 | class PEP696BadWithEmptyBases[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes](): - - class IndentedPEP696BadWithNonEmptyBases[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes](object, something_dynamic[x::-1]): -126 + class IndentedPEP696BadWithNonEmptyBases[A: object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes](object, something_dynamic[x::-1]): -127 | pass - | +126 | class IndentedPEP696BadWithNonEmptyBases[A: object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes](object, something_dynamic[x::-1]): + | + E231 [*] Missing whitespace after `:` --> E23.py:126:69 @@ -754,11 +628,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -125 | class PEP696BadWithEmptyBases[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes](): - - class IndentedPEP696BadWithNonEmptyBases[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes](object, something_dynamic[x::-1]): -126 + class IndentedPEP696BadWithNonEmptyBases[A:object="foo"[::-1], B: object =[[["foo", "bar"]]], C:object= bytes](object, something_dynamic[x::-1]): -127 | pass - | +126 | class IndentedPEP696BadWithNonEmptyBases[A:object="foo"[::-1], B: object =[[["foo", "bar"]]], C:object= bytes](object, something_dynamic[x::-1]): + | + E231 [*] Missing whitespace after `:` --> E23.py:126:99 @@ -770,11 +641,8 @@ E231 [*] Missing whitespace after `:` | help: Add missing whitespace | -125 | class PEP696BadWithEmptyBases[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes](): - - class IndentedPEP696BadWithNonEmptyBases[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes](object, something_dynamic[x::-1]): -126 + class IndentedPEP696BadWithNonEmptyBases[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C: object= bytes](object, something_dynamic[x::-1]): -127 | pass - | +126 | class IndentedPEP696BadWithNonEmptyBases[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C: object= bytes](object, something_dynamic[x::-1]): + | + E231 [*] Missing whitespace after `,` --> E23.py:147:6 @@ -787,11 +655,8 @@ E231 [*] Missing whitespace after `,` | help: Add missing whitespace | -146 | # E231 - - t"{(a,b)}" -147 + t"{(a, b)}" -148 | - | +147 | t"{(a, b)}" + | + E231 [*] Missing whitespace after `:` --> E23.py:161:37 @@ -801,7 +666,5 @@ E231 [*] Missing whitespace after `:` | ^ help: Add missing whitespace | -160 | #: E231 - - {len(t's3://{self.s3_bucket_name}/'):1} -161 + {len(t's3://{self.s3_bucket_name}/'): 1} - | +161 | {len(t's3://{self.s3_bucket_name}/'): 1} + | + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E241_E24.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E241_E24.py.snap index 3e569d5870152..a9eade6d18586 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E241_E24.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E241_E24.py.snap @@ -12,11 +12,8 @@ E241 [*] Multiple spaces after comma | help: Replace with single space | -1 | #: E241 - - a = (1, 2) -2 + a = (1, 2) -3 | #: Okay - | +2 | a = (1, 2) + | + E241 [*] Multiple spaces after comma --> E24.py:11:18 @@ -30,11 +27,8 @@ E241 [*] Multiple spaces after comma | help: Replace with single space | -10 | # issue 135 - - more_spaces = [a, b, -11 + more_spaces = [a, b, -12 | ef, +h, - | +11 | more_spaces = [a, b, + | + E241 [*] Multiple spaces after comma --> E24.py:12:19 @@ -47,11 +41,8 @@ E241 [*] Multiple spaces after comma | help: Replace with single space | -11 | more_spaces = [a, b, - - ef, +h, -12 + ef, +h, -13 | c, -d] - | +12 | ef, +h, + | + E241 [*] Multiple spaces after comma --> E24.py:13:18 @@ -62,7 +53,5 @@ E241 [*] Multiple spaces after comma | ^^^ help: Replace with single space | -12 | ef, +h, - - c, -d] -13 + c, -d] - | +13 | c, -d] + | + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E242_E24.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E242_E24.py.snap index 3218645348429..fe7b496f0e36e 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E242_E24.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E242_E24.py.snap @@ -13,8 +13,5 @@ E242 [*] Tab after comma | help: Replace with single space | -5 | #: E242 - - a = (1, 2) # tab before 2 -6 + a = (1, 2) # tab before 2 -7 | #: Okay - | +6 | a = (1, 2) # tab before 2 + | + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E251_E25.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E251_E25.py.snap index 5bebbbf58fef4..fdab815799e46 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E251_E25.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E251_E25.py.snap @@ -12,10 +12,7 @@ E251 [*] Unexpected spaces around keyword / parameter equals | help: Remove whitespace | -1 | #: E251 E251 - - def foo(bar = False): -2 + def foo(bar= False): -3 | '''Test function with an error in declaration''' +2 | def foo(bar= False): | E251 [*] Unexpected spaces around keyword / parameter equals @@ -29,10 +26,7 @@ E251 [*] Unexpected spaces around keyword / parameter equals | help: Remove whitespace | -1 | #: E251 E251 - - def foo(bar = False): -2 + def foo(bar =False): -3 | '''Test function with an error in declaration''' +2 | def foo(bar =False): | E251 [*] Unexpected spaces around keyword / parameter equals @@ -47,10 +41,7 @@ E251 [*] Unexpected spaces around keyword / parameter equals | help: Remove whitespace | -5 | #: E251 - - foo(bar= True) -6 + foo(bar=True) -7 | #: E251 +6 | foo(bar=True) | E251 [*] Unexpected spaces around keyword / parameter equals @@ -65,10 +56,7 @@ E251 [*] Unexpected spaces around keyword / parameter equals | help: Remove whitespace | -7 | #: E251 - - foo(bar =True) -8 + foo(bar=True) -9 | #: E251 E251 +8 | foo(bar=True) | E251 [*] Unexpected spaces around keyword / parameter equals @@ -83,10 +71,7 @@ E251 [*] Unexpected spaces around keyword / parameter equals | help: Remove whitespace | -9 | #: E251 E251 - - foo(bar = True) -10 + foo(bar= True) -11 | #: E251 +10 | foo(bar= True) | E251 [*] Unexpected spaces around keyword / parameter equals @@ -101,10 +86,7 @@ E251 [*] Unexpected spaces around keyword / parameter equals | help: Remove whitespace | -9 | #: E251 E251 - - foo(bar = True) -10 + foo(bar =True) -11 | #: E251 +10 | foo(bar =True) | E251 [*] Unexpected spaces around keyword / parameter equals @@ -119,10 +101,7 @@ E251 [*] Unexpected spaces around keyword / parameter equals | help: Remove whitespace | -11 | #: E251 - - y = bar(root= "sdasd") -12 + y = bar(root="sdasd") -13 | #: E251:2:29 +12 | y = bar(root="sdasd") | E251 [*] Unexpected spaces around keyword / parameter equals @@ -139,11 +118,7 @@ E251 [*] Unexpected spaces around keyword / parameter equals | help: Remove whitespace | -14 | parser.add_argument('--long-option', - - default= - - "/rather/long/filesystem/path/here/blah/blah/blah") -15 + default="/rather/long/filesystem/path/here/blah/blah/blah") -16 | #: E251:1:45 +15 | default="/rather/long/filesystem/path/here/blah/blah/blah") | E251 [*] Unexpected spaces around keyword / parameter equals @@ -160,11 +135,7 @@ E251 [*] Unexpected spaces around keyword / parameter equals | help: Remove whitespace | -17 | #: E251:1:45 - - parser.add_argument('--long-option', default - - ="/rather/long/filesystem/path/here/blah/blah/blah") -18 + parser.add_argument('--long-option', default="/rather/long/filesystem/path/here/blah/blah/blah") -19 | #: E251:3:8 E251:3:10 +18 | parser.add_argument('--long-option', default="/rather/long/filesystem/path/here/blah/blah/blah") | E251 [*] Unexpected spaces around keyword / parameter equals @@ -179,10 +150,7 @@ E251 [*] Unexpected spaces around keyword / parameter equals | help: Remove whitespace | -22 | baz=(1, 2), - - biz = 'foo' -23 + biz= 'foo' -24 | ) +23 | biz= 'foo' | E251 [*] Unexpected spaces around keyword / parameter equals @@ -197,8 +165,5 @@ E251 [*] Unexpected spaces around keyword / parameter equals | help: Remove whitespace | -22 | baz=(1, 2), - - biz = 'foo' -23 + biz ='foo' -24 | ) +23 | biz ='foo' | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E252_E25.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E252_E25.py.snap index c92f480fa7e47..2ae7328a4d0b8 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E252_E25.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E252_E25.py.snap @@ -13,11 +13,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -45 | #: E252:1:15 E252:1:16 E252:1:27 E252:1:36 - - def add(a: int=0, b: int =0, c: int= 0) -> int: -46 + def add(a: int =0, b: int =0, c: int= 0) -> int: -47 | return a + b + c - | +46 | def add(a: int =0, b: int =0, c: int= 0) -> int: + | + E252 [*] Missing whitespace around parameter equals --> E25.py:46:15 @@ -31,11 +28,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -45 | #: E252:1:15 E252:1:16 E252:1:27 E252:1:36 - - def add(a: int=0, b: int =0, c: int= 0) -> int: -46 + def add(a: int= 0, b: int =0, c: int= 0) -> int: -47 | return a + b + c - | +46 | def add(a: int= 0, b: int =0, c: int= 0) -> int: + | + E252 [*] Missing whitespace around parameter equals --> E25.py:46:26 @@ -49,11 +43,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -45 | #: E252:1:15 E252:1:16 E252:1:27 E252:1:36 - - def add(a: int=0, b: int =0, c: int= 0) -> int: -46 + def add(a: int=0, b: int = 0, c: int= 0) -> int: -47 | return a + b + c - | +46 | def add(a: int=0, b: int = 0, c: int= 0) -> int: + | + E252 [*] Missing whitespace around parameter equals --> E25.py:46:36 @@ -67,11 +58,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -45 | #: E252:1:15 E252:1:16 E252:1:27 E252:1:36 - - def add(a: int=0, b: int =0, c: int= 0) -> int: -46 + def add(a: int=0, b: int =0, c: int = 0) -> int: -47 | return a + b + c - | +46 | def add(a: int=0, b: int =0, c: int = 0) -> int: + | + E252 [*] Missing whitespace around parameter equals --> E25.py:64:18 @@ -83,11 +71,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -63 | # There should be at least one E251 diagnostic for each type parameter here: - - def pep_696_bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes](): -64 + def pep_696_bad[A =int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes](): -65 | pass - | +64 | def pep_696_bad[A =int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes](): + | + E252 [*] Missing whitespace around parameter equals --> E25.py:64:18 @@ -99,11 +84,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -63 | # There should be at least one E251 diagnostic for each type parameter here: - - def pep_696_bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes](): -64 + def pep_696_bad[A= int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes](): -65 | pass - | +64 | def pep_696_bad[A= int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes](): + | + E252 [*] Missing whitespace around parameter equals --> E25.py:64:26 @@ -115,11 +97,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -63 | # There should be at least one E251 diagnostic for each type parameter here: - - def pep_696_bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes](): -64 + def pep_696_bad[A=int, B = str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes](): -65 | pass - | +64 | def pep_696_bad[A=int, B = str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes](): + | + E252 [*] Missing whitespace around parameter equals --> E25.py:64:33 @@ -131,11 +110,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -63 | # There should be at least one E251 diagnostic for each type parameter here: - - def pep_696_bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes](): -64 + def pep_696_bad[A=int, B =str, C = bool, D:object=int, E: object=str, F: object =bool, G: object= bytes](): -65 | pass - | +64 | def pep_696_bad[A=int, B =str, C = bool, D:object=int, E: object=str, F: object =bool, G: object= bytes](): + | + E252 [*] Missing whitespace around parameter equals --> E25.py:64:49 @@ -147,11 +123,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -63 | # There should be at least one E251 diagnostic for each type parameter here: - - def pep_696_bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes](): -64 + def pep_696_bad[A=int, B =str, C= bool, D:object =int, E: object=str, F: object =bool, G: object= bytes](): -65 | pass - | +64 | def pep_696_bad[A=int, B =str, C= bool, D:object =int, E: object=str, F: object =bool, G: object= bytes](): + | + E252 [*] Missing whitespace around parameter equals --> E25.py:64:49 @@ -163,11 +136,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -63 | # There should be at least one E251 diagnostic for each type parameter here: - - def pep_696_bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes](): -64 + def pep_696_bad[A=int, B =str, C= bool, D:object= int, E: object=str, F: object =bool, G: object= bytes](): -65 | pass - | +64 | def pep_696_bad[A=int, B =str, C= bool, D:object= int, E: object=str, F: object =bool, G: object= bytes](): + | + E252 [*] Missing whitespace around parameter equals --> E25.py:64:64 @@ -179,11 +149,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -63 | # There should be at least one E251 diagnostic for each type parameter here: - - def pep_696_bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes](): -64 + def pep_696_bad[A=int, B =str, C= bool, D:object=int, E: object =str, F: object =bool, G: object= bytes](): -65 | pass - | +64 | def pep_696_bad[A=int, B =str, C= bool, D:object=int, E: object =str, F: object =bool, G: object= bytes](): + | + E252 [*] Missing whitespace around parameter equals --> E25.py:64:64 @@ -195,11 +162,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -63 | # There should be at least one E251 diagnostic for each type parameter here: - - def pep_696_bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes](): -64 + def pep_696_bad[A=int, B =str, C= bool, D:object=int, E: object= str, F: object =bool, G: object= bytes](): -65 | pass - | +64 | def pep_696_bad[A=int, B =str, C= bool, D:object=int, E: object= str, F: object =bool, G: object= bytes](): + | + E252 [*] Missing whitespace around parameter equals --> E25.py:64:80 @@ -211,11 +175,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -63 | # There should be at least one E251 diagnostic for each type parameter here: - - def pep_696_bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes](): -64 + def pep_696_bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object = bool, G: object= bytes](): -65 | pass - | +64 | def pep_696_bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object = bool, G: object= bytes](): + | + E252 [*] Missing whitespace around parameter equals --> E25.py:64:96 @@ -227,11 +188,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -63 | # There should be at least one E251 diagnostic for each type parameter here: - - def pep_696_bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes](): -64 + def pep_696_bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object = bytes](): -65 | pass - | +64 | def pep_696_bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object = bytes](): + | + E252 [*] Missing whitespace around parameter equals --> E25.py:67:18 @@ -244,11 +202,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -66 | - - class PEP696Bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes]: -67 + class PEP696Bad[A =int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes]: -68 | pass - | +67 | class PEP696Bad[A =int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes]: + | + E252 [*] Missing whitespace around parameter equals --> E25.py:67:18 @@ -261,11 +216,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -66 | - - class PEP696Bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes]: -67 + class PEP696Bad[A= int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes]: -68 | pass - | +67 | class PEP696Bad[A= int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes]: + | + E252 [*] Missing whitespace around parameter equals --> E25.py:67:26 @@ -278,11 +230,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -66 | - - class PEP696Bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes]: -67 + class PEP696Bad[A=int, B = str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes]: -68 | pass - | +67 | class PEP696Bad[A=int, B = str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes]: + | + E252 [*] Missing whitespace around parameter equals --> E25.py:67:33 @@ -295,11 +244,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -66 | - - class PEP696Bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes]: -67 + class PEP696Bad[A=int, B =str, C = bool, D:object=int, E: object=str, F: object =bool, G: object= bytes]: -68 | pass - | +67 | class PEP696Bad[A=int, B =str, C = bool, D:object=int, E: object=str, F: object =bool, G: object= bytes]: + | + E252 [*] Missing whitespace around parameter equals --> E25.py:67:49 @@ -312,11 +258,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -66 | - - class PEP696Bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes]: -67 + class PEP696Bad[A=int, B =str, C= bool, D:object =int, E: object=str, F: object =bool, G: object= bytes]: -68 | pass - | +67 | class PEP696Bad[A=int, B =str, C= bool, D:object =int, E: object=str, F: object =bool, G: object= bytes]: + | + E252 [*] Missing whitespace around parameter equals --> E25.py:67:49 @@ -329,11 +272,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -66 | - - class PEP696Bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes]: -67 + class PEP696Bad[A=int, B =str, C= bool, D:object= int, E: object=str, F: object =bool, G: object= bytes]: -68 | pass - | +67 | class PEP696Bad[A=int, B =str, C= bool, D:object= int, E: object=str, F: object =bool, G: object= bytes]: + | + E252 [*] Missing whitespace around parameter equals --> E25.py:67:64 @@ -346,11 +286,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -66 | - - class PEP696Bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes]: -67 + class PEP696Bad[A=int, B =str, C= bool, D:object=int, E: object =str, F: object =bool, G: object= bytes]: -68 | pass - | +67 | class PEP696Bad[A=int, B =str, C= bool, D:object=int, E: object =str, F: object =bool, G: object= bytes]: + | + E252 [*] Missing whitespace around parameter equals --> E25.py:67:64 @@ -363,11 +300,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -66 | - - class PEP696Bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes]: -67 + class PEP696Bad[A=int, B =str, C= bool, D:object=int, E: object= str, F: object =bool, G: object= bytes]: -68 | pass - | +67 | class PEP696Bad[A=int, B =str, C= bool, D:object=int, E: object= str, F: object =bool, G: object= bytes]: + | + E252 [*] Missing whitespace around parameter equals --> E25.py:67:80 @@ -380,11 +314,8 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -66 | - - class PEP696Bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes]: -67 + class PEP696Bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object = bool, G: object= bytes]: -68 | pass - | +67 | class PEP696Bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object = bool, G: object= bytes]: + | + E252 [*] Missing whitespace around parameter equals --> E25.py:67:96 @@ -397,8 +328,5 @@ E252 [*] Missing whitespace around parameter equals | help: Add missing whitespace | -66 | - - class PEP696Bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes]: -67 + class PEP696Bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object = bytes]: -68 | pass - | +67 | class PEP696Bad[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object = bytes]: + | + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E261_E26.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E261_E26.py.snap index 5ed1fa13560b1..8c0d956e1d033 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E261_E26.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E261_E26.py.snap @@ -12,8 +12,5 @@ E261 [*] Insert at least two spaces before an inline comment | help: Insert spaces | -1 | #: E261:1:5 - - pass # an inline comment -2 + pass # an inline comment -3 | #: E262:1:12 - | +2 | pass # an inline comment + | + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E262_E26.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E262_E26.py.snap index 4d68b8a2239b4..7169efb51c88c 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E262_E26.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E262_E26.py.snap @@ -13,11 +13,8 @@ E262 [*] Inline comment should start with `# ` | help: Format space | -3 | #: E262:1:12 - - x = x + 1 #Increment x -4 + x = x + 1 # Increment x -5 | #: E262:1:12 - | +4 | x = x + 1 # Increment x + | + E262 [*] Inline comment should start with `# ` --> E26.py:6:12 @@ -31,10 +28,8 @@ E262 [*] Inline comment should start with `# ` | help: Format space | -5 | #: E262:1:12 - - x = x + 1 # Increment x +6 - x = x + 1 # Increment x 6 + x = x + 1 # Increment x -7 | #: E262:1:12 | E262 [*] Inline comment should start with `# ` @@ -49,10 +44,8 @@ E262 [*] Inline comment should start with `# ` | help: Format space | -7 | #: E262:1:12 - - x = y + 1 #: Increment x +8 - x = y + 1 #: Increment x 8 + x = y + 1 #: Increment x -9 | #: E265:1:1 | E262 [*] Inline comment should start with `# ` @@ -67,10 +60,8 @@ E262 [*] Inline comment should start with `# ` | help: Format space | -62 | #  (One space one NBSP) Ok for block comment - - a = 42 #  (One space one NBSP) +63 - a = 42 #  (One space one NBSP) 63 + a = 42 # (One space one NBSP) -64 | #: E262:2:9 | E262 [*] Inline comment should start with `# ` @@ -85,10 +76,8 @@ E262 [*] Inline comment should start with `# ` | help: Format space | -65 | # (Two spaces) Ok for block comment - - a = 42 # (Two spaces) +66 - a = 42 # (Two spaces) 66 + a = 42 # (Two spaces) -67 | | E262 [*] Inline comment should start with `# ` @@ -103,10 +92,8 @@ E262 [*] Inline comment should start with `# ` | help: Format space | -83 | - - a = 1 ## Foo +84 - a = 1 ## Foo 84 + a = 1 # Foo -85 | | E262 [*] Inline comment should start with `# ` @@ -118,7 +105,5 @@ E262 [*] Inline comment should start with `# ` | ^^^^^ help: Format space | -85 | - - a = 1 #:Foo -86 + a = 1 #: Foo - | +86 | a = 1 #: Foo + | + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E265_E26.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E265_E26.py.snap index d2dbcff0b0fde..877fd0323374a 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E265_E26.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E265_E26.py.snap @@ -13,11 +13,8 @@ E265 [*] Block comment should start with `# ` | help: Format space | -9 | #: E265:1:1 - - #Block comment -10 + # Block comment -11 | a = 1 - | +10 | # Block comment + | + E265 [*] Block comment should start with `# ` --> E26.py:14:1 @@ -31,11 +28,8 @@ E265 [*] Block comment should start with `# ` | help: Format space | -13 | m = 42 - - #! This is important -14 + # ! This is important -15 | mx = 42 - 42 - | +14 | # ! This is important + | + E265 [*] Block comment should start with `# ` --> E26.py:25:1 @@ -49,10 +43,8 @@ E265 [*] Block comment should start with `# ` | help: Format space | -24 | #: E265:1:1 E266:2:1 - - ##if DEBUG: +25 - ##if DEBUG: 25 + # if DEBUG: -26 | ## logging.error() | E265 [*] Block comment should start with `# ` @@ -66,11 +58,8 @@ E265 [*] Block comment should start with `# ` | help: Format space | -31 | #: Okay - - #!/usr/bin/env python -32 + # !/usr/bin/env python -33 | - | +32 | # !/usr/bin/env python + | + E265 [*] Block comment should start with `# ` --> E26.py:73:1 @@ -83,11 +72,8 @@ E265 [*] Block comment should start with `# ` | help: Format space | -72 | # EF Means test is giving error and Failing - - #! Means test is segfaulting -73 + # ! Means test is segfaulting -74 | # 8 Means test runs forever - | +73 | # ! Means test is segfaulting + | + E265 [*] Block comment should start with `# ` --> E26.py:78:1 @@ -101,8 +87,6 @@ E265 [*] Block comment should start with `# ` | help: Format space | -77 | - - ###This is a variable ### +78 - ###This is a variable ### 78 + # This is a variable ### -79 | | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E266_E26.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E266_E26.py.snap index 6d882f3be0dda..3b858c1dd70af 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E266_E26.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E266_E26.py.snap @@ -12,10 +12,8 @@ E266 [*] Too many leading `#` before block comment | help: Remove leading `#` | -18 | - - ### This is a variable ### +19 - ### This is a variable ### 19 + # This is a variable ### -20 | a = 42 | E266 [*] Too many leading `#` before block comment @@ -30,10 +28,8 @@ E266 [*] Too many leading `#` before block comment | help: Remove leading `#` | -21 | - - ### Of course it is unused +22 - ### Of course it is unused 22 + # Of course it is unused -23 | return | E266 [*] Too many leading `#` before block comment @@ -48,10 +44,8 @@ E266 [*] Too many leading `#` before block comment | help: Remove leading `#` | -25 | ##if DEBUG: - - ## logging.error() +26 - ## logging.error() 26 + # logging.error() -27 | #: W291:1:42 | E266 [*] Too many leading `#` before block comment @@ -65,10 +59,8 @@ E266 [*] Too many leading `#` before block comment | help: Remove leading `#` | -68 | #: E265:5:1 - - ### Means test is not done yet +69 - ### Means test is not done yet 69 + # Means test is not done yet -70 | # E Means test is giving error (E) | E266 [*] Too many leading `#` before block comment @@ -83,8 +75,6 @@ E266 [*] Too many leading `#` before block comment | help: Remove leading `#` | -81 | #: E266:1:3 - - ## Foo +82 - ## Foo 82 + # Foo -83 | | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E271_E27.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E271_E27.py.snap index 130fbdbfc6b5f..b9431b6ff06d2 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E271_E27.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E271_E27.py.snap @@ -13,11 +13,8 @@ E271 [*] Multiple spaces after keyword | help: Replace with single space | -3 | #: E271 - - True and False -4 + True and False -5 | #: E272 - | +4 | True and False + | + E271 [*] Multiple spaces after keyword --> E27.py:6:5 @@ -31,11 +28,8 @@ E271 [*] Multiple spaces after keyword | help: Replace with single space | -5 | #: E272 - - True and False -6 + True and False -7 | #: E271 - | +6 | True and False + | + E271 [*] Multiple spaces after keyword --> E27.py:8:3 @@ -49,11 +43,8 @@ E271 [*] Multiple spaces after keyword | help: Replace with single space | -7 | #: E271 - - if 1: -8 + if 1: -9 | pass - | +8 | if 1: + | + E271 [*] Multiple spaces after keyword --> E27.py:15:6 @@ -67,11 +58,8 @@ E271 [*] Multiple spaces after keyword | help: Replace with single space | -14 | #: E271 - - a and b -15 + a and b -16 | #: E271 - | +15 | a and b + | + E271 [*] Multiple spaces after keyword --> E27.py:17:6 @@ -85,11 +73,8 @@ E271 [*] Multiple spaces after keyword | help: Replace with single space | -16 | #: E271 - - 1 and b -17 + 1 and b -18 | #: E271 - | +17 | 1 and b + | + E271 [*] Multiple spaces after keyword --> E27.py:19:6 @@ -103,11 +88,8 @@ E271 [*] Multiple spaces after keyword | help: Replace with single space | -18 | #: E271 - - a and 2 -19 + a and 2 -20 | #: E271 E272 - | +19 | a and 2 + | + E271 [*] Multiple spaces after keyword --> E27.py:21:7 @@ -121,11 +103,8 @@ E271 [*] Multiple spaces after keyword | help: Replace with single space | -20 | #: E271 E272 - - 1 and b -21 + 1 and b -22 | #: E271 E272 - | +21 | 1 and b + | + E271 [*] Multiple spaces after keyword --> E27.py:23:7 @@ -139,11 +118,8 @@ E271 [*] Multiple spaces after keyword | help: Replace with single space | -22 | #: E271 E272 - - a and 2 -23 + a and 2 -24 | #: E272 - | +23 | a and 2 + | + E271 [*] Multiple spaces after keyword --> E27.py:36:14 @@ -157,11 +133,8 @@ E271 [*] Multiple spaces after keyword | help: Replace with single space | -35 | #: E271 - - from w import (e, f) -36 + from w import (e, f) -37 | #: E275 - | +36 | from w import (e, f) + | + E271 [*] Multiple spaces after keyword --> E27.py:71:5 @@ -174,8 +147,5 @@ E271 [*] Multiple spaces after keyword | help: Replace with single space | -70 | #: E271 - - type Number = int -71 + type Number = int -72 | - | +71 | type Number = int + | + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E272_E27.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E272_E27.py.snap index 56754d1f2ac34..7cc86b737ce50 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E272_E27.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E272_E27.py.snap @@ -13,11 +13,8 @@ E272 [*] Multiple spaces before keyword | help: Replace with single space | -20 | #: E271 E272 - - 1 and b -21 + 1 and b -22 | #: E271 E272 - | +21 | 1 and b + | + E272 [*] Multiple spaces before keyword --> E27.py:23:2 @@ -31,11 +28,8 @@ E272 [*] Multiple spaces before keyword | help: Replace with single space | -22 | #: E271 E272 - - a and 2 -23 + a and 2 -24 | #: E272 - | +23 | a and 2 + | + E272 [*] Multiple spaces before keyword --> E27.py:25:5 @@ -49,8 +43,5 @@ E272 [*] Multiple spaces before keyword | help: Replace with single space | -24 | #: E272 - - this and False -25 + this and False -26 | #: E273 - | +25 | this and False + | + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E273_E27.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E273_E27.py.snap index c043d7a85242a..d838601787971 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E273_E27.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E273_E27.py.snap @@ -13,11 +13,8 @@ E273 [*] Tab after keyword | help: Replace with single space | -10 | #: E273 - - True and False -11 + True and False -12 | #: E273 E274 - | +11 | True and False + | + E273 [*] Tab after keyword --> E27.py:13:5 @@ -31,11 +28,8 @@ E273 [*] Tab after keyword | help: Replace with single space | -12 | #: E273 E274 - - True and False -13 + True and False -14 | #: E271 - | +13 | True and False + | + E273 [*] Tab after keyword --> E27.py:13:10 @@ -49,11 +43,8 @@ E273 [*] Tab after keyword | help: Replace with single space | -12 | #: E273 E274 - - True and False -13 + True and False -14 | #: E271 - | +13 | True and False + | + E273 [*] Tab after keyword --> E27.py:27:6 @@ -67,11 +58,8 @@ E273 [*] Tab after keyword | help: Replace with single space | -26 | #: E273 - - a and b -27 + a and b -28 | #: E274 - | +27 | a and b + | + E273 [*] Tab after keyword --> E27.py:31:10 @@ -85,11 +73,8 @@ E273 [*] Tab after keyword | help: Replace with single space | -30 | #: E273 E274 - - this and False -31 + this and False -32 | #: Okay - | +31 | this and False + | + E273 [*] Tab after keyword --> E27.py:74:5 @@ -102,8 +87,5 @@ E273 [*] Tab after keyword | help: Replace with single space | -73 | #: E273 - - type Number = int -74 + type Number = int -75 | - | +74 | type Number = int + | + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E274_E27.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E274_E27.py.snap index 567343463323d..e0d588c1e7f8a 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E274_E27.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E274_E27.py.snap @@ -13,11 +13,8 @@ E274 [*] Tab before keyword | help: Replace with single space | -28 | #: E274 - - a and b -29 + a and b -30 | #: E273 E274 - | +29 | a and b + | + E274 [*] Tab before keyword --> E27.py:31:5 @@ -31,8 +28,5 @@ E274 [*] Tab before keyword | help: Replace with single space | -30 | #: E273 E274 - - this and False -31 + this and False -32 | #: Okay - | +31 | this and False + | + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E275_E27.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E275_E27.py.snap index e72ee38f659e6..9eb7e29e258e5 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E275_E27.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E275_E27.py.snap @@ -13,11 +13,8 @@ E275 [*] Missing whitespace after keyword | help: Added missing whitespace after keyword | -37 | #: E275 - - from w import(e, f) -38 + from w import (e, f) -39 | #: E275 - | +38 | from w import (e, f) + | + E275 [*] Missing whitespace after keyword --> E27.py:40:24 @@ -31,11 +28,8 @@ E275 [*] Missing whitespace after keyword | help: Added missing whitespace after keyword | -39 | #: E275 - - from importable.module import(e, f) -40 + from importable.module import (e, f) -41 | #: E275 - | +40 | from importable.module import (e, f) + | + E275 [*] Missing whitespace after keyword --> E27.py:43:28 @@ -49,11 +43,8 @@ E275 [*] Missing whitespace after keyword | help: Added missing whitespace after keyword | -42 | try: - - from importable.module import(e, f) -43 + from importable.module import (e, f) -44 | except ImportError: - | +43 | from importable.module import (e, f) + | + E275 [*] Missing whitespace after keyword --> E27.py:47:1 @@ -67,11 +58,8 @@ E275 [*] Missing whitespace after keyword | help: Added missing whitespace after keyword | -46 | #: E275 - - if(foo): -47 + if (foo): -48 | pass - | +47 | if (foo): + | + E275 [*] Missing whitespace after keyword --> E27.py:55:5 @@ -85,11 +73,8 @@ E275 [*] Missing whitespace after keyword | help: Added missing whitespace after keyword | -54 | if True: - - assert(1) -55 + assert (1) -56 | #: Okay - | +55 | assert (1) + | + E275 [*] Missing whitespace after keyword --> E27.py:77:1 @@ -102,11 +87,8 @@ E275 [*] Missing whitespace after keyword | help: Added missing whitespace after keyword | -76 | #: E275 - - match(foo): -77 + match (foo): -78 | case(1): - | +77 | match (foo): + | + E275 [*] Missing whitespace after keyword --> E27.py:78:5 @@ -119,8 +101,5 @@ E275 [*] Missing whitespace after keyword | help: Added missing whitespace after keyword | -77 | match(foo): - - case(1): -78 + case (1): -79 | pass - | +78 | case (1): + | + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E301_E30.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E301_E30.py.snap index 36428f9476f3c..56a300a3cef12 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E301_E30.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E301_E30.py.snap @@ -12,10 +12,7 @@ E301 [*] Expected 1 blank line, found 0 480 | # end | help: Add missing blank line - | -477 | pass -478 + -479 | def func2(): +478 - def func2(): | E301 [*] Expected 1 blank line, found 0 @@ -29,10 +26,7 @@ E301 [*] Expected 1 blank line, found 0 491 | # end | help: Add missing blank line - | -487 | pass -488 + -489 | # comment +488 - # comment | E301 [*] Expected 1 blank line, found 0 @@ -45,10 +39,7 @@ E301 [*] Expected 1 blank line, found 0 501 | pass | help: Add missing blank line - | -498 | columns = [] -499 + -500 | @classmethod +499 - @classmethod | E301 [*] Expected 1 blank line, found 0 @@ -62,10 +53,7 @@ E301 [*] Expected 1 blank line, found 0 513 | pass | help: Add missing blank line - | -510 | pass -511 + -512 | @classmethod +511 - @classmethod | E301 [*] Expected 1 blank line, found 0 @@ -79,10 +67,7 @@ E301 [*] Expected 1 blank line, found 0 528 | # end | help: Add missing blank line - | -525 | ... -526 + -527 | def bar(self, x: int | str) -> int | str: +526 - def bar(self, x: int | str) -> int | str: | E301 [*] Expected 1 blank line, found 0 @@ -96,8 +81,5 @@ E301 [*] Expected 1 blank line, found 0 995 | # end | help: Add missing blank line - | -992 | print("conditional") -993 + -994 | def test(): +993 - def test(): | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E303_E30.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E303_E30.py.snap index 07c466c48c73e..f273a22c36b6a 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E303_E30.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E303_E30.py.snap @@ -10,10 +10,8 @@ E303 [*] Too many blank lines (2) 619 | # end | help: Remove extraneous blank line(s) - | -615 | - - -616 | def method2(): +615 - +616 - | E303 [*] Too many blank lines (2) @@ -25,10 +23,8 @@ E303 [*] Too many blank lines (2) 646 | def inner(): # E306 not expected (pycodestyle detects E306) | help: Remove extraneous blank line(s) - | -642 | - - -643 | # arbitrary comment +642 - +643 - | E303 [*] Too many blank lines (2) @@ -40,10 +36,8 @@ E303 [*] Too many blank lines (2) 658 | pass | help: Remove extraneous blank line(s) - | -654 | - - -655 | # arbitrary comment +654 - +655 - | E303 [*] Too many blank lines (3) @@ -54,10 +48,9 @@ E303 [*] Too many blank lines (3) 668 | # end | help: Remove extraneous blank line(s) - | -665 | - - -666 | print() +664 - +665 - +666 - | E303 [*] Too many blank lines (3) @@ -69,10 +62,9 @@ E303 [*] Too many blank lines (3) 678 | print() | help: Remove extraneous blank line(s) - | -674 | - - -675 | # comment +673 - +674 - +675 - | E303 [*] Too many blank lines (2) @@ -81,10 +73,8 @@ E303 [*] Too many blank lines (2) 687 | # comment | ^^^^^^^^^ help: Remove extraneous blank line(s) - | -685 | - - -686 | # comment +685 - +686 - | E303 [*] Too many blank lines (2) @@ -96,10 +86,8 @@ E303 [*] Too many blank lines (2) 692 | print() | help: Remove extraneous blank line(s) - | -688 | - - -689 | # another comment +688 - +689 - | E303 [*] Too many blank lines (3) @@ -112,10 +100,9 @@ E303 [*] Too many blank lines (3) 704 | # end | help: Remove extraneous blank line(s) - | -699 | - - -700 | """This class docstring comes on line 5. +698 - +699 - +700 - | E303 [*] Too many blank lines (2) @@ -127,10 +114,8 @@ E303 [*] Too many blank lines (2) 715 | # end | help: Remove extraneous blank line(s) - | -711 | - - -712 | def b(self): +711 - +712 - | E303 [*] Too many blank lines (2) @@ -141,10 +126,8 @@ E303 [*] Too many blank lines (2) 724 | # end | help: Remove extraneous blank line(s) - | -721 | - - -722 | a = 2 +721 - +722 - | E303 [*] Too many blank lines (2) @@ -153,10 +136,8 @@ E303 [*] Too many blank lines (2) 731 | # comment | ^^^^^^^^^ help: Remove extraneous blank line(s) - | -729 | - - -730 | # comment +729 - +730 - | E303 [*] Too many blank lines (2) @@ -168,10 +149,8 @@ E303 [*] Too many blank lines (2) 736 | def test(self): pass | help: Remove extraneous blank line(s) - | -732 | - - -733 | # another comment +732 - +733 - | E303 [*] Too many blank lines (2) @@ -183,10 +162,8 @@ E303 [*] Too many blank lines (2) 750 | # end | help: Remove extraneous blank line(s) - | -746 | - - -747 | def b(self): +746 - +747 - | E303 [*] Too many blank lines (2) @@ -197,8 +174,6 @@ E303 [*] Too many blank lines (2) 759 | # end | help: Remove extraneous blank line(s) - | -756 | - - -757 | pass +756 - +757 - | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E303_E303_first_line_comment.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E303_E303_first_line_comment.py.snap index 806c1cd8df906..b76eeedb2b97c 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E303_E303_first_line_comment.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E303_E303_first_line_comment.py.snap @@ -9,8 +9,7 @@ E303 [*] Too many blank lines (3) 6 | pass | help: Remove extraneous blank line(s) - | -3 | - - -4 | def fn(): +2 - +3 - +4 - | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E303_E303_first_line_docstring.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E303_E303_first_line_docstring.py.snap index bc91c83b8c5ae..0ddbcf033a36b 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E303_E303_first_line_docstring.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E303_E303_first_line_docstring.py.snap @@ -9,8 +9,7 @@ E303 [*] Too many blank lines (3) 6 | pass | help: Remove extraneous blank line(s) - | -3 | - - -4 | def fn(): +2 - +3 - +4 - | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E303_E303_first_line_expression.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E303_E303_first_line_expression.py.snap index f17a4e20a72e7..4b9ecdd04dd5f 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E303_E303_first_line_expression.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E303_E303_first_line_expression.py.snap @@ -9,8 +9,7 @@ E303 [*] Too many blank lines (3) 6 | pass | help: Remove extraneous blank line(s) - | -3 | - - -4 | def fn(): +2 - +3 - +4 - | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E303_E303_first_line_statement.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E303_E303_first_line_statement.py.snap index a3dfe8a08a084..e73b530526265 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E303_E303_first_line_statement.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E303_E303_first_line_statement.py.snap @@ -9,8 +9,7 @@ E303 [*] Too many blank lines (3) 6 | pass | help: Remove extraneous blank line(s) - | -3 | - - -4 | def fn(): +2 - +3 - +4 - | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E304_E30.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E304_E30.py.snap index 2b603c573f977..0521165ef3f05 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E304_E30.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E304_E30.py.snap @@ -12,10 +12,7 @@ E304 [*] Blank lines found after function decorator (1) 767 | # end | help: Remove extraneous blank line(s) - | -763 | @decorator - - -764 | def function(): +764 - | E304 [*] Blank lines found after function decorator (1) @@ -29,9 +26,7 @@ E304 [*] Blank lines found after function decorator (1) | help: Remove extraneous blank line(s) | -771 | @decorator - - -772 | # comment E304 not expected +772 + # comment E304 not expected | E304 [*] Blank lines found after function decorator (2) @@ -45,10 +40,6 @@ E304 [*] Blank lines found after function decorator (2) | help: Remove extraneous blank line(s) | -780 | @decorator - - -781 | # comment E304 not expected - - - - -782 | # second comment E304 not expected +781 + # comment E304 not expected +782 + # second comment E304 not expected | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E306_E30.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E306_E30.py.snap index 70c68352bdc58..d70291c6eaeda 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E306_E30.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E306_E30.py.snap @@ -12,10 +12,7 @@ E306 [*] Expected 1 blank line before a nested definition, found 0 856 | # end | help: Add missing blank line - | -853 | x = 1 -854 + -855 | def b(): +854 - def b(): | E306 [*] Expected 1 blank line before a nested definition, found 0 @@ -29,10 +26,7 @@ E306 [*] Expected 1 blank line before a nested definition, found 0 864 | # end | help: Add missing blank line - | -861 | x = 1 -862 + -863 | def b(): +862 - def b(): | E306 [*] Expected 1 blank line before a nested definition, found 0 @@ -46,10 +40,7 @@ E306 [*] Expected 1 blank line before a nested definition, found 0 872 | def c(): | help: Add missing blank line - | -869 | x = 2 -870 + -871 | def b(): +870 - def b(): | E306 [*] Expected 1 blank line before a nested definition, found 0 @@ -63,10 +54,7 @@ E306 [*] Expected 1 blank line before a nested definition, found 0 874 | # end | help: Add missing blank line - | -871 | x = 1 -872 + -873 | def c(): +872 - def c(): | E306 [*] Expected 1 blank line before a nested definition, found 0 @@ -80,10 +68,7 @@ E306 [*] Expected 1 blank line before a nested definition, found 0 882 | x = 2 | help: Add missing blank line - | -879 | x = 1 -880 + -881 | class C: +880 - class C: | E306 [*] Expected 1 blank line before a nested definition, found 0 @@ -97,10 +82,7 @@ E306 [*] Expected 1 blank line before a nested definition, found 0 885 | # end | help: Add missing blank line - | -882 | x = 2 -883 + -884 | def b(): +883 - def b(): | E306 [*] Expected 1 blank line before a nested definition, found 0 @@ -113,10 +95,7 @@ E306 [*] Expected 1 blank line before a nested definition, found 0 893 | # end | help: Add missing blank line - | -891 | pass -892 + -893 | def baz(): pass +892 - def baz(): pass | E306 [*] Expected 1 blank line before a nested definition, found 0 @@ -130,10 +109,7 @@ E306 [*] Expected 1 blank line before a nested definition, found 0 901 | # end | help: Add missing blank line - | -898 | def bar(): pass -899 + -900 | def baz(): +899 - def baz(): | E306 [*] Expected 1 blank line before a nested definition, found 0 @@ -147,10 +123,7 @@ E306 [*] Expected 1 blank line before a nested definition, found 0 909 | pass | help: Add missing blank line - | -906 | x = 2 -907 + -908 | @decorator +907 - @decorator | E306 [*] Expected 1 blank line before a nested definition, found 0 @@ -164,10 +137,7 @@ E306 [*] Expected 1 blank line before a nested definition, found 0 918 | pass | help: Add missing blank line - | -915 | x = 2 -916 + -917 | @decorator +916 - @decorator | E306 [*] Expected 1 blank line before a nested definition, found 0 @@ -181,10 +151,7 @@ E306 [*] Expected 1 blank line before a nested definition, found 0 927 | # end | help: Add missing blank line - | -924 | x = 2 -925 + -926 | async def b(): +925 - async def b(): | E306 [*] Expected 1 blank line before a nested definition, found 0 @@ -198,10 +165,7 @@ E306 [*] Expected 1 blank line before a nested definition, found 0 985 | loop.add_reader(self._fd, callback) | help: Add missing blank line - | -982 | loop = asyncio.get_event_loop() -983 + -984 | def callback(): +983 - def callback(): | E306 [*] Expected 1 blank line before a nested definition, found 0 @@ -215,10 +179,7 @@ E306 [*] Expected 1 blank line before a nested definition, found 0 1004 | return 2 | help: Add missing blank line - | -1001 | x = 1 -1002 + -1003 | def g(): +1002 - def g(): | E306 [*] Expected 1 blank line before a nested definition, found 0 @@ -232,8 +193,5 @@ E306 [*] Expected 1 blank line before a nested definition, found 0 1011 | return 2 | help: Add missing blank line - | -1008 | x = 1 -1009 + -1010 | def g(): +1009 - def g(): | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E401_E40.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E401_E40.py.snap index 2d8883eb252f6..19095ffc212fa 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E401_E40.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E401_E40.py.snap @@ -12,11 +12,8 @@ E401 [*] Multiple imports on one line | help: Split imports | -1 | #: E401 - - import os, sys 2 + import os 3 + import sys -4 | | E401 [*] Multiple imports on one line @@ -29,11 +26,8 @@ E401 [*] Multiple imports on one line | help: Split imports | -64 | #: E401 - - import re as regex, string # also with a comment! 65 + import re as regex -66 + import string # also with a comment! -67 | import re as regex, string; x = 1 +66 ~ import string # also with a comment! | E401 [*] Multiple imports on one line @@ -48,10 +42,8 @@ E401 [*] Multiple imports on one line | help: Split imports | -65 | import re as regex, string # also with a comment! - - import re as regex, string; x = 1 +66 - import re as regex, string; x = 1 66 + import re as regex; import string; x = 1 -67 | | E401 [*] Multiple imports on one line @@ -63,10 +55,8 @@ E401 [*] Multiple imports on one line | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Split imports | -67 | - - x = 1; import re as regex, string +68 - x = 1; import re as regex, string 68 + x = 1; import re as regex; import string -69 | | E401 [*] Multiple imports on one line @@ -80,11 +70,8 @@ E401 [*] Multiple imports on one line | help: Split imports | -71 | def blah(): - - import datetime as dt, copy 72 + import datetime as dt 73 + import copy -74 | | E401 [*] Multiple imports on one line @@ -98,11 +85,8 @@ E401 [*] Multiple imports on one line | help: Split imports | -74 | def nested_and_tested(): - - import builtins, textwrap as tw 75 + import builtins 76 + import textwrap as tw -77 | | E401 [*] Multiple imports on one line @@ -116,10 +100,8 @@ E401 [*] Multiple imports on one line | help: Split imports | -76 | - - x = 1; import re as regex, string +77 - x = 1; import re as regex, string 77 + x = 1; import re as regex; import string -78 | import re as regex, string; x = 1 | E401 [*] Multiple imports on one line @@ -133,10 +115,8 @@ E401 [*] Multiple imports on one line | help: Split imports | -77 | x = 1; import re as regex, string - - import re as regex, string; x = 1 +78 - import re as regex, string; x = 1 78 + import re as regex; import string; x = 1 -79 | | E401 [*] Multiple imports on one line @@ -148,7 +128,6 @@ E401 [*] Multiple imports on one line | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Split imports | -79 | - - if True: import re as regex, string +80 - if True: import re as regex, string 80 + if True: import re as regex; import string | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E703_E70.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E703_E70.py.snap index 06bd743077b95..ca980e8f003e8 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E703_E70.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E703_E70.py.snap @@ -13,10 +13,8 @@ E703 [*] Statement ends with an unnecessary semicolon | help: Remove unnecessary semicolon | -9 | #: E703:1:13 - - import shlex; +10 - import shlex; 10 + import shlex -11 | #: E702:1:9 E703:1:23 | E703 [*] Statement ends with an unnecessary semicolon @@ -31,10 +29,8 @@ E703 [*] Statement ends with an unnecessary semicolon | help: Remove unnecessary semicolon | -11 | #: E702:1:9 E703:1:23 - - del a[:]; a.append(42); +12 - del a[:]; a.append(42); 12 + del a[:]; a.append(42) -13 | #: E704:1:1 | E703 [*] Statement ends with an unnecessary semicolon @@ -49,10 +45,8 @@ E703 [*] Statement ends with an unnecessary semicolon | help: Remove unnecessary semicolon | -24 | #: E704:1:8 E702:1:11 E703:1:14 - - if True: x; y; +25 - if True: x; y; 25 + if True: x; y -26 | #: E701:1:8 | E703 [*] Statement ends with an unnecessary semicolon @@ -67,11 +61,9 @@ E703 [*] Statement ends with an unnecessary semicolon | help: Remove unnecessary semicolon | -66 | #: E703:2:1 - - 0\ - - ; +67 - 0\ +68 - ; 67 + 0 -68 | #: E701:2:3 | E703 [*] Statement ends with an unnecessary semicolon @@ -86,8 +78,6 @@ E703 [*] Statement ends with an unnecessary semicolon | help: Remove unnecessary semicolon | -70 | a = \ - - 5; +71 - 5; 71 + 5 -72 | #: | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E703_E703.ipynb.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E703_E703.ipynb.snap index a8775bb731a5a..d0c53bfd23715 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E703_E703.ipynb.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E703_E703.ipynb.snap @@ -13,10 +13,8 @@ E703 [*] Statement ends with an unnecessary semicolon | help: Remove unnecessary semicolon | -4 | # Only skip the last expression - - x; # E703 +5 - x; # E703 5 + x # E703 -6 | x; | E703 [*] Statement ends with an unnecessary semicolon @@ -30,9 +28,7 @@ E703 [*] Statement ends with an unnecessary semicolon 11 | x; x; | help: Remove unnecessary semicolon - | -8 | if True: - - x; -9 + x -10 | # Semicolons with multiple expressions - | + | +9 - x; +9 + x + | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E711_E711.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E711_E711.py.snap index 9edbdbce0f7ed..6a3f964ad47ad 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E711_E711.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E711_E711.py.snap @@ -12,10 +12,8 @@ E711 [*] Comparison to `None` should be `cond is None` | help: Replace with `cond is None` | -1 | #: E711 - - if res == None: +2 - if res == None: 2 + if res is None: -3 | pass | note: This is an unsafe fix and may change runtime behavior @@ -31,10 +29,8 @@ E711 [*] Comparison to `None` should be `cond is not None` | help: Replace with `cond is not None` | -4 | #: E711 - - if res != None: +5 - if res != None: 5 + if res is not None: -6 | pass | note: This is an unsafe fix and may change runtime behavior @@ -50,10 +46,8 @@ E711 [*] Comparison to `None` should be `cond is None` | help: Replace with `cond is None` | -7 | #: E711 - - if None == res: +8 - if None == res: 8 + if None is res: -9 | pass | note: This is an unsafe fix and may change runtime behavior @@ -69,10 +63,8 @@ E711 [*] Comparison to `None` should be `cond is not None` | help: Replace with `cond is not None` | -10 | #: E711 - - if None != res: +11 - if None != res: 11 + if None is not res: -12 | pass | note: This is an unsafe fix and may change runtime behavior @@ -88,10 +80,8 @@ E711 [*] Comparison to `None` should be `cond is None` | help: Replace with `cond is None` | -13 | #: E711 - - if res[1] == None: +14 - if res[1] == None: 14 + if res[1] is None: -15 | pass | note: This is an unsafe fix and may change runtime behavior @@ -107,10 +97,8 @@ E711 [*] Comparison to `None` should be `cond is not None` | help: Replace with `cond is not None` | -16 | #: E711 - - if res[1] != None: +17 - if res[1] != None: 17 + if res[1] is not None: -18 | pass | note: This is an unsafe fix and may change runtime behavior @@ -126,10 +114,8 @@ E711 [*] Comparison to `None` should be `cond is not None` | help: Replace with `cond is not None` | -19 | #: E711 - - if None != res[1]: +20 - if None != res[1]: 20 + if None is not res[1]: -21 | pass | note: This is an unsafe fix and may change runtime behavior @@ -144,10 +130,8 @@ E711 [*] Comparison to `None` should be `cond is None` | help: Replace with `cond is None` | -22 | #: E711 - - if None == res[1]: +23 - if None == res[1]: 23 + if None is res[1]: -24 | pass | note: This is an unsafe fix and may change runtime behavior @@ -162,10 +146,8 @@ E711 [*] Comparison to `None` should be `cond is None` | help: Replace with `cond is None` | -25 | - - if x == None != None: +26 - if x == None != None: 26 + if x is None is not None: -27 | pass | note: This is an unsafe fix and may change runtime behavior @@ -180,9 +162,7 @@ E711 [*] Comparison to `None` should be `cond is not None` | help: Replace with `cond is not None` | -25 | - - if x == None != None: +26 - if x == None != None: 26 + if x is None is not None: -27 | pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E712_E712.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E712_E712.py.snap index 7328806a23649..f93efac47e26a 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E712_E712.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E712_E712.py.snap @@ -12,10 +12,8 @@ E712 [*] Avoid equality comparisons to `True`; use `res:` for truth checks | help: Replace with `res` | -1 | #: E712 - - if res == True: +2 - if res == True: 2 + if res: -3 | pass | note: This is an unsafe fix and may change runtime behavior @@ -31,10 +29,8 @@ E712 [*] Avoid inequality comparisons to `False`; use `res:` for truth checks | help: Replace with `res` | -4 | #: E712 - - if res != False: +5 - if res != False: 5 + if res: -6 | pass | note: This is an unsafe fix and may change runtime behavior @@ -50,10 +46,8 @@ E712 [*] Avoid inequality comparisons to `True`; use `not res:` for false checks | help: Replace with `not res` | -7 | #: E712 - - if True != res: +8 - if True != res: 8 + if not res: -9 | pass | note: This is an unsafe fix and may change runtime behavior @@ -69,10 +63,8 @@ E712 [*] Avoid equality comparisons to `False`; use `not res:` for false checks | help: Replace with `not res` | -10 | #: E712 - - if False == res: +11 - if False == res: 11 + if not res: -12 | pass | note: This is an unsafe fix and may change runtime behavior @@ -88,10 +80,8 @@ E712 [*] Avoid equality comparisons to `True`; use `res[1]:` for truth checks | help: Replace with `res[1]` | -13 | #: E712 - - if res[1] == True: +14 - if res[1] == True: 14 + if res[1]: -15 | pass | note: This is an unsafe fix and may change runtime behavior @@ -107,10 +97,8 @@ E712 [*] Avoid inequality comparisons to `False`; use `res[1]:` for truth checks | help: Replace with `res[1]` | -16 | #: E712 - - if res[1] != False: +17 - if res[1] != False: 17 + if res[1]: -18 | pass | note: This is an unsafe fix and may change runtime behavior @@ -126,10 +114,8 @@ E712 [*] Avoid equality comparisons to `True`; use `cond:` for truth checks | help: Replace with `cond` | -19 | #: E712 - - var = 1 if cond == True else -1 if cond == False else cond +20 - var = 1 if cond == True else -1 if cond == False else cond 20 + var = 1 if cond else -1 if cond == False else cond -21 | #: E712 | note: This is an unsafe fix and may change runtime behavior @@ -145,10 +131,8 @@ E712 [*] Avoid equality comparisons to `False`; use `not cond:` for false checks | help: Replace with `not cond` | -19 | #: E712 - - var = 1 if cond == True else -1 if cond == False else cond +20 - var = 1 if cond == True else -1 if cond == False else cond 20 + var = 1 if cond == True else -1 if not cond else cond -21 | #: E712 | note: This is an unsafe fix and may change runtime behavior @@ -163,10 +147,8 @@ E712 [*] Avoid equality comparisons to `True`; use `TrueElement:` for truth chec | help: Replace with `TrueElement` | -21 | #: E712 - - if (True) == TrueElement or x == TrueElement: +22 - if (True) == TrueElement or x == TrueElement: 22 + if (TrueElement) or x == TrueElement: -23 | pass | note: This is an unsafe fix and may change runtime behavior @@ -181,10 +163,8 @@ E712 [*] Avoid equality comparisons to `True` or `False` | help: Replace comparison | -24 | - - if res == True != False: +25 - if res == True != False: 25 + if res is True is not False: -26 | pass | note: This is an unsafe fix and may change runtime behavior @@ -199,10 +179,8 @@ E712 [*] Avoid equality comparisons to `True` or `False` | help: Replace comparison | -24 | - - if res == True != False: +25 - if res == True != False: 25 + if res is True is not False: -26 | pass | note: This is an unsafe fix and may change runtime behavior @@ -217,10 +195,8 @@ E712 [*] Avoid equality comparisons to `True`; use `TrueElement:` for truth chec | help: Replace with `TrueElement` | -27 | - - if(True) == TrueElement or x == TrueElement: +28 - if(True) == TrueElement or x == TrueElement: 28 + if(TrueElement) or x == TrueElement: -29 | pass | note: This is an unsafe fix and may change runtime behavior @@ -235,10 +211,8 @@ E712 [*] Avoid equality comparisons to `True`; use `yield i:` for truth checks | help: Replace with `yield i` | -30 | - - if (yield i) == True: +31 - if (yield i) == True: 31 + if (yield i): -32 | print("even") | note: This is an unsafe fix and may change runtime behavior @@ -252,9 +226,7 @@ E712 [*] Avoid equality comparisons to `True`; use `True:` for truth checks | help: Replace with `True` | -57 | # https://github.com/astral-sh/ruff/issues/17582 - - if True == True: # No duplicated diagnostic +58 - if True == True: # No duplicated diagnostic 58 + if True: # No duplicated diagnostic -59 | pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E713_E713.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E713_E713.py.snap index b717528565cc6..320d3ff29b38b 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E713_E713.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E713_E713.py.snap @@ -12,10 +12,8 @@ E713 [*] Test for membership should be `not in` | help: Convert to `not in` | -1 | #: E713 - - if not X in Y: +2 - if not X in Y: 2 + if X not in Y: -3 | pass | E713 [*] Test for membership should be `not in` @@ -30,10 +28,8 @@ E713 [*] Test for membership should be `not in` | help: Convert to `not in` | -4 | #: E713 - - if not X.B in Y: +5 - if not X.B in Y: 5 + if X.B not in Y: -6 | pass | E713 [*] Test for membership should be `not in` @@ -48,10 +44,8 @@ E713 [*] Test for membership should be `not in` | help: Convert to `not in` | -7 | #: E713 - - if not X in Y and Z == "zero": +8 - if not X in Y and Z == "zero": 8 + if X not in Y and Z == "zero": -9 | pass | E713 [*] Test for membership should be `not in` @@ -66,10 +60,8 @@ E713 [*] Test for membership should be `not in` | help: Convert to `not in` | -10 | #: E713 - - if X == "zero" or not Y in Z: +11 - if X == "zero" or not Y in Z: 11 + if X == "zero" or Y not in Z: -12 | pass | E713 [*] Test for membership should be `not in` @@ -83,10 +75,8 @@ E713 [*] Test for membership should be `not in` | help: Convert to `not in` | -13 | #: E713 - - if not (X in Y): +14 - if not (X in Y): 14 + if X not in Y: -15 | pass | E713 [*] Test for membership should be `not in` @@ -98,7 +88,6 @@ E713 [*] Test for membership should be `not in` | ^^^^^^^^^^^^^^^^^ help: Convert to `not in` | -39 | assert not (re.search(r"^.:\\Users\\[^\\]*\\Downloads\\.*") is None) - - assert not('name' in request)or not request['name'] +40 - assert not('name' in request)or not request['name'] 40 + assert 'name' not in request or not request['name'] | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E714_E714.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E714_E714.py.snap index 3c59266b4cfc9..5d7b44e4a334a 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E714_E714.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E714_E714.py.snap @@ -12,10 +12,8 @@ E714 [*] Test for object identity should be `is not` | help: Convert to `is not` | -1 | #: E714 - - if not X is Y: +2 - if not X is Y: 2 + if X is not Y: -3 | pass | E714 [*] Test for object identity should be `is not` @@ -29,10 +27,8 @@ E714 [*] Test for object identity should be `is not` | help: Convert to `is not` | -4 | #: E714 - - if not X.B is Y: +5 - if not X.B is Y: 5 + if X.B is not Y: -6 | pass | E714 [*] Test for object identity should be `is not` @@ -44,7 +40,6 @@ E714 [*] Test for object identity should be `is not` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Convert to `is not` | -38 | assert [42, not foo] in bar - - assert not (re.search(r"^.:\\Users\\[^\\]*\\Downloads\\.*") is None) +39 - assert not (re.search(r"^.:\\Users\\[^\\]*\\Downloads\\.*") is None) 39 + assert re.search(r"^.:\\Users\\[^\\]*\\Downloads\\.*") is not None | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E731_E731.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E731_E731.py.snap index 90286da679ec8..9af71059ce1ac 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E731_E731.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E731_E731.py.snap @@ -10,11 +10,8 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | ^^^^^^^^^^^^^^^^^^^ help: Rewrite `f` as a `def` | -2 | # E731 - - f = lambda x: 2 * x -3 + def f(x): +3 ~ def f(x): 4 + return 2 * x -5 | | note: This is an unsafe fix and may change runtime behavior @@ -26,13 +23,10 @@ E731 [*] Do not assign a `lambda` expression, use a `def` 8 | f = lambda x: 2 * x | ^^^^^^^^^^^^^^^^^^^ help: Rewrite `f` as a `def` - | -7 | # E731 - - f = lambda x: 2 * x -8 + def f(x): -9 + return 2 * x -10 | - | + | +8 ~ def f(x): +9 + return 2 * x + | note: This is an unsafe fix and may change runtime behavior E731 [*] Do not assign a `lambda` expression, use a `def` @@ -44,11 +38,8 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: Rewrite `this` as a `def` | -13 | while False: - - this = lambda y, z: 2 * x -14 + def this(y, z): +14 ~ def this(y, z): 15 + return 2 * x -16 | | note: This is an unsafe fix and may change runtime behavior @@ -61,11 +52,8 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | ^^^^^^^^^^^^^^^^^^^^^ help: Rewrite `f` as a `def` | -18 | # E731 - - f = lambda: (yield 1) -19 + def f(): +19 ~ def f(): 20 + return (yield 1) -21 | | note: This is an unsafe fix and may change runtime behavior @@ -78,11 +66,8 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Rewrite `f` as a `def` | -23 | # E731 - - f = lambda: (yield from g()) -24 + def f(): +24 ~ def f(): 25 + return (yield from g()) -26 | | note: This is an unsafe fix and may change runtime behavior @@ -95,11 +80,8 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | ^^^^^^^^^^^^^^^^^^^ help: Rewrite `f` as a `def` | -56 | # E731 - - f = lambda x: 2 * x -57 + def f(x): +57 ~ def f(x): 58 + return 2 * x -59 | | note: This is an unsafe fix and may change runtime behavior @@ -115,11 +97,8 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | help: Rewrite `x` as a `def` | -72 | if True: - - x = lambda: 1 -73 + def x(): +73 ~ def x(): 74 + return 1 -75 | else: | note: This is a display-only fix and is likely to be incorrect @@ -134,11 +113,8 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | help: Rewrite `x` as a `def` | -74 | else: - - x = lambda: 2 -75 + def x(): +75 ~ def x(): 76 + return 2 -77 | return x | note: This is a display-only fix and is likely to be incorrect @@ -151,11 +127,8 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Rewrite `f` as a `def` | -85 | P = ParamSpec("P") - - f: Callable[P, int] = lambda *args: len(args) -86 + def f(*args) -> int: +86 ~ def f(*args) -> int: 87 + return len(args) -88 | | note: This is an unsafe fix and may change runtime behavior @@ -168,11 +141,8 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Rewrite `f` as a `def` | -93 | - - f: Callable[[], None] = lambda: None -94 + def f() -> None: +94 ~ def f() -> None: 95 + return None -96 | | note: This is an unsafe fix and may change runtime behavior @@ -185,11 +155,8 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Rewrite `f` as a `def` | -101 | - - f: Callable[..., None] = lambda a, b: None -102 + def f(a, b) -> None: +102 ~ def f(a, b) -> None: 103 + return None -104 | | note: This is an unsafe fix and may change runtime behavior @@ -202,11 +169,8 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Rewrite `f` as a `def` | -109 | - - f: Callable[[int], int] = lambda x: 2 * x -110 + def f(x: int) -> int: +110 ~ def f(x: int) -> int: 111 + return 2 * x -112 | | note: This is an unsafe fix and may change runtime behavior @@ -219,11 +183,8 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Rewrite `f` as a `def` | -118 | - - f: Callable[[str, int], str] = lambda a, b: a * b -119 + def f(a: str, b: int) -> str: +119 ~ def f(a: str, b: int) -> str: 120 + return a * b -121 | | note: This is an unsafe fix and may change runtime behavior @@ -236,11 +197,8 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Rewrite `f` as a `def` | -126 | - - f: Callable[[str, int], tuple[str, int]] = lambda a, b: (a, b) -127 + def f(a: str, b: int) -> tuple[str, int]: +127 ~ def f(a: str, b: int) -> tuple[str, int]: 128 + return (a, b) -129 | | note: This is an unsafe fix and may change runtime behavior @@ -253,11 +211,8 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Rewrite `f` as a `def` | -134 | - - f: Callable[[str, int, list[str]], list[str]] = lambda a, b, /, c: [*c, a * b] -135 + def f(a: str, b: int, /, c: list[str]) -> list[str]: +135 ~ def f(a: str, b: int, /, c: list[str]) -> list[str]: 136 + return [*c, a * b] -137 | | note: This is an unsafe fix and may change runtime behavior @@ -271,11 +226,8 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | help: Rewrite `CELSIUS` as a `def` | -138 | class TemperatureScales(Enum): - - CELSIUS = (lambda deg_c: deg_c) -139 + def CELSIUS(deg_c): +139 ~ def CELSIUS(deg_c): 140 + return (deg_c) -141 | FAHRENHEIT = (lambda deg_c: deg_c * 9 / 5 + 32) | note: This is an unsafe fix and may change runtime behavior @@ -288,11 +240,8 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Rewrite `FAHRENHEIT` as a `def` | -139 | CELSIUS = (lambda deg_c: deg_c) - - FAHRENHEIT = (lambda deg_c: deg_c * 9 / 5 + 32) -140 + def FAHRENHEIT(deg_c): +140 ~ def FAHRENHEIT(deg_c): 141 + return (deg_c * 9 / 5 + 32) -142 | | note: This is an unsafe fix and may change runtime behavior @@ -307,15 +256,10 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | |_____^ help: Rewrite `f` as a `def` | -146 | - - f = lambda: ( - - i := 1, - - ) -147 + def f(): +147 ~ def f(): 148 + return ( 149 + i := 1, 150 + ) -151 | | note: This is an unsafe fix and may change runtime behavior @@ -334,11 +278,11 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | help: Rewrite `x` as a `def` | -162 | # * https://github.com/astral-sh/ruff/issues/7720 - - x = lambda: """ 163 + def x(): 164 + return """ -165 | a +165 + a +166 + b +167 + """ | note: This is an unsafe fix and may change runtime behavior @@ -353,11 +297,8 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | help: Rewrite `at_least_one_million` as a `def` | -168 | # * https://github.com/astral-sh/ruff/issues/10277 - - at_least_one_million = lambda _: _ >= 1_000_000 169 + def at_least_one_million(_): 170 + return _ >= 1_000_000 -171 | | note: This is an unsafe fix and may change runtime behavior @@ -376,11 +317,11 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | help: Rewrite `x` as a `def` | -170 | - - x = lambda: ( 171 + def x(): 172 + return ( -173 | # comment +173 + # comment +174 + 5 + 10 +175 + ) | note: This is an unsafe fix and may change runtime behavior @@ -399,11 +340,11 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | help: Rewrite `x` as a `def` | -175 | - - x = lambda: ( 176 + def x(): 177 + return ( -178 | # comment +178 + # comment +179 + y := 10 +180 + ) | note: This is an unsafe fix and may change runtime behavior @@ -422,16 +363,10 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | help: Rewrite `foo_tooltip` as a `def` | -181 | # https://github.com/astral-sh/ruff/issues/18475 - - foo_tooltip = ( - - lambda x, data: f"\nfoo: {data['foo'][int(x)]}" 182 + def foo_tooltip(x, data): 183 + return (f"\nfoo: {data['foo'][int(x)]}" -184 | if data["foo"] is not None - - else "" - - ) +184 + if data["foo"] is not None 185 + else "") -186 | | note: This is an unsafe fix and may change runtime behavior @@ -451,16 +386,9 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | help: Rewrite `foo_tooltip` as a `def` | -187 | - - foo_tooltip = ( - - lambda x, data: f"\nfoo: {data['foo'][int(x)]}" + - - more - - - - ) 188 + def foo_tooltip(x, data): 189 + return (f"\nfoo: {data['foo'][int(x)]}" + 190 + more) -191 | | note: This is an unsafe fix and may change runtime behavior @@ -474,11 +402,8 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | help: Rewrite `f1` as a `def` | -199 | P = ParamSpec("P") - - f1: Callable[P, str] = lambda x: str(x) -200 + def f1(x) -> str: +200 ~ def f1(x) -> str: 201 + return str(x) -202 | f2: Callable[..., str] = lambda x: str(x) | note: This is an unsafe fix and may change runtime behavior @@ -491,9 +416,7 @@ E731 [*] Do not assign a `lambda` expression, use a `def` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Rewrite `f2` as a `def` | -200 | f1: Callable[P, str] = lambda x: str(x) - - f2: Callable[..., str] = lambda x: str(x) -201 + def f2(x) -> str: +201 ~ def f2(x) -> str: 202 + return str(x) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W291_W29.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W291_W29.py.snap index c66f72f2010d2..56f65ea53bfdc 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W291_W29.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W291_W29.py.snap @@ -13,10 +13,7 @@ W291 [*] Trailing whitespace | help: Remove trailing whitespace | -3 | #: W291:1:6 - - print -4 + print -5 | #: W293:2:1 +4 | print | W291 [*] Trailing whitespace @@ -31,10 +28,7 @@ W291 [*] Trailing whitespace | help: Remove trailing whitespace | -10 | '''multiline - - string with trailing whitespace''' -11 + string with trailing whitespace''' -12 | #: W291 W292 noeol +11 | string with trailing whitespace''' | W291 [*] Trailing whitespace @@ -49,8 +43,5 @@ W291 [*] Trailing whitespace | help: Remove trailing whitespace | -12 | #: W291 W292 noeol - - x = 1 -13 + x = 1 -14 | #: W191 W292 noeol +13 | x = 1 | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W291_W291.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W291_W291.py.snap index 68974b23b3d4c..cbd6648075f04 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W291_W291.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W291_W291.py.snap @@ -10,9 +10,7 @@ W291 [*] Trailing whitespace | help: Remove trailing whitespace | - - '''trailing whitespace -1 + '''trailing whitespace -2 | inside a multiline string''' +1 | '''trailing whitespace | note: This is an unsafe fix and may change runtime behavior @@ -27,10 +25,7 @@ W291 [*] Trailing whitespace | help: Remove trailing whitespace | -3 | - - f'''trailing whitespace -4 + f'''trailing whitespace -5 | inside a multiline f-string''' +4 | f'''trailing whitespace | note: This is an unsafe fix and may change runtime behavior @@ -45,10 +40,7 @@ W291 [*] Trailing whitespace | help: Remove trailing whitespace | -7 | # Trailing whitespace after `{` - - f'abc { -8 + f'abc { -9 | 1 + 2 +8 | f'abc { | W291 [*] Trailing whitespace @@ -62,8 +54,5 @@ W291 [*] Trailing whitespace | help: Remove trailing whitespace | -13 | f'abc { - - 1 + 2 -14 + 1 + 2 -15 | }' +14 | 1 + 2 | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W292_W292_0.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W292_W292_0.py.snap index 439b3a25914eb..73191590341ac 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W292_W292_0.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W292_W292_0.py.snap @@ -9,7 +9,5 @@ W292 [*] No newline at end of file | ^ help: Add trailing newline | -1 | def fn() -> None: - - pass -2 + pass - | +2 | pass + | + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W293_W29.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W293_W29.py.snap index a22ce507693ba..58888f2b0aa22 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W293_W29.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W293_W29.py.snap @@ -12,9 +12,5 @@ W293 [*] Blank line contains whitespace 9 | #: W291:2:35 | help: Remove whitespace from blank line - | -6 | class Foo(object): - - -7 + -8 | bang = 12 +7 - | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W293_W293.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W293_W293.py.snap index b06d8bac204eb..497ef866a873b 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W293_W293.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W293_W293.py.snap @@ -11,11 +11,7 @@ W293 [*] Blank line contains whitespace 5 | """\ | help: Remove whitespace from blank line - | -3 | """底盘信息推送控制 - - -4 + -5 | """\ +4 - | note: This is an unsafe fix and may change runtime behavior @@ -27,14 +23,12 @@ W293 [*] Blank line contains whitespace 10 | | ^^^^ help: Remove whitespace from blank line - | -7 | - - """""" \ - - \ - - -8 + """""" -9 | - | + | + 8 - """""" \ + 9 - \ +10 - + 8 + """""" + | W293 [*] Blank line contains whitespace --> W293.py:16:1 @@ -47,12 +41,10 @@ W293 [*] Blank line contains whitespace | help: Remove whitespace from blank line | -13 | "abc\ - - " \ - - \ - - +14 - " \ +15 - \ +16 - 14 + " -15 | '''blank line with whitespace | W293 [*] Blank line contains whitespace @@ -64,10 +56,6 @@ W293 [*] Blank line contains whitespace 19 | inside a multiline string''' | help: Remove whitespace from blank line - | -17 | '''blank line with whitespace - - -18 + -19 | inside a multiline string''' +18 - | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W605_W605_0.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W605_W605_0.py.snap index b4f217c17f612..8794a01ee4212 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W605_W605_0.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W605_W605_0.py.snap @@ -12,11 +12,8 @@ W605 [*] Invalid escape sequence: `\.` | help: Use a raw string literal | -1 | #: W605:1:10 - - regex = '\.png$' -2 + regex = r'\.png$' -3 | - | +2 | regex = r'\.png$' + | + W605 [*] Invalid escape sequence: `\.` --> W605_0.py:6:1 @@ -29,11 +26,8 @@ W605 [*] Invalid escape sequence: `\.` | help: Use a raw string literal | -4 | #: W605:2:1 - - regex = ''' -5 + regex = r''' -6 | \.png$ - | +5 | regex = r''' + | + W605 [*] Invalid escape sequence: `\_` --> W605_0.py:11:6 @@ -46,11 +40,8 @@ W605 [*] Invalid escape sequence: `\_` | help: Use a raw string literal | -10 | f( - - '\_' -11 + r'\_' -12 | ) - | +11 | r'\_' + | + W605 [*] Invalid escape sequence: `\_` --> W605_0.py:18:6 @@ -64,11 +55,8 @@ W605 [*] Invalid escape sequence: `\_` | help: Use a raw string literal | -14 | #: W605:4:6 - - """ -15 + r""" -16 | multi-line - | +15 | r""" + | + W605 [*] Invalid escape sequence: `\_` --> W605_0.py:23:39 @@ -78,11 +66,8 @@ W605 [*] Invalid escape sequence: `\_` | ^^ help: Add backslash to escape sequence | -22 | #: W605:1:38 - - value = 'new line\nand invalid escape \_ here' -23 + value = 'new line\nand invalid escape \\_ here' -24 | - | +23 | value = 'new line\nand invalid escape \\_ here' + | + W605 [*] Invalid escape sequence: `\.` --> W605_0.py:28:12 @@ -96,11 +81,8 @@ W605 [*] Invalid escape sequence: `\.` | help: Use a raw string literal | -27 | #: W605:1:11 - - return'\.png$' -28 + return r'\.png$' -29 | - | +28 | return r'\.png$' + | + W605 [*] Invalid escape sequence: `\_` --> W605_0.py:45:12 @@ -114,11 +96,8 @@ W605 [*] Invalid escape sequence: `\_` | help: Add backslash to escape sequence | -44 | - - regex = '\\\_' -45 + regex = '\\\\_' -46 | - | +45 | regex = '\\\\_' + | + W605 [*] Invalid escape sequence: `\ ` --> W605_0.py:48:6 @@ -131,10 +110,8 @@ W605 [*] Invalid escape sequence: `\ ` | help: Use a raw string literal | -47 | #: W605:1:7 - - u'foo\ bar' +48 - u'foo\ bar' 48 + r'foo\ bar' -49 | | W605 [*] Invalid escape sequence: `\.` @@ -148,11 +125,8 @@ W605 [*] Invalid escape sequence: `\.` | help: Add backslash to escape sequence | -52 | "foo \ - - bar \. baz" -53 + bar \\. baz" -54 | ) - | +53 | bar \\. baz" + | + W605 [*] Invalid escape sequence: `\.` --> W605_0.py:57:6 @@ -165,11 +139,8 @@ W605 [*] Invalid escape sequence: `\.` | help: Add backslash to escape sequence | -56 | #: W605:1:6 - - "foo \. bar \t" -57 + "foo \\. bar \t" -58 | - | +57 | "foo \\. bar \t" + | + W605 [*] Invalid escape sequence: `\.` --> W605_0.py:60:13 @@ -179,7 +150,5 @@ W605 [*] Invalid escape sequence: `\.` | ^^ help: Add backslash to escape sequence | -59 | #: W605:1:13 - - "foo \t bar \." -60 + "foo \t bar \\." - | +60 | "foo \t bar \\." + | + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W605_W605_1.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W605_W605_1.py.snap index 3d261c66d5584..a939c768142c6 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W605_W605_1.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__W605_W605_1.py.snap @@ -12,11 +12,8 @@ W605 [*] Invalid escape sequence: `\.` | help: Use a raw string literal | -3 | #: W605:1:10 - - regex = f'\.png$' -4 + regex = rf'\.png$' -5 | - | +4 | regex = rf'\.png$' + | + W605 [*] Invalid escape sequence: `\.` --> W605_1.py:8:1 @@ -29,11 +26,8 @@ W605 [*] Invalid escape sequence: `\.` | help: Use a raw string literal | -6 | #: W605:2:1 - - regex = f''' -7 + regex = rf''' -8 | \.png$ - | +7 | regex = rf''' + | + W605 [*] Invalid escape sequence: `\_` --> W605_1.py:13:7 @@ -46,11 +40,8 @@ W605 [*] Invalid escape sequence: `\_` | help: Use a raw string literal | -12 | f( - - f'\_' -13 + rf'\_' -14 | ) - | +13 | rf'\_' + | + W605 [*] Invalid escape sequence: `\_` --> W605_1.py:20:6 @@ -64,11 +55,8 @@ W605 [*] Invalid escape sequence: `\_` | help: Use a raw string literal | -16 | #: W605:4:6 - - f""" -17 + rf""" -18 | multi-line - | +17 | rf""" + | + W605 [*] Invalid escape sequence: `\_` --> W605_1.py:25:40 @@ -78,11 +66,8 @@ W605 [*] Invalid escape sequence: `\_` | ^^ help: Add backslash to escape sequence | -24 | #: W605:1:38 - - value = f'new line\nand invalid escape \_ here' -25 + value = f'new line\nand invalid escape \\_ here' -26 | - | +25 | value = f'new line\nand invalid escape \\_ here' + | + W605 [*] Invalid escape sequence: `\_` --> W605_1.py:43:13 @@ -96,11 +81,8 @@ W605 [*] Invalid escape sequence: `\_` | help: Add backslash to escape sequence | -42 | - - regex = f'\\\_' -43 + regex = f'\\\\_' -44 | value = f'\{{1}}' - | +43 | regex = f'\\\\_' + | + W605 [*] Invalid escape sequence: `\{` --> W605_1.py:44:11 @@ -113,11 +95,8 @@ W605 [*] Invalid escape sequence: `\{` | help: Use a raw string literal | -43 | regex = f'\\\_' - - value = f'\{{1}}' -44 + value = rf'\{{1}}' -45 | value = f'\{1}' - | +44 | value = rf'\{{1}}' + | + W605 [*] Invalid escape sequence: `\{` --> W605_1.py:45:11 @@ -131,11 +110,8 @@ W605 [*] Invalid escape sequence: `\{` | help: Use a raw string literal | -44 | value = f'\{{1}}' - - value = f'\{1}' -45 + value = rf'\{1}' -46 | value = f'{1:\}' - | +45 | value = rf'\{1}' + | + W605 [*] Invalid escape sequence: `\}` --> W605_1.py:46:14 @@ -149,11 +125,8 @@ W605 [*] Invalid escape sequence: `\}` | help: Use a raw string literal | -45 | value = f'\{1}' - - value = f'{1:\}' -46 + value = rf'{1:\}' -47 | value = f"{f"\{1}"}" - | +46 | value = rf'{1:\}' + | + W605 [*] Invalid escape sequence: `\{` --> W605_1.py:47:14 @@ -166,11 +139,8 @@ W605 [*] Invalid escape sequence: `\{` | help: Use a raw string literal | -46 | value = f'{1:\}' - - value = f"{f"\{1}"}" -47 + value = f"{rf"\{1}"}" -48 | value = rf"{f"\{1}"}" - | +47 | value = f"{rf"\{1}"}" + | + W605 [*] Invalid escape sequence: `\{` --> W605_1.py:48:15 @@ -184,11 +154,8 @@ W605 [*] Invalid escape sequence: `\{` | help: Use a raw string literal | -47 | value = f"{f"\{1}"}" - - value = rf"{f"\{1}"}" -48 + value = rf"{rf"\{1}"}" -49 | - | +48 | value = rf"{rf"\{1}"}" + | + W605 [*] Invalid escape sequence: `\d` --> W605_1.py:57:9 @@ -201,11 +168,8 @@ W605 [*] Invalid escape sequence: `\d` | help: Use a raw string literal | -56 | # Regression tests for https://github.com/astral-sh/ruff/issues/10434 - - f"{{}}+-\d" -57 + rf"{{}}+-\d" -58 | f"\n{{}}+-\d+" - | +57 | rf"{{}}+-\d" + | + W605 [*] Invalid escape sequence: `\d` --> W605_1.py:58:11 @@ -218,11 +182,8 @@ W605 [*] Invalid escape sequence: `\d` | help: Add backslash to escape sequence | -57 | f"{{}}+-\d" - - f"\n{{}}+-\d+" -58 + f"\n{{}}+-\\d+" -59 | f"\n{{}}�+-\d+" - | +58 | f"\n{{}}+-\\d+" + | + W605 [*] Invalid escape sequence: `\d` --> W605_1.py:59:12 @@ -236,11 +197,8 @@ W605 [*] Invalid escape sequence: `\d` | help: Add backslash to escape sequence | -58 | f"\n{{}}+-\d+" - - f"\n{{}}�+-\d+" -59 + f"\n{{}}�+-\\d+" -60 | - | +59 | f"\n{{}}�+-\\d+" + | + W605 [*] Invalid escape sequence: `\I` --> W605_1.py:65:31 @@ -254,11 +212,8 @@ W605 [*] Invalid escape sequence: `\I` | help: Add backslash to escape sequence | -64 | incomplete = 3 - - s = f"TOTAL: {total}\nOK: {ok}\INCOMPLETE: {incomplete}\n" -65 + s = f"TOTAL: {total}\nOK: {ok}\\INCOMPLETE: {incomplete}\n" -66 | - | +65 | s = f"TOTAL: {total}\nOK: {ok}\\INCOMPLETE: {incomplete}\n" + | + W605 [*] Invalid escape sequence: `\I` --> W605_1.py:68:9 @@ -268,11 +223,8 @@ W605 [*] Invalid escape sequence: `\I` | ^^ help: Use a raw string literal | -67 | # Debug text (should trigger) - - t = f"{'\InHere'=}" -68 + t = f"{r'\InHere'=}" -69 | - | +68 | t = f"{r'\InHere'=}" + | + W605 [*] Invalid escape sequence: `\.` --> W605_1.py:73:11 @@ -285,11 +237,8 @@ W605 [*] Invalid escape sequence: `\.` | help: Use a raw string literal | -72 | #: W605:1:10 - - regex = t'\.png$' -73 + regex = rt'\.png$' -74 | - | +73 | regex = rt'\.png$' + | + W605 [*] Invalid escape sequence: `\.` --> W605_1.py:77:1 @@ -302,11 +251,8 @@ W605 [*] Invalid escape sequence: `\.` | help: Use a raw string literal | -75 | #: W605:2:1 - - regex = t''' -76 + regex = rt''' -77 | \.png$ - | +76 | regex = rt''' + | + W605 [*] Invalid escape sequence: `\_` --> W605_1.py:82:7 @@ -319,11 +265,8 @@ W605 [*] Invalid escape sequence: `\_` | help: Use a raw string literal | -81 | f( - - t'\_' -82 + rt'\_' -83 | ) - | +82 | rt'\_' + | + W605 [*] Invalid escape sequence: `\_` --> W605_1.py:89:6 @@ -337,11 +280,8 @@ W605 [*] Invalid escape sequence: `\_` | help: Use a raw string literal | -85 | #: W605:4:6 - - t""" -86 + rt""" -87 | multi-line - | +86 | rt""" + | + W605 [*] Invalid escape sequence: `\_` --> W605_1.py:94:40 @@ -351,11 +291,8 @@ W605 [*] Invalid escape sequence: `\_` | ^^ help: Add backslash to escape sequence | -93 | #: W605:1:38 - - value = t'new line\nand invalid escape \_ here' -94 + value = t'new line\nand invalid escape \\_ here' -95 | - | +94 | value = t'new line\nand invalid escape \\_ here' + | + W605 [*] Invalid escape sequence: `\_` --> W605_1.py:112:13 @@ -369,11 +306,8 @@ W605 [*] Invalid escape sequence: `\_` | help: Add backslash to escape sequence | -111 | - - regex = t'\\\_' -112 + regex = t'\\\\_' -113 | value = t'\{{1}}' - | +112 | regex = t'\\\\_' + | + W605 [*] Invalid escape sequence: `\{` --> W605_1.py:113:11 @@ -386,11 +320,8 @@ W605 [*] Invalid escape sequence: `\{` | help: Use a raw string literal | -112 | regex = t'\\\_' - - value = t'\{{1}}' -113 + value = rt'\{{1}}' -114 | value = t'\{1}' - | +113 | value = rt'\{{1}}' + | + W605 [*] Invalid escape sequence: `\{` --> W605_1.py:114:11 @@ -404,11 +335,8 @@ W605 [*] Invalid escape sequence: `\{` | help: Use a raw string literal | -113 | value = t'\{{1}}' - - value = t'\{1}' -114 + value = rt'\{1}' -115 | value = t'{1:\}' - | +114 | value = rt'\{1}' + | + W605 [*] Invalid escape sequence: `\}` --> W605_1.py:115:14 @@ -422,11 +350,8 @@ W605 [*] Invalid escape sequence: `\}` | help: Use a raw string literal | -114 | value = t'\{1}' - - value = t'{1:\}' -115 + value = rt'{1:\}' -116 | value = t"{t"\{1}"}" - | +115 | value = rt'{1:\}' + | + W605 [*] Invalid escape sequence: `\{` --> W605_1.py:116:14 @@ -439,11 +364,8 @@ W605 [*] Invalid escape sequence: `\{` | help: Use a raw string literal | -115 | value = t'{1:\}' - - value = t"{t"\{1}"}" -116 + value = t"{rt"\{1}"}" -117 | value = rt"{t"\{1}"}" - | +116 | value = t"{rt"\{1}"}" + | + W605 [*] Invalid escape sequence: `\{` --> W605_1.py:117:15 @@ -457,11 +379,8 @@ W605 [*] Invalid escape sequence: `\{` | help: Use a raw string literal | -116 | value = t"{t"\{1}"}" - - value = rt"{t"\{1}"}" -117 + value = rt"{rt"\{1}"}" -118 | - | +117 | value = rt"{rt"\{1}"}" + | + W605 [*] Invalid escape sequence: `\d` --> W605_1.py:126:9 @@ -474,11 +393,8 @@ W605 [*] Invalid escape sequence: `\d` | help: Use a raw string literal | -125 | # Regression tests for https://github.com/astral-sh/ruff/issues/10434 - - t"{{}}+-\d" -126 + rt"{{}}+-\d" -127 | t"\n{{}}+-\d+" - | +126 | rt"{{}}+-\d" + | + W605 [*] Invalid escape sequence: `\d` --> W605_1.py:127:11 @@ -491,11 +407,8 @@ W605 [*] Invalid escape sequence: `\d` | help: Add backslash to escape sequence | -126 | t"{{}}+-\d" - - t"\n{{}}+-\d+" -127 + t"\n{{}}+-\\d+" -128 | t"\n{{}}�+-\d+" - | +127 | t"\n{{}}+-\\d+" + | + W605 [*] Invalid escape sequence: `\d` --> W605_1.py:128:12 @@ -509,11 +422,8 @@ W605 [*] Invalid escape sequence: `\d` | help: Add backslash to escape sequence | -127 | t"\n{{}}+-\d+" - - t"\n{{}}�+-\d+" -128 + t"\n{{}}�+-\\d+" -129 | - | +128 | t"\n{{}}�+-\\d+" + | + W605 [*] Invalid escape sequence: `\I` --> W605_1.py:134:31 @@ -527,11 +437,8 @@ W605 [*] Invalid escape sequence: `\I` | help: Add backslash to escape sequence | -133 | incomplete = 3 - - s = t"TOTAL: {total}\nOK: {ok}\INCOMPLETE: {incomplete}\n" -134 + s = t"TOTAL: {total}\nOK: {ok}\\INCOMPLETE: {incomplete}\n" -135 | - | +134 | s = t"TOTAL: {total}\nOK: {ok}\\INCOMPLETE: {incomplete}\n" + | + W605 [*] Invalid escape sequence: `\I` --> W605_1.py:137:9 @@ -541,7 +448,5 @@ W605 [*] Invalid escape sequence: `\I` | ^^ help: Use a raw string literal | -136 | # Debug text (should trigger) - - t = t"{'\InHere'=}" -137 + t = t"{r'\InHere'=}" - | +137 | t = t"{r'\InHere'=}" + | + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E301_notebook.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E301_notebook.snap index a2caa33015c9a..c8742e305ab7e 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E301_notebook.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E301_notebook.snap @@ -12,8 +12,5 @@ E301 [*] Expected 1 blank line, found 0 15 | pass | help: Add missing blank line - | -12 | pass -13 + -14 | @classmethod +13 - @classmethod | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E303_notebook.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E303_notebook.snap index 557c3862dde66..122e6720daae4 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E303_notebook.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E303_notebook.snap @@ -10,10 +10,8 @@ E303 [*] Too many blank lines (2) 31 | def inner(): # E306 not expected (pycodestyle detects E306) | help: Remove extraneous blank line(s) - | -27 | - - -28 | # arbitrary comment +27 - +28 - | E303 [*] Too many blank lines (4) @@ -25,9 +23,8 @@ E303 [*] Too many blank lines (4) 41 | # end | help: Remove extraneous blank line(s) - | -36 | - - - - -37 | def fn(): +35 - +36 - +37 - +38 - | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E303_typing_stub.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E303_typing_stub.snap index 5d127a7e6c951..350313ecf3f80 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E303_typing_stub.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E303_typing_stub.snap @@ -10,10 +10,8 @@ E303 [*] Too many blank lines (2) 19 | def grouped3( ): ... | help: Remove extraneous blank line(s) - | -15 | - - -16 | def grouped1(): ... +15 - +16 - | E303 [*] Too many blank lines (2) @@ -25,10 +23,8 @@ E303 [*] Too many blank lines (2) 24 | backend_object: str | None | help: Remove extraneous blank line(s) - | -20 | - - -21 | class BackendProxy: +20 - +21 - | E303 [*] Too many blank lines (2) @@ -40,9 +36,7 @@ E303 [*] Too many blank lines (2) | help: Remove extraneous blank line(s) | -33 | - - -34 | def ungrouped(): ... +33 + | E303 [*] Too many blank lines (2) @@ -54,8 +48,6 @@ E303 [*] Too many blank lines (2) 45 | pass | help: Remove extraneous blank line(s) - | -41 | - - -42 | def outer(): +41 - +42 - | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E304_notebook.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E304_notebook.snap index 970a6c54652f2..2403a0d4bb700 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E304_notebook.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E304_notebook.snap @@ -12,8 +12,5 @@ E304 [*] Blank lines found after function decorator (1) 47 | # end | help: Remove extraneous blank line(s) - | -43 | @decorator - - -44 | def function(): +44 - | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E304_typing_stub.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E304_typing_stub.snap index 57299e6af3b1f..d0159af824db2 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E304_typing_stub.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E304_typing_stub.snap @@ -9,8 +9,5 @@ E304 [*] Blank lines found after function decorator (1) 32 | def with_blank_line(): ... | ^^^ help: Remove extraneous blank line(s) - | -30 | @decorated - - -31 | def with_blank_line(): ... +31 - | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E305_notebook.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E305_notebook.snap index 4ab71bc6bb741..a4c3f1baca941 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E305_notebook.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E305_notebook.snap @@ -11,8 +11,5 @@ E305 [*] Expected 2 blank lines after class or function definition, found (1) 57 | # E306:3:5 | help: Add missing blank line(s) - | -54 | # another comment -55 + -56 | fn() +55 - fn() | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E306_notebook.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E306_notebook.snap index 2e42a73f5bde1..794842d91f131 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E306_notebook.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_E306_notebook.snap @@ -12,8 +12,5 @@ E306 [*] Expected 1 blank line before a nested definition, found 0 62 | # end | help: Add missing blank line - | -59 | x = 1 -60 + -61 | def b(): +60 - def b(): | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_typing_stub_isort.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_typing_stub_isort.snap index b440fb7b7fb59..d89c2e3177174 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_typing_stub_isort.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__blank_lines_typing_stub_isort.snap @@ -12,13 +12,8 @@ I001 [*] Import block is un-sorted or un-formatted | |________________________________^ help: Organize imports | -1 | import json - - - - - - -2 | from typing import Any, Sequence - - -3 | +1 + import json +2 + from typing import Any, Sequence | E303 [*] Too many blank lines (3) @@ -27,11 +22,9 @@ E303 [*] Too many blank lines (3) 5 | from typing import Any, Sequence | ^^^^ help: Remove extraneous blank line(s) - | -2 | - - - - -3 | from typing import Any, Sequence +2 - +3 - +4 - | E303 [*] Too many blank lines (2) @@ -40,10 +33,8 @@ E303 [*] Too many blank lines (2) 8 | class MissingCommand(TypeError): ... # noqa: N818 | ^^^^^ help: Remove extraneous blank line(s) - | -6 | - - -7 | class MissingCommand(TypeError): ... # noqa: N818 +6 - +7 - | E303 [*] Too many blank lines (2) @@ -55,11 +46,9 @@ E303 [*] Too many blank lines (2) 13 | backend_object: str | None | help: Remove extraneous blank line(s) - | -9 | - - -10 | class BackendProxy: - | +9 - +10- + | E303 [*] Too many blank lines (2) --> E30_isort.pyi:17:1 @@ -69,10 +58,8 @@ E303 [*] Too many blank lines (2) 18 | import abcd | help: Remove extraneous blank line(s) - | -15 | - - -16 | if __name__ == "__main__": +15 - +16 - | E303 [*] Too many blank lines (2) @@ -84,10 +71,8 @@ E303 [*] Too many blank lines (2) 23 | def __init__(self, backend_module: str, backend_obj: str | None) -> None: ... | help: Remove extraneous blank line(s) - | -19 | - - -20 | abcd.foo() +19 - +20 - | I001 [*] Import block is un-sorted or un-formatted @@ -102,10 +87,9 @@ I001 [*] Import block is un-sorted or un-formatted | |___________________________________________^ help: Organize imports | -27 | - - - - -28 | from typing_extensions import TypeAlias +26 + import os +27 + +28 + from typing_extensions import TypeAlias | E303 [*] Too many blank lines (3) @@ -114,11 +98,9 @@ E303 [*] Too many blank lines (3) 30 | from typing_extensions import TypeAlias | ^^^^ help: Remove extraneous blank line(s) - | -27 | - - - - -28 | from typing_extensions import TypeAlias +27 - +28 - +29 - | E303 [*] Too many blank lines (2) @@ -130,10 +112,8 @@ E303 [*] Too many blank lines (2) 35 | def __call__(self, name: str, *args: Any, **kwargs: Any) -> Any: | help: Remove extraneous blank line(s) - | -31 | - - -32 | abcd.foo() +31 - +32 - | E303 [*] Too many blank lines (2) @@ -142,10 +122,8 @@ E303 [*] Too many blank lines (2) 45 | def _exit(self) -> None: ... | ^^^ help: Remove extraneous blank line(s) - | -43 | - - -44 | def _exit(self) -> None: ... +43 - +44 - | E303 [*] Too many blank lines (2) @@ -154,10 +132,8 @@ E303 [*] Too many blank lines (2) 48 | def _optional_commands(self) -> dict[str, bool]: ... | ^^^ help: Remove extraneous blank line(s) - | -46 | - - -47 | def _optional_commands(self) -> dict[str, bool]: ... +46 - +47 - | E303 [*] Too many blank lines (2) @@ -166,10 +142,8 @@ E303 [*] Too many blank lines (2) 51 | def run(argv: Sequence[str]) -> int: ... | ^^^ help: Remove extraneous blank line(s) - | -49 | - - -50 | def run(argv: Sequence[str]) -> int: ... +49 - +50 - | E303 [*] Too many blank lines (2) @@ -178,10 +152,8 @@ E303 [*] Too many blank lines (2) 54 | def read_line(fd: int = 0) -> bytearray: ... | ^^^ help: Remove extraneous blank line(s) - | -52 | - - -53 | def read_line(fd: int = 0) -> bytearray: ... +52 - +53 - | E303 [*] Too many blank lines (2) @@ -190,10 +162,8 @@ E303 [*] Too many blank lines (2) 57 | def flush() -> None: ... | ^^^ help: Remove extraneous blank line(s) - | -55 | - - -56 | def flush() -> None: ... +55 - +56 - | E303 [*] Too many blank lines (2) @@ -205,8 +175,6 @@ E303 [*] Too many blank lines (2) 62 | class MissingCommand(TypeError): ... # noqa: N818 | help: Remove extraneous blank line(s) - | -58 | - - -59 | from typing import Any, Sequence +58 - +59 - | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__constant_literals.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__constant_literals.snap index c7f121bfedc1c..f775b0dcf5e6a 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__constant_literals.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__constant_literals.snap @@ -13,10 +13,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -3 | ### - - if "abc" is "def": # F632 (fix) +4 - if "abc" is "def": # F632 (fix) 4 + if "abc" == "def": # F632 (fix) -5 | pass | F632 [*] Use `==` to compare constant literals @@ -31,10 +29,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -5 | pass - - if "abc" is None: # F632 (fix, but leaves behind unfixable E711) +6 - if "abc" is None: # F632 (fix, but leaves behind unfixable E711) 6 + if "abc" == None: # F632 (fix, but leaves behind unfixable E711) -7 | pass | F632 [*] Use `==` to compare constant literals @@ -49,10 +45,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -7 | pass - - if None is "abc": # F632 (fix, but leaves behind unfixable E711) +8 - if None is "abc": # F632 (fix, but leaves behind unfixable E711) 8 + if None == "abc": # F632 (fix, but leaves behind unfixable E711) -9 | pass | F632 [*] Use `==` to compare constant literals @@ -67,10 +61,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -9 | pass - - if "abc" is False: # F632 (fix, but leaves behind unfixable E712) +10 - if "abc" is False: # F632 (fix, but leaves behind unfixable E712) 10 + if "abc" == False: # F632 (fix, but leaves behind unfixable E712) -11 | pass | F632 [*] Use `==` to compare constant literals @@ -85,10 +77,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -11 | pass - - if False is "abc": # F632 (fix, but leaves behind unfixable E712) +12 - if False is "abc": # F632 (fix, but leaves behind unfixable E712) 12 + if False == "abc": # F632 (fix, but leaves behind unfixable E712) -13 | pass | E712 [*] Avoid equality comparisons to `False`; use `not None:` for false checks @@ -103,10 +93,8 @@ E712 [*] Avoid equality comparisons to `False`; use `not None:` for false checks | help: Replace with `not None` | -13 | pass - - if False == None: # E711, E712 (fix) +14 - if False == None: # E711, E712 (fix) 14 + if not None: # E711, E712 (fix) -15 | pass | note: This is an unsafe fix and may change runtime behavior @@ -122,10 +110,8 @@ E711 [*] Comparison to `None` should be `cond is None` | help: Replace with `cond is None` | -13 | pass - - if False == None: # E711, E712 (fix) +14 - if False == None: # E711, E712 (fix) 14 + if not None: # E711, E712 (fix) -15 | pass | note: This is an unsafe fix and may change runtime behavior @@ -140,10 +126,8 @@ E711 [*] Comparison to `None` should be `cond is None` | help: Replace with `cond is None` | -15 | pass - - if None == False: # E711, E712 (fix) +16 - if None == False: # E711, E712 (fix) 16 + if not None: # E711, E712 (fix) -17 | pass | note: This is an unsafe fix and may change runtime behavior @@ -158,10 +142,8 @@ E712 [*] Avoid equality comparisons to `False`; use `not None:` for false checks | help: Replace with `not None` | -15 | pass - - if None == False: # E711, E712 (fix) +16 - if None == False: # E711, E712 (fix) 16 + if not None: # E711, E712 (fix) -17 | pass | note: This is an unsafe fix and may change runtime behavior @@ -176,10 +158,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -19 | named_var = [] - - if [] is []: # F632 (fix) +20 - if [] is []: # F632 (fix) 20 + if [] == []: # F632 (fix) -21 | pass | F632 [*] Use `==` to compare constant literals @@ -194,10 +174,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -21 | pass - - if named_var is []: # F632 (fix) +22 - if named_var is []: # F632 (fix) 22 + if named_var == []: # F632 (fix) -23 | pass | F632 [*] Use `==` to compare constant literals @@ -212,10 +190,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -23 | pass - - if [] is named_var: # F632 (fix) +24 - if [] is named_var: # F632 (fix) 24 + if [] == named_var: # F632 (fix) -25 | pass | F632 [*] Use `==` to compare constant literals @@ -230,10 +206,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -25 | pass - - if named_var is [1]: # F632 (fix) +26 - if named_var is [1]: # F632 (fix) 26 + if named_var == [1]: # F632 (fix) -27 | pass | F632 [*] Use `==` to compare constant literals @@ -248,10 +222,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -27 | pass - - if [1] is named_var: # F632 (fix) +28 - if [1] is named_var: # F632 (fix) 28 + if [1] == named_var: # F632 (fix) -29 | pass | F632 [*] Use `==` to compare constant literals @@ -265,10 +237,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -29 | pass - - if named_var is [i for i in [1]]: # F632 (fix) +30 - if named_var is [i for i in [1]]: # F632 (fix) 30 + if named_var == [i for i in [1]]: # F632 (fix) -31 | pass | F632 [*] Use `==` to compare constant literals @@ -282,10 +252,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -33 | named_var = {} - - if {} is {}: # F632 (fix) +34 - if {} is {}: # F632 (fix) 34 + if {} == {}: # F632 (fix) -35 | pass | F632 [*] Use `==` to compare constant literals @@ -300,10 +268,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -35 | pass - - if named_var is {}: # F632 (fix) +36 - if named_var is {}: # F632 (fix) 36 + if named_var == {}: # F632 (fix) -37 | pass | F632 [*] Use `==` to compare constant literals @@ -318,10 +284,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -37 | pass - - if {} is named_var: # F632 (fix) +38 - if {} is named_var: # F632 (fix) 38 + if {} == named_var: # F632 (fix) -39 | pass | F632 [*] Use `==` to compare constant literals @@ -336,10 +300,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -39 | pass - - if named_var is {1}: # F632 (fix) +40 - if named_var is {1}: # F632 (fix) 40 + if named_var == {1}: # F632 (fix) -41 | pass | F632 [*] Use `==` to compare constant literals @@ -354,10 +316,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -41 | pass - - if {1} is named_var: # F632 (fix) +42 - if {1} is named_var: # F632 (fix) 42 + if {1} == named_var: # F632 (fix) -43 | pass | F632 [*] Use `==` to compare constant literals @@ -371,10 +331,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -43 | pass - - if named_var is {i for i in [1]}: # F632 (fix) +44 - if named_var is {i for i in [1]}: # F632 (fix) 44 + if named_var == {i for i in [1]}: # F632 (fix) -45 | pass | F632 [*] Use `==` to compare constant literals @@ -388,10 +346,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -47 | named_var = {1: 1} - - if {1: 1} is {1: 1}: # F632 (fix) +48 - if {1: 1} is {1: 1}: # F632 (fix) 48 + if {1: 1} == {1: 1}: # F632 (fix) -49 | pass | F632 [*] Use `==` to compare constant literals @@ -406,10 +362,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -49 | pass - - if named_var is {1: 1}: # F632 (fix) +50 - if named_var is {1: 1}: # F632 (fix) 50 + if named_var == {1: 1}: # F632 (fix) -51 | pass | F632 [*] Use `==` to compare constant literals @@ -424,10 +378,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -51 | pass - - if {1: 1} is named_var: # F632 (fix) +52 - if {1: 1} is named_var: # F632 (fix) 52 + if {1: 1} == named_var: # F632 (fix) -53 | pass | F632 [*] Use `==` to compare constant literals @@ -442,10 +394,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -53 | pass - - if named_var is {1: 1}: # F632 (fix) +54 - if named_var is {1: 1}: # F632 (fix) 54 + if named_var == {1: 1}: # F632 (fix) -55 | pass | F632 [*] Use `==` to compare constant literals @@ -460,10 +410,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -55 | pass - - if {1: 1} is named_var: # F632 (fix) +56 - if {1: 1} is named_var: # F632 (fix) 56 + if {1: 1} == named_var: # F632 (fix) -57 | pass | F632 [*] Use `==` to compare constant literals @@ -477,8 +425,6 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -57 | pass - - if named_var is {i: 1 for i in [1]}: # F632 (fix) +58 - if named_var is {i: 1 for i in [1]}: # F632 (fix) 58 + if named_var == {i: 1 for i in [1]}: # F632 (fix) -59 | pass | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E40.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E40.py.snap index 565c52fbffa06..022a5e28d84e4 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E40.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E40.py.snap @@ -13,13 +13,8 @@ E402 [*] Module level import not at top of file | help: Move module level imports to top of file | -1 | #: E401 -2 + import foo -3 | import os, sys --------------------------------------------------------------------------------- -56 | - - import foo -57 | #: E402 + 2 + import foo + 3 | import os, sys | note: This is an unsafe fix and may change runtime behavior @@ -35,13 +30,8 @@ E402 [*] Module level import not at top of file | help: Move module level imports to top of file | -1 | #: E401 -2 + import foo -3 | import os, sys --------------------------------------------------------------------------------- -58 | #: E402 - - import foo -59 | + 2 + import foo + 3 | import os, sys | note: This is an unsafe fix and may change runtime behavior @@ -57,13 +47,8 @@ E402 [*] Module level import not at top of file | help: Move module level imports to top of file | -1 | #: E401 -2 + import bar -3 | import os, sys --------------------------------------------------------------------------------- -62 | - - import bar -63 | + 2 + import bar + 3 | import os, sys | note: This is an unsafe fix and may change runtime behavior @@ -77,13 +62,8 @@ E402 [*] Module level import not at top of file | help: Move module level imports to top of file | -1 | #: E401 -2 + import re as regex, string # also with a comment! -3 | import os, sys --------------------------------------------------------------------------------- -65 | #: E401 - - import re as regex, string # also with a comment! -66 | import re as regex, string; x = 1 + 2 + import re as regex, string # also with a comment! + 3 | import os, sys | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_0.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_0.py.snap index dcc852a6d6119..cca65f24789cb 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_0.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_0.py.snap @@ -10,13 +10,8 @@ E402 [*] Module level import not at top of file | ^^^^^^^^ help: Move module level imports to top of file | -1 | """Top-level docstring.""" -2 + import h -3 | --------------------------------------------------------------------------------- -35 | - - import h -36 | + 2 + import h + 3 + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_1.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_1.py.snap index 24250ad891bbe..fc621486eff40 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_1.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_1.py.snap @@ -15,11 +15,6 @@ help: Move module level imports to top of file | 1 + import b 2 | import a -3 | -4 | """Some other docstring.""" -5 | - - import b -6 | | note: This is an unsafe fix and may change runtime behavior @@ -34,8 +29,5 @@ help: Move module level imports to top of file | 1 + import c 2 | import a --------------------------------------------------------------------------------- -9 | - - import c | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_comments.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_comments.py.snap index 58a281d0fbda1..4982d41f423de 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_comments.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_comments.py.snap @@ -15,11 +15,6 @@ help: Move module level imports to top of file | 1 + import last 2 | import os -3 | -4 | print("something") -5 | - - import last -6 | | note: This is an unsafe fix and may change runtime behavior @@ -37,10 +32,6 @@ help: Move module level imports to top of file | 1 + import late # comment-late 2 | import os --------------------------------------------------------------------------------- -7 | - - import late # comment-late -8 | | note: This is an unsafe fix and may change runtime behavior @@ -58,16 +49,10 @@ E402 [*] Module level import not at top of file | help: Move module level imports to top of file | -1 + from late_paren1 import ( # comment-late_paren1 -2 + value -3 + ) -4 | import os --------------------------------------------------------------------------------- -11 | - - from late_paren1 import ( # comment-late_paren1 - - value - - ) -12 | + 1 + from late_paren1 import ( # comment-late_paren1 + 2 + value + 3 + ) + 4 | import os | note: This is an unsafe fix and may change runtime behavior @@ -85,16 +70,10 @@ E402 [*] Module level import not at top of file | help: Move module level imports to top of file | -1 + from late_paren2 import ( -2 + value # comment-late_paren2 -3 + ) -4 | import os --------------------------------------------------------------------------------- -15 | - - from late_paren2 import ( - - value # comment-late_paren2 - - ) -16 | + 1 + from late_paren2 import ( + 2 + value # comment-late_paren2 + 3 + ) + 4 | import os | note: This is an unsafe fix and may change runtime behavior @@ -112,16 +91,10 @@ E402 [*] Module level import not at top of file | help: Move module level imports to top of file | -1 + from late_paren3 import ( -2 + value -3 + ) # comment-late_paren3 -4 | import os --------------------------------------------------------------------------------- -19 | - - from late_paren3 import ( - - value - - ) # comment-late_paren3 -20 | + 1 + from late_paren3 import ( + 2 + value + 3 + ) # comment-late_paren3 + 4 | import os | note: This is an unsafe fix and may change runtime behavior @@ -138,18 +111,11 @@ E402 [*] Module level import not at top of file | |_^ help: Move module level imports to top of file | -1 + from late_paren4 import ( -2 + value1, -3 + value2, # comment-late_paren4 -4 + value3, -5 + ) -6 | import os --------------------------------------------------------------------------------- -25 | - - from late_paren4 import ( - - value1, - - value2, # comment-late_paren4 - - value3, - - ) + 1 + from late_paren4 import ( + 2 + value1, + 3 + value2, # comment-late_paren4 + 4 + value3, + 5 + ) + 6 | import os | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_docstring.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_docstring.py.snap index 11a8669004263..e1892c5b21e41 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_docstring.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_docstring.py.snap @@ -10,11 +10,7 @@ E402 [*] Module level import not at top of file | ^^^^^^^^^ help: Move module level imports to top of file | -1 | """module docstring""" 2 + import os -3 | -4 | print("something") -5 | - - import os +3 + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_future.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_future.py.snap index 398b25c7f7cd2..6cb7b1907dd71 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_future.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_future.py.snap @@ -10,11 +10,7 @@ E402 [*] Module level import not at top of file | ^^^^^^^^^ help: Move module level imports to top of file | -1 | from __future__ import annotations 2 + import os -3 | -4 | print("something") -5 | - - import os +3 + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_shebang.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_shebang.py.snap index 7c270535eb3ff..c3dc63ddb3969 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_shebang.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_shebang.py.snap @@ -10,10 +10,7 @@ E402 [*] Module level import not at top of file | ^^^^^^^^^ help: Move module level imports to top of file | -2 | 3 + import os 4 | print("something") -5 | - - import os | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_shebang_docstring_and_future.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_shebang_docstring_and_future.py.snap index d3b7eb8200f60..15a9c70250a4b 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_shebang_docstring_and_future.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E402_E402_shebang_docstring_and_future.py.snap @@ -10,11 +10,7 @@ E402 [*] Module level import not at top of file | ^^^^^^^^^ help: Move module level imports to top of file | -5 | from __future__ import annotations 6 + import os -7 | -8 | print("something") -9 | - - import os +7 + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E502_E502.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E502_E502.py.snap index d74d6f8f24021..4d697f944005e 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E502_E502.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__E502_E502.py.snap @@ -12,12 +12,10 @@ E502 [*] Redundant backslash 11 | 7) | help: Remove redundant backslash - | -8 | - - a = (3 -\ -9 + a = (3 - -10 | 2 + \ - | + | +9 - a = (3 -\ +9 + a = (3 - + | E502 [*] Redundant backslash --> E502.py:10:11 @@ -29,10 +27,8 @@ E502 [*] Redundant backslash | help: Remove redundant backslash | -9 | a = (3 -\ - - 2 + \ +10 - 2 + \ 10 + 2 + -11 | 7) | E502 [*] Redundant backslash @@ -46,10 +42,8 @@ E502 [*] Redundant backslash | help: Remove redundant backslash | -13 | z = 5 + \ - - (3 -\ +14 - (3 -\ 14 + (3 - -15 | 2 + \ | E502 [*] Redundant backslash @@ -64,10 +58,8 @@ E502 [*] Redundant backslash | help: Remove redundant backslash | -14 | (3 -\ - - 2 + \ +15 - 2 + \ 15 + 2 + -16 | 7) + \ | E502 [*] Redundant backslash @@ -81,10 +73,8 @@ E502 [*] Redundant backslash | help: Remove redundant backslash | -22 | b = [ - - 2 + 4 + 5 + \ +23 - 2 + 4 + 5 + \ 23 + 2 + 4 + 5 + -24 | 44 \ | E502 [*] Redundant backslash @@ -99,10 +89,8 @@ E502 [*] Redundant backslash | help: Remove redundant backslash | -23 | 2 + 4 + 5 + \ - - 44 \ +24 - 44 \ 24 + 44 -25 | - 5 | E502 [*] Redundant backslash @@ -116,10 +104,8 @@ E502 [*] Redundant backslash | help: Remove redundant backslash | -28 | c = (True and - - False \ +29 - False \ 29 + False -30 | or False \ | E502 [*] Redundant backslash @@ -134,10 +120,8 @@ E502 [*] Redundant backslash | help: Remove redundant backslash | -29 | False \ - - or False \ +30 - or False \ 30 + or False -31 | and True \ | E502 [*] Redundant backslash @@ -151,10 +135,8 @@ E502 [*] Redundant backslash | help: Remove redundant backslash | -30 | or False \ - - and True \ +31 - and True \ 31 + and True -32 | ) | E502 [*] Redundant backslash @@ -168,10 +150,8 @@ E502 [*] Redundant backslash | help: Remove redundant backslash | -43 | s = { - - 'x': 2 + \ +44 - 'x': 2 + \ 44 + 'x': 2 + -45 | 2 | E502 [*] Redundant backslash @@ -183,10 +163,8 @@ E502 [*] Redundant backslash | help: Remove redundant backslash | -54 | - - x = {2 + 4 \ +55 - x = {2 + 4 \ 55 + x = {2 + 4 -56 | + 3} | E502 [*] Redundant backslash @@ -201,10 +179,8 @@ E502 [*] Redundant backslash | help: Remove redundant backslash | -60 | + 3 # \ - - + 4 \ +61 - + 4 \ 61 + + 4 -62 | + 3 | E502 [*] Redundant backslash @@ -218,10 +194,8 @@ E502 [*] Redundant backslash | help: Remove redundant backslash | -81 | - - x = ("abc" \ +82 - x = ("abc" \ 82 + x = ("abc" -83 | "xyz") | E502 [*] Redundant backslash @@ -235,10 +209,8 @@ E502 [*] Redundant backslash | help: Remove redundant backslash | -85 | x = [ - - "a" + \ +86 - "a" + \ 86 + "a" + -87 | f""" | E502 [*] Redundant backslash @@ -253,10 +225,8 @@ E502 [*] Redundant backslash | help: Remove redundant backslash | -88 | b - - """ + \ +89 - """ + \ 89 + """ + -90 | "c" | E502 [*] Redundant backslash @@ -269,8 +239,6 @@ E502 [*] Redundant backslash | help: Remove redundant backslash | -94 | def foo(): - - x = (a + \ +95 - x = (a + \ 95 + x = (a + -96 | 2) | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__W391_W391.ipynb.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__W391_W391.ipynb.snap index bb07af429c7b3..fe780b73312ca 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__W391_W391.ipynb.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__W391_W391.ipynb.snap @@ -14,12 +14,9 @@ W391 [*] Too many newlines at end of cell 9 | 1 + 1 | help: Remove trailing newlines - | -5 | - - - - - - -6 | 1 + 1 +5 - +6 - +7 - | W391 [*] Too many newlines at end of cell @@ -36,13 +33,10 @@ W391 [*] Too many newlines at end of cell 16 | 1+1 | help: Remove trailing newlines - | -11 | - - - - - - - - -12 | 1+1 +11 - +12 - +13 - +14 - | W391 [*] Too many newlines at end of cell @@ -52,8 +46,6 @@ W391 [*] Too many newlines at end of cell 20 | | | |_^ help: Remove trailing newlines - | -19 | - - - - +19 - +20 - | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__W391_W391_0.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__W391_W391_0.py.snap index 571d9027bf73a..3f3c9e17c3906 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__W391_W391_0.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__W391_W391_0.py.snap @@ -9,7 +9,5 @@ W391 [*] Extra newline at end of file 14 | | ^ help: Remove trailing newline - | -13 | bar() - - +14 - | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__W391_W391_2.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__W391_W391_2.py.snap index a53365244c042..f8c2e3099ed11 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__W391_W391_2.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__preview__W391_W391_2.py.snap @@ -12,10 +12,8 @@ W391 [*] Too many newlines at end of file 17 | | | |_^ help: Remove trailing newlines - | -13 | bar() - - - - - - - - +14 - +15 - +16 - +17 - | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__shebang.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__shebang.snap index 449a8cf8adf71..ba70e11bfc798 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__shebang.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__shebang.snap @@ -12,8 +12,5 @@ E265 [*] Block comment should start with `# ` | help: Format space | -2 | # - - #! -3 + # ! -4 | #: - | +3 | # ! + | + diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__too_many_blank_lines_isort_compatibility-lines-after(0)-between(0).snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__too_many_blank_lines_isort_compatibility-lines-after(0)-between(0).snap index 783c9fd0451d9..c4a5ae94e5f89 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__too_many_blank_lines_isort_compatibility-lines-after(0)-between(0).snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__too_many_blank_lines_isort_compatibility-lines-after(0)-between(0).snap @@ -12,14 +12,8 @@ I001 [*] Import block is un-sorted or un-formatted | |________________________________^ help: Organize imports | -1 | import json - - - - - - -2 | from typing import Any, Sequence - - - - -3 | class MissingCommand(TypeError): ... # noqa: N818 +1 + import json +2 + from typing import Any, Sequence | E303 [*] Too many blank lines (3) @@ -28,10 +22,9 @@ E303 [*] Too many blank lines (3) 5 | from typing import Any, Sequence | ^^^^ help: Remove extraneous blank line(s) - | -3 | - - -4 | from typing import Any, Sequence +2 - +3 - +4 - | E303 [*] Too many blank lines (2) @@ -40,11 +33,8 @@ E303 [*] Too many blank lines (2) 8 | class MissingCommand(TypeError): ... # noqa: N818 | ^^^^^ help: Remove extraneous blank line(s) - | -5 | from typing import Any, Sequence - - - - -6 | class MissingCommand(TypeError): ... # noqa: N818 +6 - +7 - | E303 [*] Too many blank lines (2) @@ -56,10 +46,8 @@ E303 [*] Too many blank lines (2) 23 | def __init__(self, backend_module: str, backend_obj: str | None) -> None: ... | help: Remove extraneous blank line(s) - | -19 | - - -20 | abcd.foo() +19 - +20 - | I001 [*] Import block is un-sorted or un-formatted @@ -74,10 +62,9 @@ I001 [*] Import block is un-sorted or un-formatted | |___________________________________________^ help: Organize imports | -27 | - - - - -28 | from typing_extensions import TypeAlias +26 + import os +27 + +28 + from typing_extensions import TypeAlias | E303 [*] Too many blank lines (3) @@ -86,11 +73,9 @@ E303 [*] Too many blank lines (3) 30 | from typing_extensions import TypeAlias | ^^^^ help: Remove extraneous blank line(s) - | -27 | - - - - -28 | from typing_extensions import TypeAlias +27 - +28 - +29 - | E303 [*] Too many blank lines (2) @@ -102,10 +87,8 @@ E303 [*] Too many blank lines (2) 35 | def __call__(self, name: str, *args: Any, **kwargs: Any) -> Any: | help: Remove extraneous blank line(s) - | -31 | - - -32 | abcd.foo() +31 - +32 - | I001 [*] Import block is un-sorted or un-formatted @@ -118,9 +101,7 @@ I001 [*] Import block is un-sorted or un-formatted | help: Organize imports | -60 | from typing import Any, Sequence - - -61 | class MissingCommand(TypeError): ... # noqa: N818 +60 + from typing import Any, Sequence | E303 [*] Too many blank lines (1) @@ -131,8 +112,5 @@ E303 [*] Too many blank lines (1) 62 | class MissingCommand(TypeError): ... # noqa: N818 | ^^^^^ help: Remove extraneous blank line(s) - | -60 | from typing import Any, Sequence - - -61 | class MissingCommand(TypeError): ... # noqa: N818 +61 - | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__too_many_blank_lines_isort_compatibility-lines-after(1)-between(1).snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__too_many_blank_lines_isort_compatibility-lines-after(1)-between(1).snap index 03ef751687676..6cb81dbb7080d 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__too_many_blank_lines_isort_compatibility-lines-after(1)-between(1).snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__too_many_blank_lines_isort_compatibility-lines-after(1)-between(1).snap @@ -12,12 +12,9 @@ I001 [*] Import block is un-sorted or un-formatted | |________________________________^ help: Organize imports | -2 | - - - - -3 | from typing import Any, Sequence - - -4 | +1 + import json +2 + +3 + from typing import Any, Sequence | E303 [*] Too many blank lines (3) @@ -26,10 +23,9 @@ E303 [*] Too many blank lines (3) 5 | from typing import Any, Sequence | ^^^^ help: Remove extraneous blank line(s) - | -3 | - - -4 | from typing import Any, Sequence +2 - +3 - +4 - | E303 [*] Too many blank lines (2) @@ -38,10 +34,8 @@ E303 [*] Too many blank lines (2) 8 | class MissingCommand(TypeError): ... # noqa: N818 | ^^^^^ help: Remove extraneous blank line(s) - | -6 | - - -7 | class MissingCommand(TypeError): ... # noqa: N818 +6 - +7 - | E303 [*] Too many blank lines (2) @@ -53,10 +47,8 @@ E303 [*] Too many blank lines (2) 23 | def __init__(self, backend_module: str, backend_obj: str | None) -> None: ... | help: Remove extraneous blank line(s) - | -19 | - - -20 | abcd.foo() +19 - +20 - | I001 [*] Import block is un-sorted or un-formatted @@ -71,10 +63,9 @@ I001 [*] Import block is un-sorted or un-formatted | |___________________________________________^ help: Organize imports | -27 | - - - - -28 | from typing_extensions import TypeAlias +26 + import os +27 + +28 + from typing_extensions import TypeAlias | E303 [*] Too many blank lines (3) @@ -83,11 +74,9 @@ E303 [*] Too many blank lines (3) 30 | from typing_extensions import TypeAlias | ^^^^ help: Remove extraneous blank line(s) - | -27 | - - - - -28 | from typing_extensions import TypeAlias +27 - +28 - +29 - | E303 [*] Too many blank lines (2) @@ -99,8 +88,6 @@ E303 [*] Too many blank lines (2) 35 | def __call__(self, name: str, *args: Any, **kwargs: Any) -> Any: | help: Remove extraneous blank line(s) - | -31 | - - -32 | abcd.foo() +31 - +32 - | diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__w292_4.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__w292_4.snap index b12cf346d6ed9..6c88fc28f06ce 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__w292_4.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__w292_4.snap @@ -8,6 +8,5 @@ W292 [*] No newline at end of file | ^ help: Add trailing newline | - - 1 + | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D200_D.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D200_D.py.snap index 134ff2bb6dae0..c378a5f2cacf8 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D200_D.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D200_D.py.snap @@ -12,12 +12,10 @@ D200 [*] One-line docstring should fit on one line | |_______^ help: Reformat to one line | -128 | def asdlkfasd(): - - """ - - Wrong. - - """ +129 - """ +130 - Wrong. +131 - """ 129 + """Wrong.""" -130 | | note: This is an unsafe fix and may change runtime behavior @@ -32,12 +30,10 @@ D200 [*] One-line docstring should fit on one line | |_____________^ help: Reformat to one line | -596 | def one_liner(): - - """ - - - - Wrong.""" +597 - """ +598 - +599 - Wrong.""" 597 + """Wrong.""" -598 | | note: This is an unsafe fix and may change runtime behavior @@ -52,12 +48,10 @@ D200 [*] One-line docstring should fit on one line | |_______^ help: Reformat to one line | -605 | def one_liner(): - - r"""Wrong. - - - - """ +606 - r"""Wrong. +607 - +608 - """ 606 + r"""Wrong.""" -607 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D200_D200.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D200_D200.py.snap index 72eb17cdede5f..ed6e9c6cba56f 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D200_D200.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D200_D200.py.snap @@ -19,11 +19,9 @@ D200 [*] One-line docstring should fit on one line | |_______^ help: Reformat to one line | -6 | def func(): - - """\\ - - """ +7 - """\\ +8 - """ 7 + """\\""" -8 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D201_D.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D201_D.py.snap index de8307724f34a..09b6606372d26 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D201_D.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D201_D.py.snap @@ -9,10 +9,7 @@ D201 [*] No blank lines allowed before function docstring (found 1) 137 | """Leading space.""" | ^^^^^^^^^^^^^^^^^^^^ help: Remove blank line(s) before function docstring - | -135 | def leading_space(): - - -136 | """Leading space.""" +136 - | D201 [*] No blank lines allowed before function docstring (found 1) @@ -26,10 +23,7 @@ D201 [*] No blank lines allowed before function docstring (found 1) 153 | pass | help: Remove blank line(s) before function docstring - | -149 | def trailing_and_leading_space(): - - -150 | """Trailing and leading space.""" +150 - | D201 [*] No blank lines allowed before function docstring (found 1) @@ -43,10 +37,7 @@ D201 [*] No blank lines allowed before function docstring (found 1) 549 | | """ | |_______^ help: Remove blank line(s) before function docstring - | -544 | def multiline_leading_space(): - - -545 | """Leading space. +545 - | D201 [*] No blank lines allowed before function docstring (found 1) @@ -63,10 +54,7 @@ D201 [*] No blank lines allowed before function docstring (found 1) 573 | pass | help: Remove blank line(s) before function docstring - | -566 | def multiline_trailing_and_leading_space(): - - -567 | """Trailing and leading space. +567 - | D201 No blank lines allowed before function docstring (found 1) diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D202_D.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D202_D.py.snap index 34ca732cd869d..e395e810e777e 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D202_D.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D202_D.py.snap @@ -14,8 +14,6 @@ D202 [*] No blank lines allowed after function docstring (found 1) help: Remove blank line(s) after function docstring | 142 | """Leading space.""" - - -143 | pass | D202 [*] No blank lines allowed after function docstring (found 1) @@ -31,8 +29,6 @@ D202 [*] No blank lines allowed after function docstring (found 1) help: Remove blank line(s) after function docstring | 151 | """Trailing and leading space.""" - - -152 | pass | D202 [*] No blank lines allowed after function docstring (found 1) @@ -51,8 +47,6 @@ D202 [*] No blank lines allowed after function docstring (found 1) help: Remove blank line(s) after function docstring | 558 | """ - - -559 | pass | D202 [*] No blank lines allowed after function docstring (found 1) @@ -71,8 +65,6 @@ D202 [*] No blank lines allowed after function docstring (found 1) help: Remove blank line(s) after function docstring | 571 | """ - - -572 | pass | D202 No blank lines allowed after function docstring (found 1) diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D202_D202.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D202_D202.py.snap index 33e762f4b711e..64295813af3e8 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D202_D202.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D202_D202.py.snap @@ -11,9 +11,6 @@ D202 [*] No blank lines allowed after function docstring (found 2) help: Remove blank line(s) after function docstring | 57 | """This is a docstring.""" - - - - -58 | def inner(): | D202 [*] No blank lines allowed after function docstring (found 2) @@ -26,9 +23,6 @@ D202 [*] No blank lines allowed after function docstring (found 2) help: Remove blank line(s) after function docstring | 68 | """This is a docstring.""" - - - - -69 | # This is a comment. | D202 [*] No blank lines allowed after function docstring (found 1) @@ -44,6 +38,4 @@ D202 [*] No blank lines allowed after function docstring (found 1) help: Remove blank line(s) after function docstring | 80 | """This is a docstring.""" - - -81 | # This is a comment. | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D203_D.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D203_D.py.snap index 992037f4f60a1..ea7a75b7446d7 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D203_D.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D203_D.py.snap @@ -8,10 +8,7 @@ D203 [*] 1 blank line required before class docstring 161 | """Leading space missing.""" | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Insert 1 blank line before class docstring - | -160 | class LeadingSpaceMissing: -161 + -162 | """Leading space missing.""" +161 - """Leading space missing.""" | D203 [*] 1 blank line required before class docstring @@ -23,10 +20,7 @@ D203 [*] 1 blank line required before class docstring 193 | pass | help: Insert 1 blank line before class docstring - | -191 | class LeadingAndTrailingSpaceMissing: -192 + -193 | """Leading and trailing space missing.""" +192 - """Leading and trailing space missing.""" | D203 [*] 1 blank line required before class docstring @@ -46,10 +40,7 @@ D203 [*] 1 blank line required before class docstring 534 | def __init__(self, x): | help: Insert 1 blank line before class docstring - | -525 | class Blah: # noqa: D203,D213 -526 + -527 | """A Blah. +526 - """A Blah. | D203 [*] 1 blank line required before class docstring @@ -62,10 +53,7 @@ D203 [*] 1 blank line required before class docstring 651 | pass | help: Insert 1 blank line before class docstring - | -648 | class StatementOnSameLineAsDocstring: -649 + -650 | "After this docstring there's another statement on the same line separated by a semicolon." ; priorities=1 +649 - "After this docstring there's another statement on the same line separated by a semicolon." ; priorities=1 | D203 [*] 1 blank line required before class docstring @@ -75,10 +63,7 @@ D203 [*] 1 blank line required before class docstring 654 | "After this docstring there's another statement on the same line separated by a semicolon."; priorities=1 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Insert 1 blank line before class docstring - | -653 | class StatementOnSameLineAsDocstring: -654 + -655 | "After this docstring there's another statement on the same line separated by a semicolon."; priorities=1 +654 - "After this docstring there's another statement on the same line separated by a semicolon."; priorities=1 | D203 [*] 1 blank line required before class docstring @@ -91,8 +76,5 @@ D203 [*] 1 blank line required before class docstring 660 | pass | help: Insert 1 blank line before class docstring - | -657 | class CommentAfterDocstring: -658 + -659 | "After this docstring there's a comment." # priorities=1 +658 - "After this docstring there's a comment." # priorities=1 | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D204_D.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D204_D.py.snap index ed5fa25d858b3..6ea982827c67c 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D204_D.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D204_D.py.snap @@ -13,9 +13,7 @@ D204 [*] 1 blank line required after class docstring help: Insert 1 blank line after class docstring | 181 | """TrailingSpace.""" -182 + -183 | pass - | + | + D204 [*] 1 blank line required after class docstring --> D.py:192:5 @@ -28,9 +26,7 @@ D204 [*] 1 blank line required after class docstring help: Insert 1 blank line after class docstring | 192 | """Leading and trailing space missing.""" -193 + -194 | pass - | + | + D204 [*] 1 blank line required after class docstring --> D.py:649:5 @@ -43,12 +39,9 @@ D204 [*] 1 blank line required after class docstring | help: Insert 1 blank line after class docstring | -648 | class StatementOnSameLineAsDocstring: - - "After this docstring there's another statement on the same line separated by a semicolon." ; priorities=1 -649 + "After this docstring there's another statement on the same line separated by a semicolon." -650 + +649 ~ "After this docstring there's another statement on the same line separated by a semicolon." +650 + 651 + priorities=1 -652 | def sort_services(self): | D204 [*] 1 blank line required after class docstring @@ -59,12 +52,9 @@ D204 [*] 1 blank line required after class docstring | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Insert 1 blank line after class docstring | -653 | class StatementOnSameLineAsDocstring: - - "After this docstring there's another statement on the same line separated by a semicolon."; priorities=1 -654 + "After this docstring there's another statement on the same line separated by a semicolon." -655 + +654 ~ "After this docstring there's another statement on the same line separated by a semicolon." +655 + 656 + priorities=1 -657 | | D204 [*] 1 blank line required after class docstring @@ -79,6 +69,4 @@ D204 [*] 1 blank line required after class docstring help: Insert 1 blank line after class docstring | 658 | "After this docstring there's a comment." # priorities=1 -659 + -660 | def sort_services(self): - | + | + diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D205_D.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D205_D.py.snap index 2b09f1aab33af..5dc06f930ae13 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D205_D.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D205_D.py.snap @@ -26,8 +26,6 @@ D205 [*] 1 blank line required between summary line and description (found 2) 215 | | """ | |_______^ help: Insert single blank line - | -211 | - - -212 | Description. +211 - +212 - | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D207_D.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D207_D.py.snap index b9d96c349236e..db9a1a87192c9 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D207_D.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D207_D.py.snap @@ -13,11 +13,8 @@ D207 [*] Docstring is under-indented | help: Increase indentation | -231 | - - Description. -232 + Description. -233 | - | +232 | Description. + | ++++ D207 [*] Docstring is under-indented --> D.py:244:1 @@ -28,11 +25,8 @@ D207 [*] Docstring is under-indented | ^ help: Increase indentation | -243 | - - """ -244 + """ -245 | - | +244 | """ + | ++++ D207 [*] Docstring is under-indented --> D.py:440:1 @@ -45,11 +39,8 @@ D207 [*] Docstring is under-indented | help: Increase indentation | -439 | - - Second Line -440 + Second Line -441 | """ - | +440 | Second Line + | ++++++++++++++++++++++++++++++++ D207 [*] Docstring is under-indented --> D.py:441:1 @@ -59,8 +50,5 @@ D207 [*] Docstring is under-indented | ^ help: Increase indentation | -440 | Second Line - - """ -441 + """ -442 | - | +441 | """ + | ++++++++++++++++++++++++++++++++ diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D208_D.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D208_D.py.snap index 21bddce5ea9c4..a3abc4bbefa89 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D208_D.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D208_D.py.snap @@ -13,11 +13,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -251 | - - Description. -252 + Description. -253 | - | +252 | Description. + | ++++ D208 [*] Docstring is over-indented --> D.py:264:1 @@ -28,11 +25,8 @@ D208 [*] Docstring is over-indented | ^ help: Remove over-indentation | -263 | - - """ -264 + """ -265 | - | +264 | """ + | ++++ D208 [*] Docstring is over-indented --> D.py:272:1 @@ -46,11 +40,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -271 | - - Description. -272 + Description. -273 | - | +272 | Description. + | ++++ D208 [*] Docstring is over-indented --> D.py:673:1 @@ -64,11 +55,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -672 | - - This is overindented -673 + This is overindented -674 | And so is this, but it we should preserve the extra space on this line relative - | +673 | This is overindented + | ++++ D208 [*] Docstring is over-indented --> D.py:674:1 @@ -81,11 +69,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -673 | This is overindented - - And so is this, but it we should preserve the extra space on this line relative -674 + And so is this, but it we should preserve the extra space on this line relative -675 | to the one before - | +674 | And so is this, but it we should preserve the extra space on this line relative + | ++++ D208 [*] Docstring is over-indented --> D.py:675:1 @@ -98,11 +83,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -674 | And so is this, but it we should preserve the extra space on this line relative - - to the one before -675 + to the one before -676 | """ - | +675 | to the one before + | ++++ D208 [*] Docstring is over-indented --> D.py:682:1 @@ -116,11 +98,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -681 | - - This is overindented -682 + This is overindented -683 | And so is this, but it we should preserve the extra space on this line relative - | +682 | This is overindented + | ++++ D208 [*] Docstring is over-indented --> D.py:683:1 @@ -133,11 +112,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -682 | This is overindented - - And so is this, but it we should preserve the extra space on this line relative -683 + And so is this, but it we should preserve the extra space on this line relative -684 | to the one before - | +683 | And so is this, but it we should preserve the extra space on this line relative + | ++++ D208 [*] Docstring is over-indented --> D.py:684:1 @@ -151,11 +127,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -683 | And so is this, but it we should preserve the extra space on this line relative - - to the one before -684 + to the one before -685 | This is also overindented - | +684 | to the one before + | ++++ D208 [*] Docstring is over-indented --> D.py:685:1 @@ -169,11 +142,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -684 | to the one before - - This is also overindented -685 + This is also overindented -686 | And so is this, but it we should preserve the extra space on this line relative - | +685 | This is also overindented + | ++++ D208 [*] Docstring is over-indented --> D.py:686:1 @@ -187,11 +157,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -685 | This is also overindented - - And so is this, but it we should preserve the extra space on this line relative -686 + And so is this, but it we should preserve the extra space on this line relative -687 | to the one before - | +686 | And so is this, but it we should preserve the extra space on this line relative + | ++++ D208 [*] Docstring is over-indented --> D.py:687:1 @@ -204,11 +171,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -686 | And so is this, but it we should preserve the extra space on this line relative - - to the one before -687 + to the one before -688 | """ - | +687 | to the one before + | ++++ D208 [*] Docstring is over-indented --> D.py:695:1 @@ -222,11 +186,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -694 | - - This is overindented -695 + This is overindented -696 | And so is this, but it we should preserve the extra space on this line relative - | +695 | This is overindented + | ++++ D208 [*] Docstring is over-indented --> D.py:696:1 @@ -239,11 +200,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -695 | This is overindented - - And so is this, but it we should preserve the extra space on this line relative -696 + And so is this, but it we should preserve the extra space on this line relative -697 | to the one before - | +696 | And so is this, but it we should preserve the extra space on this line relative + | ++++ D208 [*] Docstring is over-indented --> D.py:697:1 @@ -257,11 +215,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -696 | And so is this, but it we should preserve the extra space on this line relative - - to the one before -697 + to the one before -698 | And the relative indent here should be preserved too - | +697 | to the one before + | ++++ D208 [*] Docstring is over-indented --> D.py:698:1 @@ -274,11 +229,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -697 | to the one before - - And the relative indent here should be preserved too -698 + And the relative indent here should be preserved too -699 | """ - | +698 | And the relative indent here should be preserved too + | ++++ D208 [*] Docstring is over-indented --> D.py:704:1 @@ -292,11 +244,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -703 | - - This is overindented -704 + This is overindented -705 | And so is this, but it we should preserve the extra space on this line relative - | +704 | This is overindented + | ++++ D208 [*] Docstring is over-indented --> D.py:705:1 @@ -309,11 +258,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -704 | This is overindented - - And so is this, but it we should preserve the extra space on this line relative -705 + And so is this, but it we should preserve the extra space on this line relative -706 | This is overindented - | +705 | And so is this, but it we should preserve the extra space on this line relative + | ++++ D208 [*] Docstring is over-indented --> D.py:706:1 @@ -327,11 +273,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -705 | And so is this, but it we should preserve the extra space on this line relative - - This is overindented -706 + This is overindented -707 | This is overindented - | +706 | This is overindented + | ++++ D208 [*] Docstring is over-indented --> D.py:707:1 @@ -344,11 +287,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -706 | This is overindented - - This is overindented -707 + This is overindented -708 | """ - | +707 | This is overindented + | ++++ D208 [*] Docstring is over-indented --> D.py:723:1 @@ -361,8 +301,5 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -722 | - -     Returns: -723 + Returns: -724 | """ - | +723 | Returns: + | ++++ diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D208_D208.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D208_D208.py.snap index 1b574c671ea43..7ad9bc8535e7e 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D208_D208.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D208_D208.py.snap @@ -11,10 +11,7 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -1 | """ - - Author -2 + Author -3 | """ +2 | Author | D208 [*] Docstring is over-indented @@ -29,11 +26,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -7 | """ Remove sampler - - Args: -8 + Args: -9 |     Returns: - | +8 | Args: + | ++++ D208 [*] Docstring is over-indented --> D208.py:9:1 @@ -45,12 +39,9 @@ D208 [*] Docstring is over-indented 10 | """ | help: Remove over-indentation - | -8 | Args: - -     Returns: -9 + Returns: -10 | """ - | + | +9 | Returns: + | ++++ D208 [*] Docstring is over-indented --> D208.py:10:1 @@ -61,11 +52,8 @@ D208 [*] Docstring is over-indented | ^ help: Remove over-indentation | -9 |     Returns: - - """ -10 + """ -11 | - | +10 | """ + | ++++ D208 [*] Docstring is over-indented --> D208.py:24:1 @@ -76,11 +64,8 @@ D208 [*] Docstring is over-indented | ^ help: Remove over-indentation | -23 | Returns: - - """ -24 + """ -25 | - | +24 | """ + | ++++ D208 [*] Docstring is over-indented --> D208.py:29:1 @@ -94,11 +79,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -28 | """All lines are over indented including the last containing the closing quotes - - Args: -29 + Args: -30 | Returns: - | +29 | Args: + | ++++ D208 [*] Docstring is over-indented --> D208.py:30:1 @@ -111,11 +93,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -29 | Args: - - Returns: -30 + Returns: -31 | """ - | +30 | Returns: + | ++++ D208 [*] Docstring is over-indented --> D208.py:31:1 @@ -129,11 +108,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -30 | Returns: - - """ -31 + """ -32 | - | +31 | """ + | ++++ D208 [*] Docstring is over-indented --> D208.py:35:1 @@ -146,11 +122,8 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -34 | """All lines are over indented including the last - - Args: -35 + Args: -36 | Returns""" - | +35 | Args: + | ++++ D208 [*] Docstring is over-indented --> D208.py:36:1 @@ -164,8 +137,5 @@ D208 [*] Docstring is over-indented | help: Remove over-indentation | -35 | Args: - - Returns""" -36 + Returns""" -37 | - | +36 | Returns""" + | ++++ diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D209_D.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D209_D.py.snap index 3d93975d39ee8..ceb60d9c0c6f4 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D209_D.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D209_D.py.snap @@ -12,11 +12,8 @@ D209 [*] Multi-line docstring closing quotes should be on a separate line | |___________________^ help: Move closing quotes to new line | -282 | - - Description.""" -283 + Description. -284 + """ -285 | +283 ~ Description. +284 ~ """ | D209 [*] Multi-line docstring closing quotes should be on a separate line @@ -30,9 +27,6 @@ D209 [*] Multi-line docstring closing quotes should be on a separate line | |_____________________^ help: Move closing quotes to new line | -589 | - - Description. """ -590 + Description. -591 + """ -592 | +590 ~ Description. +591 ~ """ | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D210_D.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D210_D.py.snap index a984c9b0443d9..d5380ce3f833f 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D210_D.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D210_D.py.snap @@ -10,11 +10,8 @@ D210 [*] No whitespaces allowed surrounding docstring text | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Trim surrounding whitespace | -287 | def endswith(): - - """Whitespace at the end. """ -288 + """Whitespace at the end.""" -289 | - | +288 | """Whitespace at the end.""" + | ~~~~~~~~~~~~~~~~~~~~~~ D210 [*] No whitespaces allowed surrounding docstring text --> D.py:293:5 @@ -25,11 +22,8 @@ D210 [*] No whitespaces allowed surrounding docstring text | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Trim surrounding whitespace | -292 | def around(): - - """ Whitespace at everywhere. """ -293 + """Whitespace at everywhere.""" -294 | - | +293 | """Whitespace at everywhere.""" + | ~~~~~~~~~~~~~~~~~~~~~~~~~ D210 [*] No whitespaces allowed surrounding docstring text --> D.py:299:5 @@ -43,11 +37,8 @@ D210 [*] No whitespaces allowed surrounding docstring text | |_______^ help: Trim surrounding whitespace | -298 | def multiline(): - - """ Whitespace at the beginning. -299 + """Whitespace at the beginning. -300 | - | +299 | """Whitespace at the beginning. + | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ D210 No whitespaces allowed surrounding docstring text --> D.py:581:5 diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D211_D.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D211_D.py.snap index 7f30b2fc716c4..82ac96c921a82 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D211_D.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D211_D.py.snap @@ -9,10 +9,7 @@ D211 [*] No blank lines allowed before class docstring 170 | """With leading space.""" | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove blank line(s) before class docstring - | -168 | class WithLeadingSpace: - - -169 | """With leading space.""" +169 - | D211 [*] No blank lines allowed before class docstring @@ -25,8 +22,5 @@ D211 [*] No blank lines allowed before class docstring 182 | pass | help: Remove blank line(s) before class docstring - | -179 | class TrailingSpace: - - -180 | """TrailingSpace.""" +180 - | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D212_D.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D212_D.py.snap index 3660a3edb615a..5779cf20805ad 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D212_D.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D212_D.py.snap @@ -12,11 +12,7 @@ D212 [*] Multi-line docstring summary should start at the first line | |_______^ help: Remove whitespace after opening quotes | -128 | def asdlkfasd(): - - """ - - Wrong. -129 + """Wrong. -130 | """ +129 | """Wrong. | D212 [*] Multi-line docstring summary should start at the first line @@ -30,12 +26,7 @@ D212 [*] Multi-line docstring summary should start at the first line | |_____________^ help: Remove whitespace after opening quotes | -596 | def one_liner(): - - """ - - - - Wrong.""" -597 + """Wrong.""" -598 | +597 | """Wrong.""" | D212 [*] Multi-line docstring summary should start at the first line @@ -49,10 +40,5 @@ D212 [*] Multi-line docstring summary should start at the first line | |______________^ help: Remove whitespace after opening quotes | -623 | def one_liner(): - - """ - - - - "Wrong.""" -624 + """"Wrong.""" -625 | +624 | """"Wrong.""" | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D213_D.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D213_D.py.snap index a2cbde6dbcaf5..8fee91c8e85c2 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D213_D.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D213_D.py.snap @@ -13,11 +13,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |_______^ help: Insert line break and indentation after opening quotes | -199 | def multi_line_zero_separating_blanks(): - - """Summary. -200 + """ -201 + Summary. -202 | Description. +200 ~ """ +201 ~ Summary. | D213 [*] Multi-line docstring summary should start at the second line @@ -34,11 +31,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |_______^ help: Insert line break and indentation after opening quotes | -209 | def multi_line_two_separating_blanks(): - - """Summary. -210 + """ -211 + Summary. -212 | +210 ~ """ +211 ~ Summary. | D213 [*] Multi-line docstring summary should start at the second line @@ -54,11 +48,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |_______^ help: Insert line break and indentation after opening quotes | -219 | def multi_line_one_separating_blanks(): - - """Summary. -220 + """ -221 + Summary. -222 | +220 ~ """ +221 ~ Summary. | D213 [*] Multi-line docstring summary should start at the second line @@ -74,11 +65,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |_______^ help: Insert line break and indentation after opening quotes | -229 | def asdfsdf(): - - """Summary. -230 + """ -231 + Summary. -232 | +230 ~ """ +231 ~ Summary. | D213 [*] Multi-line docstring summary should start at the second line @@ -94,11 +82,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |___^ help: Insert line break and indentation after opening quotes | -239 | def asdsdfsdffsdf(): - - """Summary. -240 + """ -241 + Summary. -242 | +240 ~ """ +241 ~ Summary. | D213 [*] Multi-line docstring summary should start at the second line @@ -114,11 +99,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |_______^ help: Insert line break and indentation after opening quotes | -249 | def asdfsdsdf24(): - - """Summary. -250 + """ -251 + Summary. -252 | +250 ~ """ +251 ~ Summary. | D213 [*] Multi-line docstring summary should start at the second line @@ -134,11 +116,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |___________^ help: Insert line break and indentation after opening quotes | -259 | def asdfsdsdfsdf24(): - - """Summary. -260 + """ -261 + Summary. -262 | +260 ~ """ +261 ~ Summary. | D213 [*] Multi-line docstring summary should start at the second line @@ -154,11 +133,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |_______^ help: Insert line break and indentation after opening quotes | -269 | def asdfsdfsdsdsdfsdf24(): - - """Summary. -270 + """ -271 + Summary. -272 | +270 ~ """ +271 ~ Summary. | D213 [*] Multi-line docstring summary should start at the second line @@ -172,11 +148,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |___________________^ help: Insert line break and indentation after opening quotes | -280 | def asdfljdf24(): - - """Summary. -281 + """ -282 + Summary. -283 | +281 ~ """ +282 ~ Summary. | D213 [*] Multi-line docstring summary should start at the second line @@ -191,11 +164,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |_______^ help: Insert line break and indentation after opening quotes | -298 | def multiline(): - - """ Whitespace at the beginning. -299 + """ -300 + Whitespace at the beginning. -301 | +299 ~ """ +300 ~ Whitespace at the beginning. | D213 [*] Multi-line docstring summary should start at the second line @@ -212,11 +182,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |_______^ help: Insert line break and indentation after opening quotes | -342 | def exceptions_of_D301(): - - """Exclude some backslashes from D301. -343 + """ -344 + Exclude some backslashes from D301. -345 | +343 ~ """ +344 ~ Exclude some backslashes from D301. | D213 [*] Multi-line docstring summary should start at the second line @@ -233,11 +200,8 @@ D213 [*] Multi-line docstring summary should start at the second line | help: Insert line break and indentation after opening quotes | -382 | def new_209(): - - """First line. -383 + """ -384 + First line. -385 | +383 ~ """ +384 ~ First line. | D213 [*] Multi-line docstring summary should start at the second line @@ -253,11 +217,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |_______^ help: Insert line break and indentation after opening quotes | -391 | def old_209(): - - """One liner. -392 + """ -393 + One liner. -394 | +392 ~ """ +393 ~ One liner. | D213 [*] Multi-line docstring summary should start at the second line @@ -273,11 +234,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |_______^ help: Insert line break and indentation after opening quotes | -437 | @expect('D213: Multi-line docstring summary should start at the second line') - - def docstring_start_in_same_line(): """First Line. -438 + def docstring_start_in_same_line(): """ -439 + First Line. -440 | +438 ~ def docstring_start_in_same_line(): """ +439 ~ First Line. | D213 [*] Multi-line docstring summary should start at the second line @@ -293,11 +251,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |_______^ help: Insert line break and indentation after opening quotes | -449 | def a_following_valid_function(x=None): - - """Check for a bug where the previous function caused an assertion. -450 + """ -451 + Check for a bug where the previous function caused an assertion. -452 | +450 ~ """ +451 ~ Check for a bug where the previous function caused an assertion. | D213 [*] Multi-line docstring summary should start at the second line @@ -318,11 +273,8 @@ D213 [*] Multi-line docstring summary should start at the second line | help: Insert line break and indentation after opening quotes | -525 | class Blah: # noqa: D203,D213 - - """A Blah. -526 + """ -527 + A Blah. -528 | +526 ~ """ +527 ~ A Blah. | D213 [*] Multi-line docstring summary should start at the second line @@ -337,11 +289,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |_______^ help: Insert line break and indentation after opening quotes | -545 | - - """Leading space. -546 + """ -547 + Leading space. -548 | +546 ~ """ +547 ~ Leading space. | D213 [*] Multi-line docstring summary should start at the second line @@ -359,11 +308,8 @@ D213 [*] Multi-line docstring summary should start at the second line | help: Insert line break and indentation after opening quotes | -554 | def multiline_trailing_space(): - - """Leading space. -555 + """ -556 + Leading space. -557 | +555 ~ """ +556 ~ Leading space. | D213 [*] Multi-line docstring summary should start at the second line @@ -381,11 +327,8 @@ D213 [*] Multi-line docstring summary should start at the second line | help: Insert line break and indentation after opening quotes | -567 | - - """Trailing and leading space. -568 + """ -569 + Trailing and leading space. -570 | +568 ~ """ +569 ~ Trailing and leading space. | D213 [*] Multi-line docstring summary should start at the second line @@ -399,11 +342,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |_____________________^ help: Insert line break and indentation after opening quotes | -587 | def asdfljdjgf24(): - - """Summary. -588 + """ -589 + Summary. -590 | +588 ~ """ +589 ~ Summary. | D213 [*] Multi-line docstring summary should start at the second line @@ -417,11 +357,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |_______^ help: Insert line break and indentation after opening quotes | -605 | def one_liner(): - - r"""Wrong. -606 + r""" -607 + Wrong. -608 | +606 ~ r""" +607 ~ Wrong. | D213 [*] Multi-line docstring summary should start at the second line @@ -435,11 +372,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |_______^ help: Insert line break and indentation after opening quotes | -614 | def one_liner(): - - """Wrong." -615 + """ -616 + Wrong." -617 | +615 ~ """ +616 ~ Wrong." | D213 [*] Multi-line docstring summary should start at the second line @@ -455,11 +389,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |_______^ help: Insert line break and indentation after opening quotes | -670 | def retain_extra_whitespace(): - - """Summary. -671 + """ -672 + Summary. -673 | +671 ~ """ +672 ~ Summary. | D213 [*] Multi-line docstring summary should start at the second line @@ -478,11 +409,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |_______^ help: Insert line break and indentation after opening quotes | -679 | def retain_extra_whitespace_multiple(): - - """Summary. -680 + """ -681 + Summary. -682 | +680 ~ """ +681 ~ Summary. | D213 [*] Multi-line docstring summary should start at the second line @@ -502,11 +430,8 @@ D213 [*] Multi-line docstring summary should start at the second line | help: Insert line break and indentation after opening quotes | -692 | def retain_extra_whitespace_deeper(): - - """Summary. -693 + """ -694 + Summary. -695 | +693 ~ """ +694 ~ Summary. | D213 [*] Multi-line docstring summary should start at the second line @@ -523,11 +448,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |_______^ help: Insert line break and indentation after opening quotes | -701 | def retain_extra_whitespace_followed_by_same_offset(): - - """Summary. -702 + """ -703 + Summary. -704 | +702 ~ """ +703 ~ Summary. | D213 [*] Multi-line docstring summary should start at the second line @@ -543,11 +465,8 @@ D213 [*] Multi-line docstring summary should start at the second line | |_______^ help: Insert line break and indentation after opening quotes | -711 | def retain_extra_whitespace_not_overindented(): - - """Summary. -712 + """ -713 + Summary. -714 | +712 ~ """ +713 ~ Summary. | D213 [*] Multi-line docstring summary should start at the second line @@ -561,9 +480,6 @@ D213 [*] Multi-line docstring summary should start at the second line | |_______^ help: Insert line break and indentation after opening quotes | -720 | def inconsistent_indent_byte_size(): - - """There's a non-breaking space (2-bytes) after 3 spaces (https://github.com/astral-sh/ruff/issues/9080). -721 + """ -722 + There's a non-breaking space (2-bytes) after 3 spaces (https://github.com/astral-sh/ruff/issues/9080). -723 | +721 ~ """ +722 ~ There's a non-breaking space (2-bytes) after 3 spaces (https://github.com/astral-sh/ruff/issues/9080). | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D214_D214_module.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D214_D214_module.py.snap index 03231873513d3..60d8b66904727 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D214_D214_module.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D214_D214_module.py.snap @@ -13,10 +13,7 @@ D214 [*] Section is over-indented ("Returns") | help: Remove over-indentation from "Returns" | -2 | - - Returns -3 + Returns -4 | ----- +3 | Returns | D214 [*] Section is over-indented ("Args") @@ -31,8 +28,5 @@ D214 [*] Section is over-indented ("Args") | help: Remove over-indentation from "Args" | -6 | - - Args -7 + Args -8 | ----- +7 | Args | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D214_sections.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D214_sections.py.snap index 4356bafc1ca27..d8caa5ca0801d 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D214_sections.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D214_sections.py.snap @@ -13,11 +13,8 @@ D214 [*] Section is over-indented ("Returns") | help: Remove over-indentation from "Returns" | -145 | - - Returns -146 + Returns -147 | ------- - | +146 | Returns + | ++++ D214 [*] Section is over-indented ("Returns") --> sections.py:563:9 @@ -30,8 +27,5 @@ D214 [*] Section is over-indented ("Returns") | help: Remove over-indentation from "Returns" | -562 | - - Returns: -563 + Returns: -564 | """ - | +563 | Returns: + | ++++ diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D215_D215.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D215_D215.py.snap index 4098a2f68cd95..8e0190e2ea04f 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D215_D215.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D215_D215.py.snap @@ -12,8 +12,5 @@ D215 [*] Section underline is over-indented ("TODO") | help: Remove over-indentation from "TODO" underline | -2 | TODO: - - - -3 + -4 | """ +3 - - | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D215_sections.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D215_sections.py.snap index dbe279db10793..1ff0305422681 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D215_sections.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D215_sections.py.snap @@ -11,10 +11,8 @@ D215 [*] Section underline is over-indented ("Returns") | help: Remove over-indentation from "Returns" underline | -158 | Returns - - ------- +159 - ------- 159 + ------ -160 | A value of some sort. | D215 [*] Section underline is over-indented ("Returns") @@ -27,8 +25,6 @@ D215 [*] Section underline is over-indented ("Returns") | help: Remove over-indentation from "Returns" underline | -172 | Returns - - ------- +173 - ------- 173 + ------ -174 | """ | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D300_D.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D300_D.py.snap index f11fe7926f700..1bea75951643c 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D300_D.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D300_D.py.snap @@ -10,10 +10,8 @@ D300 [*] Use triple double quotes `"""` | ^^^^^^^^^^^^^^^ help: Convert to triple double quotes | -306 | def triple_single_quotes_raw(): - - r'''Summary.''' +307 - r'''Summary.''' 307 + r"""Summary.""" -308 | | D300 [*] Use triple double quotes `"""` @@ -25,10 +23,8 @@ D300 [*] Use triple double quotes `"""` | ^^^^^^^^^^^^^^^ help: Convert to triple double quotes | -311 | def triple_single_quotes_raw_uppercase(): - - R'''Summary.''' +312 - R'''Summary.''' 312 + R"""Summary.""" -313 | | D300 [*] Use triple double quotes `"""` @@ -40,10 +36,8 @@ D300 [*] Use triple double quotes `"""` | ^^^^^^^^^^^ help: Convert to triple double quotes | -316 | def single_quotes_raw(): - - r'Summary.' +317 - r'Summary.' 317 + r"""Summary.""" -318 | | D300 [*] Use triple double quotes `"""` @@ -55,10 +49,8 @@ D300 [*] Use triple double quotes `"""` | ^^^^^^^^^^^ help: Convert to triple double quotes | -321 | def single_quotes_raw_uppercase(): - - R'Summary.' +322 - R'Summary.' 322 + R"""Summary.""" -323 | | D300 [*] Use triple double quotes `"""` @@ -70,10 +62,8 @@ D300 [*] Use triple double quotes `"""` | ^^^^^^^^^^^^ help: Convert to triple double quotes | -327 | def single_quotes_raw_uppercase_backslash(): - - R'Sum\mary.' +328 - R'Sum\mary.' 328 + R"""Sum\mary.""" -329 | | D300 [*] Use triple double quotes `"""` @@ -88,12 +78,8 @@ D300 [*] Use triple double quotes `"""` | help: Convert to triple double quotes | -644 | def single_line_docstring_with_an_escaped_backslash(): - - "\ - - " -645 + """\ +645 ~ """\ 646 + """ -647 | | D300 [*] Use triple double quotes `"""` @@ -107,10 +93,8 @@ D300 [*] Use triple double quotes `"""` | help: Convert to triple double quotes | -648 | class StatementOnSameLineAsDocstring: - - "After this docstring there's another statement on the same line separated by a semicolon." ; priorities=1 +649 - "After this docstring there's another statement on the same line separated by a semicolon." ; priorities=1 649 + """After this docstring there's another statement on the same line separated by a semicolon.""" ; priorities=1 -650 | def sort_services(self): | D300 [*] Use triple double quotes `"""` @@ -121,10 +105,8 @@ D300 [*] Use triple double quotes `"""` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Convert to triple double quotes | -653 | class StatementOnSameLineAsDocstring: - - "After this docstring there's another statement on the same line separated by a semicolon."; priorities=1 +654 - "After this docstring there's another statement on the same line separated by a semicolon."; priorities=1 654 + """After this docstring there's another statement on the same line separated by a semicolon."""; priorities=1 -655 | | D300 [*] Use triple double quotes `"""` @@ -138,10 +120,8 @@ D300 [*] Use triple double quotes `"""` | help: Convert to triple double quotes | -657 | class CommentAfterDocstring: - - "After this docstring there's a comment." # priorities=1 +658 - "After this docstring there's a comment." # priorities=1 658 + """After this docstring there's a comment.""" # priorities=1 -659 | def sort_services(self): | D300 [*] Use triple double quotes `"""` @@ -153,10 +133,6 @@ D300 [*] Use triple double quotes `"""` | |_________________________________________________________^ help: Convert to triple double quotes | -663 | def newline_after_closing_quote(self): - - "We enforce a newline after the closing quote for a multi-line docstring \ - - but continuations shouldn't be considered multi-line" -664 + """We enforce a newline after the closing quote for a multi-line docstring \ +664 ~ """We enforce a newline after the closing quote for a multi-line docstring \ 665 + but continuations shouldn't be considered multi-line""" -666 | | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D300_D300.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D300_D300.py.snap index 794d33e32e54e..b96099cedfbc3 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D300_D300.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D300_D300.py.snap @@ -17,8 +17,6 @@ D300 [*] Use triple double quotes `"""` | ^^^^^^^^^^^^^ help: Convert to triple double quotes | -9 | def contains_quote(): - - 'Sum"\\mary.' +10 - 'Sum"\\mary.' 10 + """Sum"\\mary.""" -11 | | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D301_D.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D301_D.py.snap index 9d1f0339a35e7..159429730643c 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D301_D.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D301_D.py.snap @@ -10,9 +10,6 @@ D301 [*] Use `r"""` if any backslashes in a docstring | ^^^^^^^^^^^^^^^^ help: Add `r` prefix | -332 | def double_quotes_backslash(): - - """Sum\\mary.""" -333 + r"""Sum\\mary.""" -334 | - | +333 | r"""Sum\\mary.""" + | + note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D301_D301.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D301_D301.py.snap index a6501bd05b1e2..b38f5608fa207 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D301_D301.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D301_D301.py.snap @@ -9,11 +9,8 @@ D301 [*] Use `r"""` if any backslashes in a docstring | ^^^^^^^^^^^^^^^^ help: Add `r` prefix | -1 | def double_quotes_backslash(): - - """Sum\\mary.""" -2 + r"""Sum\\mary.""" -3 | - | +2 | r"""Sum\\mary.""" + | + note: This is an unsafe fix and may change runtime behavior D301 Use `r"""` if any backslashes in a docstring @@ -34,11 +31,8 @@ D301 [*] Use `r"""` if any backslashes in a docstring | |_______^ help: Add `r` prefix | -92 | def should_add_raw_for_single_double_quote_escape(): - - """ -93 + r""" -94 | This is single quote escape \". - | +93 | r""" + | + note: This is an unsafe fix and may change runtime behavior D301 [*] Use `r"""` if any backslashes in a docstring @@ -50,10 +44,7 @@ D301 [*] Use `r"""` if any backslashes in a docstring 101 | | ''' | |_______^ help: Add `r` prefix - | -98 | def should_add_raw_for_single_single_quote_escape(): - - ''' -99 + r''' -100 | This is single quote escape \'. - | + | +99 | r''' + | + note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D400_D.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D400_D.py.snap index a51349390f667..a6b84bb69fae7 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D400_D.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D400_D.py.snap @@ -10,11 +10,8 @@ D400 [*] First line should end with a period | ^^^^^^^^^^^^^ help: Add period | -354 | def lwnlkjl(): - - """Summary""" -355 + """Summary.""" -356 | - | +355 | """Summary.""" + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -26,11 +23,8 @@ D400 [*] First line should end with a period | ^^^^^^^^^^^^^^^ help: Add period | -405 | " or exclamation point (not 'r')") - - def oneliner_withdoc(): """One liner""" -406 + def oneliner_withdoc(): """One liner.""" -407 | - | +406 | def oneliner_withdoc(): """One liner.""" + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -44,11 +38,8 @@ D400 [*] First line should end with a period | help: Add period | -409 | def ignored_decorator(func): # noqa: D400,D401,D415 - - """Runs something""" -410 + """Runs something.""" -411 | func() - | +410 | """Runs something.""" + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -62,11 +53,8 @@ D400 [*] First line should end with a period | help: Add period | -415 | def decorator_for_test(func): # noqa: D400,D401,D415 - - """Runs something""" -416 + """Runs something.""" -417 | func() - | +416 | """Runs something.""" + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -77,11 +65,8 @@ D400 [*] First line should end with a period | ^^^^^^^^^^^^^^^ help: Add period | -421 | @ignored_decorator - - def oneliner_ignored_decorator(): """One liner""" -422 + def oneliner_ignored_decorator(): """One liner.""" -423 | - | +422 | def oneliner_ignored_decorator(): """One liner.""" + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -93,11 +78,8 @@ D400 [*] First line should end with a period | ^^^^^^^^^^^^^^^ help: Add period | -428 | " or exclamation point (not 'r')") - - def oneliner_with_decorator_expecting_errors(): """One liner""" -429 + def oneliner_with_decorator_expecting_errors(): """One liner.""" -430 | - | +429 | def oneliner_with_decorator_expecting_errors(): """One liner.""" + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -111,11 +93,8 @@ D400 [*] First line should end with a period | help: Add period | -469 | def docstring_bad(): - - """Runs something""" -470 + """Runs something.""" -471 | pass - | +470 | """Runs something.""" + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -128,11 +107,8 @@ D400 [*] First line should end with a period | help: Add period | -474 | def docstring_bad_ignore_all(): # noqa - - """Runs something""" -475 + """Runs something.""" -476 | pass - | +475 | """Runs something.""" + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -145,11 +121,8 @@ D400 [*] First line should end with a period | help: Add period | -479 | def docstring_bad_ignore_one(): # noqa: D400,D401,D415 - - """Runs something""" -480 + """Runs something.""" -481 | pass - | +480 | """Runs something.""" + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -163,11 +136,8 @@ D400 [*] First line should end with a period | help: Add period | -486 | def docstring_ignore_some_violations_but_catch_D401(): # noqa: E501,D400,D415 - - """Runs something""" -487 + """Runs something.""" -488 | pass - | +487 | """Runs something.""" + | + note: This is an unsafe fix and may change runtime behavior D400 First line should end with a period @@ -187,11 +157,8 @@ D400 [*] First line should end with a period | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add period | -519 | def bad_google_string(): # noqa: D400 - - """Test a valid something""" -520 + """Test a valid something.""" -521 | - | +520 | """Test a valid something.""" + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -203,11 +170,8 @@ D400 [*] First line should end with a period | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add period | -580 | def endswith_quote(): - - """Whitespace at the end, but also a quote" """ -581 + """Whitespace at the end, but also a quote". """ -582 | - | +581 | """Whitespace at the end, but also a quote". """ + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -221,11 +185,8 @@ D400 [*] First line should end with a period | |_______^ help: Add period | -614 | def one_liner(): - - """Wrong." -615 + """Wrong.". -616 | - | +615 | """Wrong.". + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -238,11 +199,8 @@ D400 [*] First line should end with a period | help: Add period | -638 | - - class SameLine: """This is a docstring on the same line""" -639 + class SameLine: """This is a docstring on the same line.""" -640 | - | +639 | class SameLine: """This is a docstring on the same line.""" + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -254,11 +212,8 @@ D400 [*] First line should end with a period | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add period | -640 | - - def same_line(): """This is a docstring on the same line""" -641 + def same_line(): """This is a docstring on the same line.""" -642 | - | +641 | def same_line(): """This is a docstring on the same line.""" + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -270,9 +225,6 @@ D400 [*] First line should end with a period | |_________________________________________________________^ help: Add period | -664 | "We enforce a newline after the closing quote for a multi-line docstring \ - - but continuations shouldn't be considered multi-line" -665 + but continuations shouldn't be considered multi-line." -666 | - | +665 | but continuations shouldn't be considered multi-line." + | + note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D400_D400.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D400_D400.py.snap index dc4d4c64e99e1..0e700b2fe62aa 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D400_D400.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D400_D400.py.snap @@ -11,11 +11,8 @@ D400 [*] First line should end with a period | help: Add period | -1 | def f(): - - "Here's a line without a period" -2 + "Here's a line without a period." -3 | ... - | +2 | "Here's a line without a period." + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -28,11 +25,8 @@ D400 [*] First line should end with a period | help: Add period | -6 | def f(): - - """Here's a line without a period""" -7 + """Here's a line without a period.""" -8 | ... - | +7 | """Here's a line without a period.""" + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -48,11 +42,8 @@ D400 [*] First line should end with a period | help: Add period | -13 | Here's a line without a period, - - but here's the next line -14 + but here's the next line. -15 | """ - | +14 | but here's the next line. + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -65,11 +56,8 @@ D400 [*] First line should end with a period | help: Add period | -19 | def f(): - - """Here's a line without a period""" -20 + """Here's a line without a period.""" -21 | ... - | +20 | """Here's a line without a period.""" + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -84,11 +72,8 @@ D400 [*] First line should end with a period | help: Add period | -26 | Here's a line without a period, - - but here's the next line""" -27 + but here's the next line.""" -28 | ... - | +27 | but here's the next line.""" + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -103,11 +88,8 @@ D400 [*] First line should end with a period | help: Add period | -33 | Here's a line without a period, - - but here's the next line with trailing space """ -34 + but here's the next line with trailing space. """ -35 | ... - | +34 | but here's the next line with trailing space. """ + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -120,11 +102,8 @@ D400 [*] First line should end with a period | help: Add period | -38 | def f(): - - r"Here's a line without a period" -39 + r"Here's a line without a period." -40 | ... - | +39 | r"Here's a line without a period." + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -137,11 +116,8 @@ D400 [*] First line should end with a period | help: Add period | -43 | def f(): - - r"""Here's a line without a period""" -44 + r"""Here's a line without a period.""" -45 | ... - | +44 | r"""Here's a line without a period.""" + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -157,11 +133,8 @@ D400 [*] First line should end with a period | help: Add period | -50 | Here's a line without a period, - - but here's the next line -51 + but here's the next line. -52 | """ - | +51 | but here's the next line. + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -174,11 +147,8 @@ D400 [*] First line should end with a period | help: Add period | -56 | def f(): - - r"""Here's a line without a period""" -57 + r"""Here's a line without a period.""" -58 | ... - | +57 | r"""Here's a line without a period.""" + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -193,11 +163,8 @@ D400 [*] First line should end with a period | help: Add period | -63 | Here's a line without a period, - - but here's the next line""" -64 + but here's the next line.""" -65 | ... - | +64 | but here's the next line.""" + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -212,11 +179,8 @@ D400 [*] First line should end with a period | help: Add period | -70 | Here's a line without a period, - - but here's the next line with trailing space """ -71 + but here's the next line with trailing space. """ -72 | ... - | +71 | but here's the next line with trailing space. """ + | + note: This is an unsafe fix and may change runtime behavior D400 [*] First line should end with a period @@ -232,9 +196,6 @@ D400 [*] First line should end with a period | |_______^ help: Add period | -97 | """ - - My example -98 + My example. -99 | ========== - | +98 | My example. + | + note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D400_D400_415.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D400_D400_415.py.snap index 8366c2abbd55c..69a35f62a8414 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D400_D400_415.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D400_D400_415.py.snap @@ -51,9 +51,6 @@ D400 [*] First line should end with a period | help: Add period | -18 | def f(): - - """Here's a line ending with a whitespace """ -19 + """Here's a line ending with a whitespace. """ -20 | ... - | +19 | """Here's a line ending with a whitespace. """ + | + note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D403_D403.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D403_D403.py.snap index b50c3780727d0..27139d4c3b182 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D403_D403.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D403_D403.py.snap @@ -12,10 +12,8 @@ D403 [*] First word of the docstring should be capitalized: `this` -> `This` | help: Capitalize `this` to `This` | -1 | def bad_function(): - - """this docstring is not capitalized""" +2 - """this docstring is not capitalized""" 2 + """This docstring is not capitalized""" -3 | | D403 [*] First word of the docstring should be capitalized: `singleword` -> `Singleword` @@ -29,10 +27,8 @@ D403 [*] First word of the docstring should be capitalized: `singleword` -> `Sin | help: Capitalize `singleword` to `Singleword` | -29 | def single_word(): - - """singleword.""" +30 - """singleword.""" 30 + """Singleword.""" -31 | | D403 [*] First word of the docstring should be capitalized: `singleword` -> `Singleword` @@ -46,10 +42,8 @@ D403 [*] First word of the docstring should be capitalized: `singleword` -> `Sin | help: Capitalize `singleword` to `Singleword` | -32 | def single_word_no_dot(): - - """singleword""" +33 - """singleword""" 33 + """Singleword""" -34 | | D403 [*] First word of the docstring should be capitalized: `here` -> `Here` @@ -70,10 +64,8 @@ D403 [*] First word of the docstring should be capitalized: `here` -> `Here` | help: Capitalize `here` to `Here` | -39 | - - here is the start of my docstring! +40 - here is the start of my docstring! 40 + Here is the start of my docstring! -41 | | D403 [*] First word of the docstring should be capitalized: `singleword` -> `Singleword` @@ -89,10 +81,8 @@ D403 [*] First word of the docstring should be capitalized: `singleword` -> `Sin | help: Capitalize `singleword` to `Singleword` | -45 | def single_word_newline(): - - """singleword +46 - """singleword 46 + """Singleword -47 | | D403 [*] First word of the docstring should be capitalized: `singleword` -> `Singleword` @@ -108,10 +98,8 @@ D403 [*] First word of the docstring should be capitalized: `singleword` -> `Sin | help: Capitalize `singleword` to `Singleword` | -50 | def single_word_dot_newline(): - - """singleword. +51 - """singleword. 51 + """Singleword. -52 | | D403 [*] First word of the docstring should be capitalized: `singleword` -> `Singleword` @@ -127,10 +115,8 @@ D403 [*] First word of the docstring should be capitalized: `singleword` -> `Sin | help: Capitalize `singleword` to `Singleword` | -56 | """ - - singleword +57 - singleword 57 + Singleword -58 | """ | D403 [*] First word of the docstring should be capitalized: `singleword` -> `Singleword` @@ -146,10 +132,8 @@ D403 [*] First word of the docstring should be capitalized: `singleword` -> `Sin | help: Capitalize `singleword` to `Singleword` | -61 | """ - - singleword. +62 - singleword. 62 + Singleword. -63 | """ | D403 [*] First word of the docstring should be capitalized: `singleword` -> `Singleword` @@ -166,10 +150,8 @@ D403 [*] First word of the docstring should be capitalized: `singleword` -> `Sin | help: Capitalize `singleword` to `Singleword` | -65 | def single_word_then_more_text(): - - """singleword +66 - """singleword 66 + """Singleword -67 | | D403 [*] First word of the docstring should be capitalized: `singleword` -> `Singleword` @@ -186,10 +168,8 @@ D403 [*] First word of the docstring should be capitalized: `singleword` -> `Sin | help: Capitalize `singleword` to `Singleword` | -71 | def single_word_dot_then_more_text(): - - """singleword. +72 - """singleword. 72 + """Singleword. -73 | | D403 [*] First word of the docstring should be capitalized: `singleword` -> `Singleword` @@ -207,10 +187,8 @@ D403 [*] First word of the docstring should be capitalized: `singleword` -> `Sin | help: Capitalize `singleword` to `Singleword` | -78 | """ - - singleword +79 - singleword 79 + Singleword -80 | | D403 [*] First word of the docstring should be capitalized: `singleword` -> `Singleword` @@ -225,8 +203,6 @@ D403 [*] First word of the docstring should be capitalized: `singleword` -> `Sin | |_______^ help: Capitalize `singleword` to `Singleword` | -85 | """ - - singleword. +86 - singleword. 86 + Singleword. -87 | | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D405_sections.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D405_sections.py.snap index 3d12478389f6c..61691812301db 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D405_sections.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D405_sections.py.snap @@ -13,10 +13,8 @@ D405 [*] Section name should be properly capitalized ("returns") | help: Capitalize "returns" | -18 | - - returns +19 - returns 19 + Returns -20 | ------- | D405 [*] Section name should be properly capitalized ("Short summary") @@ -30,10 +28,8 @@ D405 [*] Section name should be properly capitalized ("Short summary") | help: Capitalize "Short summary" | -217 | - - Short summary +218 - Short summary 218 + Short Summary -219 | ------------- | D405 [*] Section name should be properly capitalized ("returns") @@ -48,8 +44,6 @@ D405 [*] Section name should be properly capitalized ("returns") | help: Capitalize "returns" | -572 | - - returns: +573 - returns: 573 + Returns: -574 | Here's another note. | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D406_sections.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D406_sections.py.snap index 8e60342e2630e..4c5b80c5c12c0 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D406_sections.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D406_sections.py.snap @@ -13,10 +13,8 @@ D406 [*] Section name should end with a newline ("Returns") | help: Add newline after "Returns" | -31 | - - Returns: +32 - Returns: 32 + Returns -33 | ------- | D406 [*] Section name should end with a newline ("Raises") @@ -30,10 +28,8 @@ D406 [*] Section name should end with a newline ("Raises") | help: Add newline after "Raises" | -226 | Many many wonderful things. - - Raises: +227 - Raises: 227 + Raises -228 | My attention. | D406 [*] Section name should end with a newline ("Parameters") @@ -48,8 +44,6 @@ D406 [*] Section name should end with a newline ("Parameters") | help: Add newline after "Parameters" | -600 | - - Parameters: +601 - Parameters: 601 + Parameters -602 | ---------- | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D407_sections.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D407_sections.py.snap index 90e97c63ea063..a2eb5d31b04eb 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D407_sections.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D407_sections.py.snap @@ -12,9 +12,8 @@ D407 [*] Missing dashed underline after section ("Returns") | help: Add dashed line under "Returns" | -44 | Returns +44 ~ Returns 45 + ------- -46 | A value of some sort. | D407 [*] Missing dashed underline after section ("Returns") @@ -29,9 +28,8 @@ D407 [*] Missing dashed underline after section ("Returns") | help: Add dashed line under "Returns" | -56 | Returns +56 ~ Returns 57 + ------- -58 | | D407 [*] Missing dashed underline after section ("Returns") @@ -43,11 +41,8 @@ D407 [*] Missing dashed underline after section ("Returns") | ^^^^^^^ help: Add dashed line under "Returns" | -66 | - - Returns""" -67 + Returns -68 + -------""" -69 | +67 ~ Returns +68 ~ -------""" | D407 [*] Missing dashed underline after section ("Raises") @@ -61,9 +56,8 @@ D407 [*] Missing dashed underline after section ("Raises") | help: Add dashed line under "Raises" | -227 | Raises: +227 ~ Raises: 228 + ------ -229 | My attention. | D407 [*] Missing dashed underline after section ("Parameters") @@ -76,10 +70,8 @@ D407 [*] Missing dashed underline after section ("Parameters") | help: Add dashed line under "Parameters" | -521 | Parameters - - ========== +522 - ========== 522 + ---------- -523 | """ | D407 [*] Missing dashed underline after section ("Parameters") @@ -92,10 +84,8 @@ D407 [*] Missing dashed underline after section ("Parameters") | help: Add dashed line under "Parameters" | -529 | Parameters - - =========== +530 - =========== 530 + ---------- -531 | """ | D407 [*] Missing dashed underline after section ("Parameters") @@ -110,7 +100,6 @@ D407 [*] Missing dashed underline after section ("Parameters") | help: Add dashed line under "Parameters" | -613 | Parameters +613 ~ Parameters 614 + ---------- -615 | -‐----------------- | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D408_sections.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D408_sections.py.snap index 79a5025831ac1..d15d0f2a39bf4 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D408_sections.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D408_sections.py.snap @@ -11,8 +11,5 @@ D408 [*] Section underline should be in the line following the section's name (" 99 | A value of some sort. | help: Add underline to "Returns" - | -96 | Returns - - -97 | ------- +97 - | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D409_sections.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D409_sections.py.snap index 95b91e7bbe6b5..34427603cd1f7 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D409_sections.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D409_sections.py.snap @@ -11,11 +11,8 @@ D409 [*] Section underline should match the length of its name ("Returns") | help: Adjust underline length to match "Returns" | -110 | Returns - - -- -111 + ------- -112 | A value of some sort. - | +111 | ------- + | +++++ D409 [*] Section underline should match the length of its name ("Returns") --> sections.py:225:5 @@ -28,11 +25,8 @@ D409 [*] Section underline should match the length of its name ("Returns") | help: Adjust underline length to match "Returns" | -224 | Returns - - ------ -225 + ------- -226 | Many many wonderful things. - | +225 | ------- + | + D409 [*] Section underline should match the length of its name ("Other Parameters") --> sections.py:589:5 @@ -45,8 +39,5 @@ D409 [*] Section underline should match the length of its name ("Other Parameter | help: Adjust underline length to match "Other Parameters" | -588 | Other Parameters - - ---------- -589 + ---------------- -590 | other_parameters: - | +589 | ---------------- + | ++++++ diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D410_D410.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D410_D410.py.snap index 688c5e8f5a9eb..46c43e6823381 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D410_D410.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D410_D410.py.snap @@ -12,10 +12,7 @@ D410 [*] Missing blank line after section ("Parameters") 6 | a : int | help: Add blank line after "Parameters" - | -9 | _description_ -10 + -11 | Returns +10 - Returns | D410 [*] Missing blank line after section ("Parameters") @@ -29,8 +26,5 @@ D410 [*] Missing blank line after section ("Parameters") 23 | Returns | help: Add blank line after "Parameters" - | -22 | ---------- -23 + -24 | Returns +23 - Returns | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D410_sections.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D410_sections.py.snap index 4ef9aaf74fce0..b0a639d9e5069 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D410_sections.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D410_sections.py.snap @@ -12,10 +12,7 @@ D410 [*] Missing blank line after section ("Returns") 80 | Yields | help: Add blank line after "Returns" - | -79 | ------- -80 + -81 | Yields +80 - Yields | D410 [*] Missing blank line after section ("Returns") @@ -29,8 +26,5 @@ D410 [*] Missing blank line after section ("Returns") 226 | Many many wonderful things. | help: Add blank line after "Returns" - | -226 | Many many wonderful things. -227 + -228 | Raises: +227 - Raises: | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D411_sections.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D411_sections.py.snap index 9d7e16b96428e..94c1ccb49e233 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D411_sections.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D411_sections.py.snap @@ -11,10 +11,7 @@ D411 [*] Missing blank line before section ("Yields") 81 | ------ | help: Add blank line before "Yields" - | -79 | ------- -80 + -81 | Yields +80 - Yields | D411 [*] Missing blank line before section ("Returns") @@ -27,10 +24,7 @@ D411 [*] Missing blank line before section ("Returns") 136 | A value of some sort. | help: Add blank line before "Returns" - | -133 | The function's description. -134 + -135 | Returns +134 - Returns | D411 [*] Missing blank line before section ("Raises") @@ -43,8 +37,5 @@ D411 [*] Missing blank line before section ("Raises") 228 | My attention. | help: Add blank line before "Raises" - | -226 | Many many wonderful things. -227 + -228 | Raises: +227 - Raises: | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D412_sections.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D412_sections.py.snap index 143bb676e882d..00c8b13338825 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D412_sections.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D412_sections.py.snap @@ -11,8 +11,5 @@ D412 [*] No blank lines allowed between a section header and its content ("Short 219 | ------------- | help: Remove blank line(s) - | -219 | ------------- - - -220 | This is the function's description, which will also specify what it +220 - | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D412_sphinx.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D412_sphinx.py.snap index b3668e3c29bc1..8af60ed811ced 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D412_sphinx.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D412_sphinx.py.snap @@ -9,10 +9,8 @@ D412 [*] No blank lines allowed between a section header and its content ("Examp 13 | Example: | ^^^^^^^ help: Remove blank line(s) - | -14 | - - -15 | .. code-block:: python +14 - +15 - | D412 [*] No blank lines allowed between a section header and its content ("Example") @@ -23,11 +21,9 @@ D412 [*] No blank lines allowed between a section header and its content ("Examp 24 | Example: | ^^^^^^^ help: Remove blank line(s) - | -25 | - - - - -26 | .. code-block:: python +25 - +26 - +27 - | D412 [*] No blank lines allowed between a section header and its content ("Example") @@ -40,10 +36,8 @@ D412 [*] No blank lines allowed between a section header and its content ("Examp 48 | ------- | help: Remove blank line(s) - | -49 | - - -50 | .. code-block:: python +49 - +50 - | D412 [*] No blank lines allowed between a section header and its content ("Example") @@ -56,9 +50,7 @@ D412 [*] No blank lines allowed between a section header and its content ("Examp 60 | ------- | help: Remove blank line(s) - | -61 | - - - - -62 | .. code-block:: python +61 - +62 - +63 - | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D413_D413.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D413_D413.py.snap index 5aca8ab835f92..9e1ae893083d8 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D413_D413.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D413_D413.py.snap @@ -12,11 +12,8 @@ D413 [*] Missing blank line after last section ("Returns") 9 | """ | help: Add blank line after "Returns" - | -8 | the value -9 + -10 | """ - | +9 - """ + | D413 [*] Missing blank line after last section ("Returns") --> D413.py:19:5 @@ -29,10 +26,7 @@ D413 [*] Missing blank line after last section ("Returns") 21 | """ | help: Add blank line after "Returns" - | -20 | the value -21 + -22 | """ +21 - """ | D413 [*] Missing blank line after last section ("Returns") @@ -46,12 +40,9 @@ D413 [*] Missing blank line after last section ("Returns") | help: Add blank line after "Returns" | -58 | Returns: - - the value""" -59 + the value -60 + -61 + """ -62 | +59 ~ the value +60 + +61 ~ """ | D413 [*] Missing blank line after last section ("Returns") @@ -66,12 +57,8 @@ D413 [*] Missing blank line after last section ("Returns") | help: Add blank line after "Returns" | -70 | the value - - """ -71 | -72 + """ -73 + -74 | +71 + +72 ~ """ | D413 [*] Missing blank line after last section ("Raises") @@ -85,8 +72,5 @@ D413 [*] Missing blank line after last section ("Raises") 79 | """) | help: Add blank line after "Raises" - | -78 | ValueError: An error. -79 + -80 | """) +79 - """) | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D413_sections.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D413_sections.py.snap index 4f65203e47b1e..d68f8b44ce54e 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D413_sections.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D413_sections.py.snap @@ -10,12 +10,9 @@ D413 [*] Missing blank line after last section ("Returns") | ^^^^^^^ help: Add blank line after "Returns" | -66 | - - Returns""" -67 + Returns -68 + -69 + """ -70 | +67 ~ Returns +68 + +69 ~ """ | D413 [*] Missing blank line after last section ("Returns") @@ -29,10 +26,7 @@ D413 [*] Missing blank line after last section ("Returns") 124 | A value of some sort. | help: Add blank line after "Returns" - | -124 | A value of some sort. -125 + -126 | """ +125 - """ | D413 [*] Missing blank line after last section ("Returns") @@ -46,10 +40,7 @@ D413 [*] Missing blank line after last section ("Returns") 174 | """ | help: Add blank line after "Returns" - | -173 | ------- -174 + -175 | """ +174 - """ | D413 [*] Missing blank line after last section ("Parameters") @@ -63,10 +54,7 @@ D413 [*] Missing blank line after last section ("Parameters") 523 | """ | help: Add blank line after "Parameters" - | -522 | ========== -523 + -524 | """ +523 - """ | D413 [*] Missing blank line after last section ("Parameters") @@ -80,10 +68,7 @@ D413 [*] Missing blank line after last section ("Parameters") 531 | """ | help: Add blank line after "Parameters" - | -530 | =========== -531 + -532 | """ +531 - """ | D413 [*] Missing blank line after last section ("Args") @@ -96,10 +81,7 @@ D413 [*] Missing blank line after last section ("Args") 551 | Here's a note. | help: Add blank line after "Args" - | -553 | returns: -554 + -555 | """ +554 - """ | D413 [*] Missing blank line after last section ("Returns") @@ -112,10 +94,7 @@ D413 [*] Missing blank line after last section ("Returns") 564 | """ | help: Add blank line after "Returns" - | -563 | Returns: -564 + -565 | """ +564 - """ | D413 [*] Missing blank line after last section ("returns") @@ -129,10 +108,7 @@ D413 [*] Missing blank line after last section ("returns") 575 | """ | help: Add blank line after "returns" - | -574 | Here's another note. -575 + -576 | """ +575 - """ | D413 [*] Missing blank line after last section ("Parameters") @@ -146,8 +122,5 @@ D413 [*] Missing blank line after last section ("Parameters") 603 | parameters: | help: Add blank line after "Parameters" - | -606 | Some value -607 + -608 | """ +607 - """ | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D413_sphinx_directive.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D413_sphinx_directive.py.snap index 7c9ba10d96f03..ace848e4b5928 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D413_sphinx_directive.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D413_sphinx_directive.py.snap @@ -12,10 +12,7 @@ D413 [*] Missing blank line after last section ("Returns") 26 | """ | help: Add blank line after "Returns" - | -25 | None -26 + -27 | """ +26 - """ | D413 [*] Missing blank line after last section ("Returns") @@ -29,10 +26,7 @@ D413 [*] Missing blank line after last section ("Returns") 52 | """ | help: Add blank line after "Returns" - | -51 | None -52 + -53 | """ +52 - """ | D413 [*] Missing blank line after last section ("Notes") @@ -46,8 +40,5 @@ D413 [*] Missing blank line after last section ("Notes") 64 | """ | help: Add blank line after "Notes" - | -63 | This IS a real section and should still be detected. -64 + -65 | """ +64 - """ | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D415_D.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D415_D.py.snap index 1b2f8c941d9b9..cb03248a336b8 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D415_D.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D415_D.py.snap @@ -10,11 +10,8 @@ D415 [*] First line should end with a period, question mark, or exclamation poin | ^^^^^^^^^^^^^ help: Add closing punctuation | -354 | def lwnlkjl(): - - """Summary""" -355 + """Summary.""" -356 | - | +355 | """Summary.""" + | + note: This is an unsafe fix and may change runtime behavior D415 [*] First line should end with a period, question mark, or exclamation point @@ -26,11 +23,8 @@ D415 [*] First line should end with a period, question mark, or exclamation poin | ^^^^^^^^^^^^^^^ help: Add closing punctuation | -405 | " or exclamation point (not 'r')") - - def oneliner_withdoc(): """One liner""" -406 + def oneliner_withdoc(): """One liner.""" -407 | - | +406 | def oneliner_withdoc(): """One liner.""" + | + note: This is an unsafe fix and may change runtime behavior D415 [*] First line should end with a period, question mark, or exclamation point @@ -44,11 +38,8 @@ D415 [*] First line should end with a period, question mark, or exclamation poin | help: Add closing punctuation | -409 | def ignored_decorator(func): # noqa: D400,D401,D415 - - """Runs something""" -410 + """Runs something.""" -411 | func() - | +410 | """Runs something.""" + | + note: This is an unsafe fix and may change runtime behavior D415 [*] First line should end with a period, question mark, or exclamation point @@ -62,11 +53,8 @@ D415 [*] First line should end with a period, question mark, or exclamation poin | help: Add closing punctuation | -415 | def decorator_for_test(func): # noqa: D400,D401,D415 - - """Runs something""" -416 + """Runs something.""" -417 | func() - | +416 | """Runs something.""" + | + note: This is an unsafe fix and may change runtime behavior D415 [*] First line should end with a period, question mark, or exclamation point @@ -77,11 +65,8 @@ D415 [*] First line should end with a period, question mark, or exclamation poin | ^^^^^^^^^^^^^^^ help: Add closing punctuation | -421 | @ignored_decorator - - def oneliner_ignored_decorator(): """One liner""" -422 + def oneliner_ignored_decorator(): """One liner.""" -423 | - | +422 | def oneliner_ignored_decorator(): """One liner.""" + | + note: This is an unsafe fix and may change runtime behavior D415 [*] First line should end with a period, question mark, or exclamation point @@ -93,11 +78,8 @@ D415 [*] First line should end with a period, question mark, or exclamation poin | ^^^^^^^^^^^^^^^ help: Add closing punctuation | -428 | " or exclamation point (not 'r')") - - def oneliner_with_decorator_expecting_errors(): """One liner""" -429 + def oneliner_with_decorator_expecting_errors(): """One liner.""" -430 | - | +429 | def oneliner_with_decorator_expecting_errors(): """One liner.""" + | + note: This is an unsafe fix and may change runtime behavior D415 [*] First line should end with a period, question mark, or exclamation point @@ -111,11 +93,8 @@ D415 [*] First line should end with a period, question mark, or exclamation poin | help: Add closing punctuation | -469 | def docstring_bad(): - - """Runs something""" -470 + """Runs something.""" -471 | pass - | +470 | """Runs something.""" + | + note: This is an unsafe fix and may change runtime behavior D415 [*] First line should end with a period, question mark, or exclamation point @@ -128,11 +107,8 @@ D415 [*] First line should end with a period, question mark, or exclamation poin | help: Add closing punctuation | -474 | def docstring_bad_ignore_all(): # noqa - - """Runs something""" -475 + """Runs something.""" -476 | pass - | +475 | """Runs something.""" + | + note: This is an unsafe fix and may change runtime behavior D415 [*] First line should end with a period, question mark, or exclamation point @@ -145,11 +121,8 @@ D415 [*] First line should end with a period, question mark, or exclamation poin | help: Add closing punctuation | -479 | def docstring_bad_ignore_one(): # noqa: D400,D401,D415 - - """Runs something""" -480 + """Runs something.""" -481 | pass - | +480 | """Runs something.""" + | + note: This is an unsafe fix and may change runtime behavior D415 [*] First line should end with a period, question mark, or exclamation point @@ -163,11 +136,8 @@ D415 [*] First line should end with a period, question mark, or exclamation poin | help: Add closing punctuation | -486 | def docstring_ignore_some_violations_but_catch_D401(): # noqa: E501,D400,D415 - - """Runs something""" -487 + """Runs something.""" -488 | pass - | +487 | """Runs something.""" + | + note: This is an unsafe fix and may change runtime behavior D415 [*] First line should end with a period, question mark, or exclamation point @@ -179,11 +149,8 @@ D415 [*] First line should end with a period, question mark, or exclamation poin | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add closing punctuation | -519 | def bad_google_string(): # noqa: D400 - - """Test a valid something""" -520 + """Test a valid something.""" -521 | - | +520 | """Test a valid something.""" + | + note: This is an unsafe fix and may change runtime behavior D415 [*] First line should end with a period, question mark, or exclamation point @@ -195,11 +162,8 @@ D415 [*] First line should end with a period, question mark, or exclamation poin | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add closing punctuation | -580 | def endswith_quote(): - - """Whitespace at the end, but also a quote" """ -581 + """Whitespace at the end, but also a quote". """ -582 | - | +581 | """Whitespace at the end, but also a quote". """ + | + note: This is an unsafe fix and may change runtime behavior D415 [*] First line should end with a period, question mark, or exclamation point @@ -213,11 +177,8 @@ D415 [*] First line should end with a period, question mark, or exclamation poin | |_______^ help: Add closing punctuation | -614 | def one_liner(): - - """Wrong." -615 + """Wrong.". -616 | - | +615 | """Wrong.". + | + note: This is an unsafe fix and may change runtime behavior D415 [*] First line should end with a period, question mark, or exclamation point @@ -230,11 +191,8 @@ D415 [*] First line should end with a period, question mark, or exclamation poin | help: Add closing punctuation | -638 | - - class SameLine: """This is a docstring on the same line""" -639 + class SameLine: """This is a docstring on the same line.""" -640 | - | +639 | class SameLine: """This is a docstring on the same line.""" + | + note: This is an unsafe fix and may change runtime behavior D415 [*] First line should end with a period, question mark, or exclamation point @@ -246,11 +204,8 @@ D415 [*] First line should end with a period, question mark, or exclamation poin | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add closing punctuation | -640 | - - def same_line(): """This is a docstring on the same line""" -641 + def same_line(): """This is a docstring on the same line.""" -642 | - | +641 | def same_line(): """This is a docstring on the same line.""" + | + note: This is an unsafe fix and may change runtime behavior D415 [*] First line should end with a period, question mark, or exclamation point @@ -262,9 +217,6 @@ D415 [*] First line should end with a period, question mark, or exclamation poin | |_________________________________________________________^ help: Add closing punctuation | -664 | "We enforce a newline after the closing quote for a multi-line docstring \ - - but continuations shouldn't be considered multi-line" -665 + but continuations shouldn't be considered multi-line." -666 | - | +665 | but continuations shouldn't be considered multi-line." + | + note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D415_D400_415.py.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D415_D400_415.py.snap index 8f623426b87d8..5cf7e49221f6f 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D415_D400_415.py.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__D415_D400_415.py.snap @@ -31,9 +31,6 @@ D415 [*] First line should end with a period, question mark, or exclamation poin | help: Add closing punctuation | -18 | def f(): - - """Here's a line ending with a whitespace """ -19 + """Here's a line ending with a whitespace. """ -20 | ... - | +19 | """Here's a line ending with a whitespace. """ + | + note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__bom.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__bom.snap index 828ef679e34aa..807e034e11093 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__bom.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__bom.snap @@ -8,6 +8,6 @@ D300 [*] Use triple double quotes `"""` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Convert to triple double quotes | - - ''' SAM macro definitions ''' +1 - ''' SAM macro definitions ''' 1 + """ SAM macro definitions """ | diff --git a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__d209_d400.snap b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__d209_d400.snap index 59e45c5e0bd67..025b7002bd1c9 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__d209_d400.snap +++ b/crates/ruff_linter/src/rules/pydocstyle/snapshots/ruff_linter__rules__pydocstyle__tests__d209_d400.snap @@ -10,10 +10,8 @@ D209 [*] Multi-line docstring closing quotes should be on a separate line | |________________________________________________________________________^ help: Move closing quotes to new line | -2 | """lorem ipsum dolor sit amet consectetur adipiscing elit - - sed do eiusmod tempor incididunt ut labore et dolore magna aliqua""" -3 + sed do eiusmod tempor incididunt ut labore et dolore magna aliqua -4 + """ +3 ~ sed do eiusmod tempor incididunt ut labore et dolore magna aliqua +4 ~ """ | D400 [*] First line should end with a period @@ -25,8 +23,6 @@ D400 [*] First line should end with a period | |________________________________________________________________________^ help: Add period | -2 | """lorem ipsum dolor sit amet consectetur adipiscing elit - - sed do eiusmod tempor incididunt ut labore et dolore magna aliqua""" -3 + sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" - | +3 | sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" + | + note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_0.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_0.py.snap index d000f803e9ba6..bcaf235d12842 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_0.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_0.py.snap @@ -12,10 +12,8 @@ F401 [*] `functools` imported but unused | help: Remove unused import: `functools` | -1 | from __future__ import all_feature_names - - import functools, os +2 - import functools, os 2 + import os -3 | from datetime import datetime | F401 [*] `collections.OrderedDict` imported but unused @@ -30,9 +28,10 @@ F401 [*] `collections.OrderedDict` imported but unused | help: Remove unused import: `collections.OrderedDict` | -5 | Counter, - - OrderedDict, -6 | namedtuple, +4 + from collections import ( +5 + Counter, +6 + namedtuple, +7 + ) | F401 [*] `logging.handlers` imported but unused @@ -47,9 +46,7 @@ F401 [*] `logging.handlers` imported but unused | help: Remove unused import: `logging.handlers` | -11 | import logging.config - - import logging.handlers -12 | from typing import ( +12 - import logging.handlers | F401 [*] `shelve` imported but unused @@ -62,9 +59,7 @@ F401 [*] `shelve` imported but unused | help: Remove unused import: `shelve` | -31 | if TYPE_CHECKING: - - import shelve -32 | import importlib +32 - import shelve | F401 [*] `importlib` imported but unused @@ -79,9 +74,7 @@ F401 [*] `importlib` imported but unused | help: Remove unused import: `importlib` | -32 | import shelve - - import importlib -33 | +33 - import importlib | F401 [*] `pathlib` imported but unused @@ -96,9 +89,7 @@ F401 [*] `pathlib` imported but unused | help: Remove unused import: `pathlib` | -36 | """Hello, world!""" - - import pathlib -37 | +37 - import pathlib | F401 [*] `pickle` imported but unused @@ -109,10 +100,8 @@ F401 [*] `pickle` imported but unused | ^^^^^^ help: Remove unused import: `pickle` | -51 | def b(self) -> None: - - import pickle +52 - import pickle 52 + pass -53 | | F401 [*] `x` imported but unused @@ -126,9 +115,7 @@ F401 [*] `x` imported but unused | help: Remove unused import: `x` | -92 | case 0,: - - import x -93 | import y +93 - import x | F401 [*] `y` imported but unused @@ -140,9 +127,7 @@ F401 [*] `y` imported but unused | ^ help: Remove unused import: `y` | -93 | import x - - import y -94 | +94 - import y | F401 [*] `foo.bar.baz` imported but unused @@ -156,11 +141,9 @@ F401 [*] `foo.bar.baz` imported but unused 101 | print(bop.baz.read_csv("test.csv")) | help: Remove unused import: `foo.bar.baz` - | -98 | import foo.bar as bop - - import foo.bar.baz -99 | - | + | + 99 - import foo.bar.baz + | F401 [*] `a1` imported but unused --> F401_0.py:105:12 @@ -174,9 +157,7 @@ F401 [*] `a1` imported but unused | help: Remove unused import: `a1` | -104 | if TYPE_CHECKING: - - import a1 -105 | +105 - import a1 | F401 [*] `a2` imported but unused @@ -188,9 +169,7 @@ F401 [*] `a2` imported but unused | ^^ help: Remove unused import: `a2` | -106 | - - import a2 -107 | +107 - import a2 | F401 [*] `b1` imported but unused @@ -205,9 +184,7 @@ F401 [*] `b1` imported but unused | help: Remove unused import: `b1` | -111 | case 0,: - - import b1 -112 | +112 - import b1 | F401 [*] `b2` imported but unused @@ -219,9 +196,7 @@ F401 [*] `b2` imported but unused | ^^ help: Remove unused import: `b2` | -113 | - - import b2 -114 | +114 - import b2 | F401 [*] `datameta_client_lib.model_helpers.noqa` imported but unused @@ -232,7 +207,6 @@ F401 [*] `datameta_client_lib.model_helpers.noqa` imported but unused | ^^^^ help: Remove unused import: `datameta_client_lib.model_helpers.noqa` | -120 | - - from datameta_client_lib.model_helpers import ( - - noqa ) +121 - from datameta_client_lib.model_helpers import ( +122 - noqa ) | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_11.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_11.py.snap index 7bedc926b31bc..4d568aae20639 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_11.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_11.py.snap @@ -9,8 +9,6 @@ F401 [*] `pathlib.PurePath` imported but unused | ^^^^^^^^ help: Remove unused import: `pathlib.PurePath` | -3 | from typing import List - - from pathlib import Path, PurePath +4 - from pathlib import Path, PurePath 4 + from pathlib import Path -5 | | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_15.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_15.py.snap index cba2cf8fea290..06c01644f9a9b 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_15.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_15.py.snap @@ -9,8 +9,6 @@ F401 [*] `pathlib.Path` imported but unused | ^^^^ help: Remove unused import: `pathlib.Path` | -4 | if TYPE_CHECKING: - - from pathlib import Path +5 - from pathlib import Path 5 + pass -6 | | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_17.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_17.py.snap index fcececcb987c6..a5785b74b8da2 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_17.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_17.py.snap @@ -12,9 +12,7 @@ F401 [*] `threading.Thread` imported but unused | help: Remove unused import: `threading.Thread` | -11 | def fn(thread: Thread): - - from threading import Thread -12 | +12 - from threading import Thread | F401 [*] `threading.Thread` imported but unused @@ -28,7 +26,5 @@ F401 [*] `threading.Thread` imported but unused | help: Remove unused import: `threading.Thread` | -19 | def fn(thread: Thread): - - from threading import Thread -20 | +20 - from threading import Thread | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_18.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_18.py.snap index b2901bdbc27f0..b917d56d32262 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_18.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_18.py.snap @@ -9,8 +9,6 @@ F401 [*] `__future__` imported but unused | ^^^^^^^^^^ help: Remove unused import: `__future__` | -4 | def f(): - - import __future__ +5 - import __future__ 5 + pass -6 | | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_23.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_23.py.snap index bbd30ac0a121e..3a9ed3611f5b6 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_23.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_23.py.snap @@ -11,7 +11,5 @@ F401 [*] `re.RegexFlag` imported but unused | help: Remove unused import: `re.RegexFlag` | -3 | from pathlib import Path - - from re import RegexFlag -4 | from typing import Annotated +4 - from re import RegexFlag | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_34.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_34.py.snap index 3e680fa65abfc..b574fff511ec1 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_34.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_34.py.snap @@ -13,9 +13,7 @@ F401 [*] `typing.Union` imported but unused | help: Remove unused import: `typing.Union` | -44 | def f(): - - from typing import Union -45 | +45 - from typing import Union | F401 [*] `typing.Union` imported but unused @@ -29,7 +27,5 @@ F401 [*] `typing.Union` imported but unused | help: Remove unused import: `typing.Union` | -57 | def f(): - - from typing import Union -58 | +58 - from typing import Union | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_5.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_5.py.snap index b6483be2edee7..734647aa185be 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_5.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_5.py.snap @@ -12,9 +12,7 @@ F401 [*] `a.b.c` imported but unused | help: Remove unused import: `a.b.c` | -1 | """Test: removal of multi-segment and aliases imports.""" - - from a.b import c -2 | from d.e import f as g +2 - from a.b import c | F401 [*] `d.e.f` imported but unused @@ -29,9 +27,7 @@ F401 [*] `d.e.f` imported but unused | help: Remove unused import: `d.e.f` | -2 | from a.b import c - - from d.e import f as g -3 | import h.i +3 - from d.e import f as g | F401 [*] `h.i` imported but unused @@ -45,9 +41,7 @@ F401 [*] `h.i` imported but unused | help: Remove unused import: `h.i` | -3 | from d.e import f as g - - import h.i -4 | import j.k as l +4 - import h.i | F401 [*] `j.k` imported but unused @@ -59,6 +53,5 @@ F401 [*] `j.k` imported but unused | ^ help: Remove unused import: `j.k` | -4 | import h.i - - import j.k as l +5 - import j.k as l | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_6.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_6.py.snap index cf985888c0925..9ff9d73914b74 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_6.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_6.py.snap @@ -12,9 +12,7 @@ F401 [*] `.background.BackgroundTasks` imported but unused | help: Remove unused import: `.background.BackgroundTasks` | -6 | # F401 `background.BackgroundTasks` imported but unused - - from .background import BackgroundTasks -7 | +7 - from .background import BackgroundTasks | F401 [*] `.datastructures.UploadFile` imported but unused @@ -28,9 +26,7 @@ F401 [*] `.datastructures.UploadFile` imported but unused | help: Remove unused import: `.datastructures.UploadFile` | -9 | # F401 `datastructures.UploadFile` imported but unused - - from .datastructures import UploadFile as FileUpload -10 | +10 - from .datastructures import UploadFile as FileUpload | F401 [*] `background` imported but unused @@ -44,9 +40,7 @@ F401 [*] `background` imported but unused | help: Remove unused import: `background` | -15 | # F401 `background` imported but unused - - import background -16 | +16 - import background | F401 [*] `datastructures` imported but unused @@ -57,6 +51,5 @@ F401 [*] `datastructures` imported but unused | ^^^^^^^^^^ help: Remove unused import: `datastructures` | -18 | # F401 `datastructures` imported but unused - - import datastructures as structures +19 - import datastructures as structures | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_7.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_7.py.snap index 94f60b328ee38..01c78504827c4 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_7.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_7.py.snap @@ -12,11 +12,9 @@ F401 [*] `typing.Union` imported but unused | help: Remove unused import: `typing.Union` | -29 | Mapping, # noqa: F401 - - Union, - - ) +28 + from typing import ( +29 + Mapping, # noqa: F401 30 + ) -31 | | F401 [*] `typing.Awaitable` imported but unused @@ -27,8 +25,7 @@ F401 [*] `typing.Awaitable` imported but unused | ^^^^^^^^^ help: Remove unused import | -65 | # This should mark F501 as unused. - - from typing import Awaitable, AwaitableGenerator # noqa: F501 +66 - from typing import Awaitable, AwaitableGenerator # noqa: F501 | F401 [*] `typing.AwaitableGenerator` imported but unused @@ -39,6 +36,5 @@ F401 [*] `typing.AwaitableGenerator` imported but unused | ^^^^^^^^^^^^^^^^^^ help: Remove unused import | -65 | # This should mark F501 as unused. - - from typing import Awaitable, AwaitableGenerator # noqa: F501 +66 - from typing import Awaitable, AwaitableGenerator # noqa: F501 | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_9.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_9.py.snap index 9fcfd335725c4..99bddcbadc0a8 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_9.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_F401_9.py.snap @@ -9,7 +9,6 @@ F401 [*] `foo.baz` imported but unused | ^^^ help: Remove unused import: `foo.baz` | -3 | __all__ = ("bar",) - - from foo import bar, baz +4 - from foo import bar, baz 4 + from foo import bar | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_24____init__.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_24____init__.py.snap index b22638490d318..2151ba652f70f 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_24____init__.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_24____init__.py.snap @@ -8,9 +8,7 @@ F401 [*] `sys` imported but unused | ^^^ help: Remove unused import: `sys` | -18 | - - import sys # F401: remove unused -19 | +19 - import sys # F401: remove unused | note: This is an unsafe fix and may change runtime behavior @@ -21,9 +19,7 @@ F401 [*] `.unused` imported but unused; consider removing, adding to `__all__`, | ^^^^^^ help: Remove unused import: `.unused` | -32 | - - from . import unused # F401: change to redundant alias -33 | +33 - from . import unused # F401: change to redundant alias | note: This is an unsafe fix and may change runtime behavior @@ -34,7 +30,6 @@ F401 [*] `.renamed` imported but unused; consider removing, adding to `__all__`, | ^^^^ help: Remove unused import: `.renamed` | -35 | - - from . import renamed as bees # F401: no fix +36 - from . import renamed as bees # F401: no fix | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_25__all_nonempty____init__.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_25__all_nonempty____init__.py.snap index 7816a422e629b..1c4a6033ec0b9 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_25__all_nonempty____init__.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_25__all_nonempty____init__.py.snap @@ -8,9 +8,7 @@ F401 [*] `sys` imported but unused | ^^^ help: Remove unused import: `sys` | -18 | - - import sys # F401: remove unused -19 | +19 - import sys # F401: remove unused | note: This is an unsafe fix and may change runtime behavior @@ -21,9 +19,7 @@ F401 [*] `.unused` imported but unused; consider removing, adding to `__all__`, | ^^^^^^ help: Remove unused import: `.unused` | -35 | - - from . import unused # F401: add to __all__ -36 | +36 - from . import unused # F401: add to __all__ | note: This is an unsafe fix and may change runtime behavior @@ -34,8 +30,6 @@ F401 [*] `.renamed` imported but unused; consider removing, adding to `__all__`, | ^^^^ help: Remove unused import: `.renamed` | -38 | - - from . import renamed as bees # F401: add to __all__ -39 | +39 - from . import renamed as bees # F401: add to __all__ | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_26__all_empty____init__.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_26__all_empty____init__.py.snap index 21fc5fb21f461..04bbf29823ffd 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_26__all_empty____init__.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_26__all_empty____init__.py.snap @@ -8,9 +8,7 @@ F401 [*] `.unused` imported but unused; consider removing, adding to `__all__`, | ^^^^^^ help: Remove unused import: `.unused` | -4 | - - from . import unused # F401: add to __all__ -5 | +5 - from . import unused # F401: add to __all__ | note: This is an unsafe fix and may change runtime behavior @@ -21,8 +19,6 @@ F401 [*] `.renamed` imported but unused; consider removing, adding to `__all__`, | ^^^^ help: Remove unused import: `.renamed` | -7 | - - from . import renamed as bees # F401: add to __all__ -8 | +8 - from . import renamed as bees # F401: add to __all__ | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_27__all_mistyped____init__.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_27__all_mistyped____init__.py.snap index 8d7f2d9e1454c..61c1a52e68a8c 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_27__all_mistyped____init__.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_27__all_mistyped____init__.py.snap @@ -8,9 +8,7 @@ F401 [*] `.unused` imported but unused; consider removing, adding to `__all__`, | ^^^^^^ help: Remove unused import: `.unused` | -4 | - - from . import unused # F401: recommend add to all w/o fix -5 | +5 - from . import unused # F401: recommend add to all w/o fix | note: This is an unsafe fix and may change runtime behavior @@ -21,8 +19,6 @@ F401 [*] `.renamed` imported but unused; consider removing, adding to `__all__`, | ^^^^ help: Remove unused import: `.renamed` | -7 | - - from . import renamed as bees # F401: recommend add to all w/o fix -8 | +8 - from . import renamed as bees # F401: recommend add to all w/o fix | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_28__all_multiple____init__.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_28__all_multiple____init__.py.snap index 16ba6bec64de1..a9dea7b217b29 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_28__all_multiple____init__.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_28__all_multiple____init__.py.snap @@ -8,9 +8,7 @@ F401 [*] `.unused` imported but unused; consider removing, adding to `__all__`, | ^^^^^^ help: Remove unused import | -4 | - - from . import unused, renamed as bees # F401: add to __all__ -5 | +5 - from . import unused, renamed as bees # F401: add to __all__ | note: This is an unsafe fix and may change runtime behavior @@ -21,8 +19,6 @@ F401 [*] `.renamed` imported but unused; consider removing, adding to `__all__`, | ^^^^ help: Remove unused import | -4 | - - from . import unused, renamed as bees # F401: add to __all__ -5 | +5 - from . import unused, renamed as bees # F401: add to __all__ | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_29__all_conditional____init__.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_29__all_conditional____init__.py.snap index a80c3b7b91b6a..b4aa464584a97 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_29__all_conditional____init__.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_29__all_conditional____init__.py.snap @@ -13,10 +13,8 @@ F401 [*] `.unused` imported but unused; consider removing, adding to `__all__`, | help: Remove unused import | -7 | - - from . import unused, exported, renamed as bees +8 - from . import unused, exported, renamed as bees 8 + from . import exported -9 | | note: This is an unsafe fix and may change runtime behavior @@ -32,9 +30,7 @@ F401 [*] `.renamed` imported but unused; consider removing, adding to `__all__`, | help: Remove unused import | -7 | - - from . import unused, exported, renamed as bees +8 - from . import unused, exported, renamed as bees 8 + from . import exported -9 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_30.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_30.py.snap index 4890e7032d02a..de120e7eb579d 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_30.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F401_deprecated_option_F401_30.py.snap @@ -10,6 +10,5 @@ F401 [*] `.main.MaμToMan` imported but unused | ^^^^^^^^ help: Remove unused import: `.main.MaμToMan` | -5 | - - from .main import MaµToMan +6 - from .main import MaµToMan | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F504_F504.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F504_F504.py.snap index 235818bb478dc..1dfc8487db91a 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F504_F504.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F504_F504.py.snap @@ -13,10 +13,8 @@ F504 [*] `%`-format string has unused named argument(s): b | help: Remove extra named arguments: b | -2 | a = "wrong" - - "%(a)s %(c)s" % {a: "?", "b": "!"} # F504 ("b" not used) +3 - "%(a)s %(c)s" % {a: "?", "b": "!"} # F504 ("b" not used) 3 + "%(a)s %(c)s" % {a: "?", } # F504 ("b" not used) -4 | | F504 [*] `%`-format string has unused named argument(s): b @@ -30,10 +28,8 @@ F504 [*] `%`-format string has unused named argument(s): b | help: Remove extra named arguments: b | -7 | - - "%(a)s" % {"a": 1, r"b": "!"} # F504 ("b" not used) +8 - "%(a)s" % {"a": 1, r"b": "!"} # F504 ("b" not used) 8 + "%(a)s" % {"a": 1, } # F504 ("b" not used) -9 | "%(a)s" % {'a': 1, u"b": "!"} # F504 ("b" not used) | F504 [*] `%`-format string has unused named argument(s): b @@ -46,12 +42,10 @@ F504 [*] `%`-format string has unused named argument(s): b 11 | '' % {'a''b' : ''} # F504 ("ab" not used) | help: Remove extra named arguments: b - | -8 | "%(a)s" % {"a": 1, r"b": "!"} # F504 ("b" not used) - - "%(a)s" % {'a': 1, u"b": "!"} # F504 ("b" not used) -9 + "%(a)s" % {'a': 1, } # F504 ("b" not used) -10 | - | + | +9 - "%(a)s" % {'a': 1, u"b": "!"} # F504 ("b" not used) +9 + "%(a)s" % {'a': 1, } # F504 ("b" not used) + | F504 [*] `%`-format string has unused named argument(s): ab --> F504.py:11:1 @@ -65,10 +59,8 @@ F504 [*] `%`-format string has unused named argument(s): ab | help: Remove extra named arguments: ab | -10 | - - '' % {'a''b' : ''} # F504 ("ab" not used) +11 - '' % {'a''b' : ''} # F504 ("ab" not used) 11 + '' % {} # F504 ("ab" not used) -12 | | F504 [*] `%`-format string has unused named argument(s): test1, test2 @@ -85,10 +77,9 @@ F504 [*] `%`-format string has unused named argument(s): test1, test2 | help: Remove extra named arguments: test1, test2 | -14 | "" % { - - 'test1': '', - 'test2': '', +14 ~ "" % { 15 + -16 | } +16 + } | F504 [*] `%`-format string has unused named argument(s): greeting @@ -99,8 +90,7 @@ F504 [*] `%`-format string has unused named argument(s): greeting | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove extra named arguments: greeting | -19 | # https://github.com/astral-sh/ruff/issues/18806 - - "Hello, %(name)s" % {"greeting": print(1), "name": "World"} +20 - "Hello, %(name)s" % {"greeting": print(1), "name": "World"} 20 + "Hello, %(name)s" % {"name": "World"} | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F504_F50x.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F504_F50x.py.snap index e63361158852a..a15cd56a7732d 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F504_F50x.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F504_F50x.py.snap @@ -13,8 +13,6 @@ F504 [*] `%`-format string has unused named argument(s): baz | help: Remove extra named arguments: baz | -7 | '%(bar)s' % {} # F505 - - '%(bar)s' % {'bar': 1, 'baz': 2} # F504 +8 - '%(bar)s' % {'bar': 1, 'baz': 2} # F504 8 + '%(bar)s' % {'bar': 1, } # F504 -9 | '%(bar)s' % (1, 2, 3) # F502 | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F522_F522.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F522_F522.py.snap index a6145805a113e..29baf69fc85a4 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F522_F522.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F522_F522.py.snap @@ -11,9 +11,8 @@ F522 [*] `.format` call has unused named argument(s): bar | help: Remove extra named arguments: bar | - - "{}".format(1, bar=2) # F522 +1 - "{}".format(1, bar=2) # F522 1 + "{}".format(1, ) # F522 -2 | "{bar}{}".format(1, bar=2, spam=3) # F522 | F522 [*] `.format` call has unused named argument(s): spam @@ -27,10 +26,8 @@ F522 [*] `.format` call has unused named argument(s): spam | help: Remove extra named arguments: spam | -1 | "{}".format(1, bar=2) # F522 - - "{bar}{}".format(1, bar=2, spam=3) # F522 +2 - "{bar}{}".format(1, bar=2, spam=3) # F522 2 + "{bar}{}".format(1, bar=2, ) # F522 -3 | "{bar:{spam}}".format(bar=2, spam=3) # No issues | F522 [*] `.format` call has unused named argument(s): eggs, ham @@ -45,10 +42,8 @@ F522 [*] `.format` call has unused named argument(s): eggs, ham | help: Remove extra named arguments: eggs, ham | -3 | "{bar:{spam}}".format(bar=2, spam=3) # No issues - - "{bar:{spam}}".format(bar=2, spam=3, eggs=4, ham=5) # F522 +4 - "{bar:{spam}}".format(bar=2, spam=3, eggs=4, ham=5) # F522 4 + "{bar:{spam}}".format(bar=2, spam=3, ) # F522 -5 | ('' | F522 [*] `.format` call has unused named argument(s): x @@ -65,10 +60,8 @@ F522 [*] `.format` call has unused named argument(s): x | help: Remove extra named arguments: x | -5 | ('' - - .format(x=2)) # F522 -6 + .format()) # F522 -7 | +5 ~ ('' +6 ~ .format()) # F522 | F522 [*] `.format` call has unused named argument(s): greeting @@ -83,10 +76,8 @@ F522 [*] `.format` call has unused named argument(s): greeting | help: Remove extra named arguments: greeting | -9 | # The fix here is unsafe because the unused argument has side effect - - "Hello, {name}".format(greeting=print(1), name="World") +10 - "Hello, {name}".format(greeting=print(1), name="World") 10 + "Hello, {name}".format(name="World") -11 | | note: This is an unsafe fix and may change runtime behavior @@ -99,7 +90,6 @@ F522 [*] `.format` call has unused named argument(s): greeting | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove extra named arguments: greeting | -13 | # even though the used argument has a side effect - - "Hello, {name}".format(greeting="Pikachu", name=print(1)) +14 - "Hello, {name}".format(greeting="Pikachu", name=print(1)) 14 + "Hello, {name}".format(name=print(1)) | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F523_F523.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F523_F523.py.snap index 2c19fe4263474..4880dc120a283 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F523_F523.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F523_F523.py.snap @@ -12,10 +12,8 @@ F523 [*] `.format` call has unused arguments at position(s): 1 | help: Remove extra positional arguments at position(s): 1 | -1 | # With indexes - - "{0}".format(1, 2) # F523 +2 - "{0}".format(1, 2) # F523 2 + "{0}".format(1, ) # F523 -3 | "{1}".format(1, 2, 3) # F523 | F523 `.format` call has unused arguments at position(s): 0, 2 @@ -42,10 +40,8 @@ F523 [*] `.format` call has unused arguments at position(s): 2 | help: Remove extra positional arguments at position(s): 2 | -4 | "{1:{0}}".format(1, 2) # No issues - - "{1:{0}}".format(1, 2, 3) # F523 +5 - "{1:{0}}".format(1, 2, 3) # F523 5 + "{1:{0}}".format(1, 2, ) # F523 -6 | "{0}{2}".format(1, 2) # F523, # F524 | F523 [*] `.format` call has unused arguments at position(s): 1 @@ -59,10 +55,8 @@ F523 [*] `.format` call has unused arguments at position(s): 1 | help: Remove extra positional arguments at position(s): 1 | -5 | "{1:{0}}".format(1, 2, 3) # F523 - - "{0}{2}".format(1, 2) # F523, # F524 +6 - "{0}{2}".format(1, 2) # F523, # F524 6 + "{0}{2}".format(1, ) # F523, # F524 -7 | "{1.arg[1]!r:0{2['arg']}{1}}".format(1, 2, 3, 4) # F523 | F523 `.format` call has unused arguments at position(s): 0, 3 @@ -88,10 +82,8 @@ F523 [*] `.format` call has unused arguments at position(s): 1 | help: Remove extra positional arguments at position(s): 1 | -9 | # With no indexes - - "{}".format(1, 2) # F523 +10 - "{}".format(1, 2) # F523 10 + "{}".format(1, ) # F523 -11 | "{}".format(1, 2, 3) # F523 | F523 [*] `.format` call has unused arguments at position(s): 1, 2 @@ -106,10 +98,8 @@ F523 [*] `.format` call has unused arguments at position(s): 1, 2 | help: Remove extra positional arguments at position(s): 1, 2 | -10 | "{}".format(1, 2) # F523 - - "{}".format(1, 2, 3) # F523 +11 - "{}".format(1, 2, 3) # F523 11 + "{}".format(1, ) # F523 -12 | "{:{}}".format(1, 2) # No issues | F523 [*] `.format` call has unused arguments at position(s): 2 @@ -124,10 +114,8 @@ F523 [*] `.format` call has unused arguments at position(s): 2 | help: Remove extra positional arguments at position(s): 2 | -12 | "{:{}}".format(1, 2) # No issues - - "{:{}}".format(1, 2, 3) # F523 +13 - "{:{}}".format(1, 2, 3) # F523 13 + "{:{}}".format(1, 2, ) # F523 -14 | | F523 `.format` call has unused arguments at position(s): 2 @@ -153,10 +141,8 @@ F523 [*] `.format` call has unused arguments at position(s): 1, 2 | help: Remove extra positional arguments at position(s): 1, 2 | -21 | # With nested quotes - - "''1{0}".format(1, 2, 3) # F523 +22 - "''1{0}".format(1, 2, 3) # F523 22 + "''1{0}".format(1, ) # F523 -23 | "\"\"{1}{0}".format(1, 2, 3) # F523 | F523 [*] `.format` call has unused arguments at position(s): 2 @@ -170,10 +156,8 @@ F523 [*] `.format` call has unused arguments at position(s): 2 | help: Remove extra positional arguments at position(s): 2 | -22 | "''1{0}".format(1, 2, 3) # F523 - - "\"\"{1}{0}".format(1, 2, 3) # F523 +23 - "\"\"{1}{0}".format(1, 2, 3) # F523 23 + "\"\"{1}{0}".format(1, 2, ) # F523 -24 | '""{1}{0}'.format(1, 2, 3) # F523 | F523 [*] `.format` call has unused arguments at position(s): 2 @@ -188,10 +172,8 @@ F523 [*] `.format` call has unused arguments at position(s): 2 | help: Remove extra positional arguments at position(s): 2 | -23 | "\"\"{1}{0}".format(1, 2, 3) # F523 - - '""{1}{0}'.format(1, 2, 3) # F523 +24 - '""{1}{0}'.format(1, 2, 3) # F523 24 + '""{1}{0}'.format(1, 2, ) # F523 -25 | | F523 `.format` call has unused arguments at position(s): 0 @@ -241,11 +223,9 @@ F523 [*] `.format` call has unused arguments at position(s): 0 | help: Remove extra positional arguments at position(s): 0 | -31 | # Multiline - - ('' - - .format(2)) +32 - ('' +33 - .format(2)) 32 + ('') -33 | | F523 [*] `.format` call has unused arguments at position(s): 0 @@ -258,10 +238,8 @@ F523 [*] `.format` call has unused arguments at position(s): 0 | help: Remove extra positional arguments at position(s): 0 | -35 | # Removing the final argument. - - "Hello".format("world") +36 - "Hello".format("world") 36 + "Hello" -37 | "Hello".format("world", key="value") | F523 [*] `.format` call has unused arguments at position(s): 0 @@ -276,10 +254,8 @@ F523 [*] `.format` call has unused arguments at position(s): 0 | help: Remove extra positional arguments at position(s): 0 | -36 | "Hello".format("world") - - "Hello".format("world", key="value") +37 - "Hello".format("world", key="value") 37 + "Hello".format(key="value") -38 | | F523 [*] `.format` call has unused arguments at position(s): 1 @@ -294,10 +270,8 @@ F523 [*] `.format` call has unused arguments at position(s): 1 | help: Remove extra positional arguments at position(s): 1 | -40 | # The fix here is unsafe because the unused argument has side effect - - "Hello, {0}".format("world", print(1)) +41 - "Hello, {0}".format("world", print(1)) 41 + "Hello, {0}".format("world", ) -42 | | note: This is an unsafe fix and may change runtime behavior @@ -310,7 +284,6 @@ F523 [*] `.format` call has unused arguments at position(s): 1 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove extra positional arguments at position(s): 1 | -44 | # even though the used argument has a side effect - - "Hello, {0}".format(print(1), "Pikachu") +45 - "Hello, {0}".format(print(1), "Pikachu") 45 + "Hello, {0}".format(print(1), ) | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F541_F541.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F541_F541.py.snap index 07437d8d121af..fe01cd7b6e6d0 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F541_F541.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F541_F541.py.snap @@ -12,10 +12,8 @@ F541 [*] f-string without any placeholders | help: Remove extraneous `f` prefix | -5 | # Errors - - c = f"def" +6 - c = f"def" 6 + c = "def" -7 | d = f"def" + "ghi" | F541 [*] f-string without any placeholders @@ -30,10 +28,8 @@ F541 [*] f-string without any placeholders | help: Remove extraneous `f` prefix | -6 | c = f"def" - - d = f"def" + "ghi" +7 - d = f"def" + "ghi" 7 + d = "def" + "ghi" -8 | e = ( | F541 [*] f-string without any placeholders @@ -47,12 +43,10 @@ F541 [*] f-string without any placeholders 11 | ) | help: Remove extraneous `f` prefix - | -8 | e = ( - - f"def" + -9 + "def" + -10 | "ghi" - | + | +9 - f"def" + +9 + "def" + + | F541 [*] f-string without any placeholders --> F541.py:13:5 @@ -66,10 +60,8 @@ F541 [*] f-string without any placeholders | help: Remove extraneous `f` prefix | -12 | f = ( - - f"a" +13 - f"a" 13 + "a" -14 | F"b" | F541 [*] f-string without any placeholders @@ -84,10 +76,8 @@ F541 [*] f-string without any placeholders | help: Remove extraneous `f` prefix | -13 | f"a" - - F"b" +14 - F"b" 14 + "b" -15 | "c" | F541 [*] f-string without any placeholders @@ -102,10 +92,8 @@ F541 [*] f-string without any placeholders | help: Remove extraneous `f` prefix | -15 | "c" - - rf"d" +16 - rf"d" 16 + r"d" -17 | fr"e" | F541 [*] f-string without any placeholders @@ -120,10 +108,8 @@ F541 [*] f-string without any placeholders | help: Remove extraneous `f` prefix | -16 | rf"d" - - fr"e" +17 - fr"e" 17 + r"e" -18 | ) | F541 [*] f-string without any placeholders @@ -138,10 +124,8 @@ F541 [*] f-string without any placeholders | help: Remove extraneous `f` prefix | -18 | ) - - g = f"" +19 - g = f"" 19 + g = "" -20 | | F541 [*] f-string without any placeholders @@ -155,10 +139,8 @@ F541 [*] f-string without any placeholders | help: Remove extraneous `f` prefix | -24 | # Error - - h = "x" "y" f"z" +25 - h = "x" "y" f"z" 25 + h = "x" "y" "z" -26 | | F541 [*] f-string without any placeholders @@ -172,10 +154,8 @@ F541 [*] f-string without any placeholders | help: Remove extraneous `f` prefix | -33 | # Errors - - f"{v:{f'0.2f'}}" +34 - f"{v:{f'0.2f'}}" 34 + f"{v:{'0.2f'}}" -35 | f"{f''}" | F541 [*] f-string without any placeholders @@ -190,10 +170,8 @@ F541 [*] f-string without any placeholders | help: Remove extraneous `f` prefix | -34 | f"{v:{f'0.2f'}}" - - f"{f''}" +35 - f"{f''}" 35 + f"{''}" -36 | f"{{test}}" | F541 [*] f-string without any placeholders @@ -208,10 +186,8 @@ F541 [*] f-string without any placeholders | help: Remove extraneous `f` prefix | -35 | f"{f''}" - - f"{{test}}" +36 - f"{{test}}" 36 + "{test}" -37 | f'{{ 40 }}' | F541 [*] f-string without any placeholders @@ -226,10 +202,8 @@ F541 [*] f-string without any placeholders | help: Remove extraneous `f` prefix | -36 | f"{{test}}" - - f'{{ 40 }}' +37 - f'{{ 40 }}' 37 + '{ 40 }' -38 | f"{{a {{x}}" | F541 [*] f-string without any placeholders @@ -244,10 +218,8 @@ F541 [*] f-string without any placeholders | help: Remove extraneous `f` prefix | -37 | f'{{ 40 }}' - - f"{{a {{x}}" +38 - f"{{a {{x}}" 38 + "{a {x}" -39 | f"{{{{x}}}}" | F541 [*] f-string without any placeholders @@ -262,10 +234,8 @@ F541 [*] f-string without any placeholders | help: Remove extraneous `f` prefix | -38 | f"{{a {{x}}" - - f"{{{{x}}}}" +39 - f"{{{{x}}}}" 39 + "{{x}}" -40 | ""f"" | F541 [*] f-string without any placeholders @@ -280,10 +250,8 @@ F541 [*] f-string without any placeholders | help: Remove extraneous `f` prefix | -39 | f"{{{{x}}}}" - - ""f"" +40 - ""f"" 40 + "" "" -41 | ''f"" | F541 [*] f-string without any placeholders @@ -298,10 +266,8 @@ F541 [*] f-string without any placeholders | help: Remove extraneous `f` prefix | -40 | ""f"" - - ''f"" +41 - ''f"" 41 + ''"" -42 | (""f""r"") | F541 [*] f-string without any placeholders @@ -316,10 +282,8 @@ F541 [*] f-string without any placeholders | help: Remove extraneous `f` prefix | -41 | ''f"" - - (""f""r"") +42 - (""f""r"") 42 + ("" ""r"") -43 | f"{v:{f"0.2f"}}" | F541 [*] f-string without any placeholders @@ -333,10 +297,8 @@ F541 [*] f-string without any placeholders | help: Remove extraneous `f` prefix | -42 | (""f""r"") - - f"{v:{f"0.2f"}}" +43 - f"{v:{f"0.2f"}}" 43 + f"{v:{"0.2f"}}" -44 | f"\{{x}}" | F541 [*] f-string without any placeholders @@ -348,7 +310,6 @@ F541 [*] f-string without any placeholders | ^^^^^^^^^ help: Remove extraneous `f` prefix | -43 | f"{v:{f"0.2f"}}" - - f"\{{x}}" +44 - f"\{{x}}" 44 + "\{x}" | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F601_F601.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F601_F601.py.snap index bbf24bc669922..c7d19fe98f4f5 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F601_F601.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F601_F601.py.snap @@ -95,9 +95,7 @@ F601 [*] Dictionary key literal `"a"` repeated | help: Remove repeated key literal `"a"` | -17 | "a": 3, - - "a": 3, -18 | } +17 - "a": 3, | note: This is an unsafe fix and may change runtime behavior @@ -137,9 +135,7 @@ F601 [*] Dictionary key literal `"a"` repeated | help: Remove repeated key literal `"a"` | -24 | "a": 3, - - "a": 3, -25 | "a": 4, +24 - "a": 3, | note: This is an unsafe fix and may change runtime behavior @@ -166,9 +162,7 @@ F601 [*] Dictionary key literal `"a"` repeated | help: Remove repeated key literal `"a"` | -30 | "a": 1, - - "a": 1, -31 | "a": 2, +30 - "a": 1, | note: This is an unsafe fix and may change runtime behavior @@ -243,9 +237,9 @@ F601 [*] Dictionary key literal `"a"` repeated | help: Remove repeated key literal `"a"` | -44 | a: 3, - - "a": 3, -45 | a: 4, +44 - a: 3, +45 - "a": 3, +44 + a: 3, | note: This is an unsafe fix and may change runtime behavior @@ -260,10 +254,8 @@ F601 [*] Dictionary key literal `"a"` repeated | help: Remove repeated key literal `"a"` | -48 | - - x = {"a": 1, "a": 1} +49 - x = {"a": 1, "a": 1} 49 + x = {"a": 1} -50 | x = {"a": 1, "b": 2, "a": 1} | note: This is an unsafe fix and may change runtime behavior @@ -278,10 +270,8 @@ F601 [*] Dictionary key literal `"a"` repeated | help: Remove repeated key literal `"a"` | -49 | x = {"a": 1, "a": 1} - - x = {"a": 1, "b": 2, "a": 1} +50 - x = {"a": 1, "b": 2, "a": 1} 50 + x = {"a": 1, "b": 2} -51 | | note: This is an unsafe fix and may change runtime behavior @@ -307,10 +297,8 @@ F601 [*] Dictionary key literal `"x"` repeated | help: Remove repeated key literal `"x"` | -57 | # Regression test for: https://github.com/astral-sh/ruff/issues/4897 - - t={"x":"test123", "x":("test123")} +58 - t={"x":"test123", "x":("test123")} 58 + t={"x":"test123"} -59 | | note: This is an unsafe fix and may change runtime behavior @@ -326,10 +314,8 @@ F601 [*] Dictionary key literal `"x"` repeated | help: Remove repeated key literal `"x"` | -59 | - - t={"x":("test123"), "x":"test123"} +60 - t={"x":("test123"), "x":"test123"} 60 + t={"x":("test123")} -61 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F602_F602.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F602_F602.py.snap index 2e225de3318a9..bd5d5130b6a93 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F602_F602.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F602_F602.py.snap @@ -48,9 +48,7 @@ F602 [*] Dictionary key `a` repeated | help: Remove repeated key `a` | -12 | a: 3, - - a: 3, -13 | } +12 - a: 3, | note: This is an unsafe fix and may change runtime behavior @@ -90,9 +88,7 @@ F602 [*] Dictionary key `a` repeated | help: Remove repeated key `a` | -19 | a: 3, - - a: 3, -20 | a: 4, +19 - a: 3, | note: This is an unsafe fix and may change runtime behavior @@ -119,9 +115,7 @@ F602 [*] Dictionary key `a` repeated | help: Remove repeated key `a` | -25 | a: 1, - - a: 1, -26 | a: 2, +25 - a: 1, | note: This is an unsafe fix and may change runtime behavior @@ -172,9 +166,9 @@ F602 [*] Dictionary key `a` repeated | help: Remove repeated key `a` | -34 | "a": 1, - - a: 1, -35 | "a": 2, +34 - "a": 1, +35 - a: 1, +34 + "a": 1, | note: This is an unsafe fix and may change runtime behavior @@ -224,10 +218,8 @@ F602 [*] Dictionary key `a` repeated | help: Remove repeated key `a` | -43 | - - x = {a: 1, a: 1} +44 - x = {a: 1, a: 1} 44 + x = {a: 1} -45 | x = {a: 1, b: 2, a: 1} | note: This is an unsafe fix and may change runtime behavior @@ -239,8 +231,7 @@ F602 [*] Dictionary key `a` repeated | ^ help: Remove repeated key `a` | -44 | x = {a: 1, a: 1} - - x = {a: 1, b: 2, a: 1} +45 - x = {a: 1, b: 2, a: 1} 45 + x = {a: 1, b: 2} | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F632_F632.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F632_F632.py.snap index e1df6b06eefd0..cfab8386cdd01 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F632_F632.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F632_F632.py.snap @@ -10,9 +10,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | - - if x is "abc": +1 - if x is "abc": 1 + if x == "abc": -2 | pass | F632 [*] Use `!=` to compare constant literals @@ -26,10 +25,8 @@ F632 [*] Use `!=` to compare constant literals | help: Replace `is not` with `!=` | -3 | - - if 123 is not y: +4 - if 123 is not y: 4 + if 123 != y: -5 | pass | F632 [*] Use `!=` to compare constant literals @@ -45,11 +42,9 @@ F632 [*] Use `!=` to compare constant literals | help: Replace `is not` with `!=` | -6 | - - if 123 is \ - - not y: +7 - if 123 is \ +8 - not y: 7 + if 123 != y: -8 | pass | F632 [*] Use `==` to compare constant literals @@ -63,10 +58,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -10 | - - if "123" is x < 3: +11 - if "123" is x < 3: 11 + if "123" == x < 3: -12 | pass | F632 [*] Use `==` to compare constant literals @@ -80,10 +73,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -13 | - - if "123" != x is 3: +14 - if "123" != x is 3: 14 + if "123" != x == 3: -15 | pass | F632 [*] Use `==` to compare constant literals @@ -97,10 +88,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -16 | - - if ("123" != x) is 3: +17 - if ("123" != x) is 3: 17 + if ("123" != x) == 3: -18 | pass | F632 [*] Use `==` to compare constant literals @@ -114,10 +103,8 @@ F632 [*] Use `==` to compare constant literals | help: Replace `is` with `==` | -19 | - - if "123" != (x is 3): +20 - if "123" != (x is 3): 20 + if "123" != (x == 3): -21 | pass | F632 [*] Use `!=` to compare constant literals @@ -134,11 +121,9 @@ F632 [*] Use `!=` to compare constant literals | help: Replace `is not` with `!=` | -22 | - - {2 is - - not ''} +23 - {2 is +24 - not ''} 23 + {2 != ''} -24 | | F632 [*] Use `!=` to compare constant literals @@ -155,11 +140,9 @@ F632 [*] Use `!=` to compare constant literals | help: Replace `is not` with `!=` | -25 | - - {2 is - - not ''} +26 - {2 is +27 - not ''} 26 + {2 != ''} -27 | | F632 [*] Use `!=` to compare constant literals @@ -172,10 +155,8 @@ F632 [*] Use `!=` to compare constant literals | help: Replace `is not` with `!=` | -29 | # Regression test for - - if values[1is not None ] is not '-': +30 - if values[1is not None ] is not '-': 30 + if values[1is not None ] != '-': -31 | pass | F632 [*] Use `!=` to compare constant literals @@ -188,10 +169,8 @@ F632 [*] Use `!=` to compare constant literals | help: Replace `is not` with `!=` | -29 | # Regression test for - - if values[1is not None ] is not '-': +30 - if values[1is not None ] is not '-': 30 + if values[1!= None ] is not '-': -31 | pass | F632 [*] Use `!=` to compare constant literals @@ -202,7 +181,6 @@ F632 [*] Use `!=` to compare constant literals | ^^^^^^^^^^^^ help: Replace `is not` with `!=` | -33 | # Regression test for https://github.com/astral-sh/ruff/issues/11736 - - variable: "123 is not y" +34 - variable: "123 is not y" 34 + variable: "123 != y" | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_17.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_17.py.snap index 05b281f2b1185..48a1c2d9bf9fd 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_17.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_17.py.snap @@ -17,9 +17,7 @@ F811 [*] Redefinition of unused `fu` from line 2 | -- previous definition of `fu` here help: Remove definition: `fu` | -5 | def bar(): - - import fu -6 | +6 - import fu | F811 Redefinition of unused `fu` from line 6 diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_21.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_21.py.snap index 4d1e409d06ce2..d49c8c689beee 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_21.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_21.py.snap @@ -20,10 +20,8 @@ F811 [*] Redefinition of unused `Sequence` from line 26 | help: Remove definition: `Sequence` | -29 | # This should ignore the first error. - - from typing import ( - - List, # noqa: F811 - - Sequence, - - ) -30 | +30 - from typing import ( +31 - List, # noqa: F811 +32 - Sequence, +33 - ) | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_32.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_32.py.snap index 9d765221ab078..0a2e04c190e50 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_32.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_32.py.snap @@ -13,7 +13,7 @@ F811 [*] Redefinition of unused `List` from line 4 | help: Remove definition: `List` | -4 | List, - - List, -5 | ) +3 + from typing import ( +4 + List, +5 + ) | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_6.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_6.py.snap index 661e301b481c6..d2d273cd2f268 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_6.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_6.py.snap @@ -14,7 +14,5 @@ F811 [*] Redefinition of unused `os` from line 5 | help: Remove definition: `os` | -5 | import os - - import os -6 | os.path +6 - import os | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_8.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_8.py.snap index f66e56508ee79..6418eb9367577 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_8.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_8.py.snap @@ -14,7 +14,5 @@ F811 [*] Redefinition of unused `os` from line 4 | help: Remove definition: `os` | -4 | import os - - import os -5 | except: +5 - import os | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F841_F841_0.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F841_F841_0.py.snap index 203edd2357aab..a2c6e79c005f3 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F841_F841_0.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F841_F841_0.py.snap @@ -12,10 +12,8 @@ F841 [*] Local variable `e` is assigned to but never used | help: Remove assignment to unused variable `e` | -2 | 1 / 0 - - except ValueError as e: +3 - except ValueError as e: 3 + except ValueError: -4 | pass | F841 [*] Local variable `z` is assigned to but never used @@ -27,10 +25,8 @@ F841 [*] Local variable `z` is assigned to but never used | ^ help: Remove assignment to unused variable `z` | -15 | y = 2 - - z = x + y +16 - z = x + y 16 + x + y -17 | | note: This is an unsafe fix and may change runtime behavior @@ -44,9 +40,7 @@ F841 [*] Local variable `foo` is assigned to but never used | help: Remove assignment to unused variable `foo` | -19 | def f(): - - foo = (1, 2) -20 | (a, b) = (1, 2) +20 - foo = (1, 2) | note: This is an unsafe fix and may change runtime behavior @@ -62,11 +56,8 @@ F841 [*] Local variable `a` is assigned to but never used | help: Remove assignment to unused variable `a` | -20 | foo = (1, 2) - - (a, b) = (1, 2) -21 + (_a, b) = (1, 2) -22 | - | +21 | (_a, b) = (1, 2) + | + note: This is an unsafe fix and may change runtime behavior F841 [*] Local variable `b` is assigned to but never used @@ -81,11 +72,8 @@ F841 [*] Local variable `b` is assigned to but never used | help: Remove assignment to unused variable `b` | -20 | foo = (1, 2) - - (a, b) = (1, 2) -21 + (a, _b) = (1, 2) -22 | - | +21 | (a, _b) = (1, 2) + | + note: This is an unsafe fix and may change runtime behavior F841 [*] Local variable `baz` is assigned to but never used @@ -97,10 +85,8 @@ F841 [*] Local variable `baz` is assigned to but never used | ^^^ help: Remove assignment to unused variable `baz` | -25 | - - (x, y) = baz = bar +26 - (x, y) = baz = bar 26 + (x, y) = bar -27 | | note: This is an unsafe fix and may change runtime behavior @@ -116,10 +102,8 @@ F841 [*] Local variable `b` is assigned to but never used | help: Remove assignment to unused variable `b` | -50 | # F841 - - b = 1 +51 - b = 1 51 + pass -52 | | note: This is an unsafe fix and may change runtime behavior @@ -133,10 +117,8 @@ F841 [*] Local variable `my_file` is assigned to but never used | help: Remove assignment to unused variable `my_file` | -78 | def f(): - - with open("file") as my_file, open("") as ((this, that)): +79 - with open("file") as my_file, open("") as ((this, that)): 79 + with open("file"), open("") as ((this, that)): -80 | print("hello") | note: This is an unsafe fix and may change runtime behavior @@ -152,10 +134,8 @@ F841 [*] Local variable `my_file` is assigned to but never used | help: Remove assignment to unused variable `my_file` | -84 | with ( - - open("file") as my_file, +85 - open("file") as my_file, 85 + open("file"), -86 | open("") as ((this, that)), | note: This is an unsafe fix and may change runtime behavior @@ -171,9 +151,7 @@ F841 [*] Local variable `msg3` is assigned to but never used | help: Remove assignment to unused variable `msg3` | -101 | msg2 = "Hello, world!" - - msg3 = "Hello, world!" -102 | match x: +102 - msg3 = "Hello, world!" | note: This is an unsafe fix and may change runtime behavior @@ -189,10 +167,8 @@ F841 [*] Local variable `Baz` is assigned to but never used | help: Remove assignment to unused variable `Baz` | -114 | Bar = enum.Enum("Bar", "A B") - - Baz = enum.Enum("Baz", "A B") +115 - Baz = enum.Enum("Baz", "A B") 115 + enum.Enum("Baz", "A B") -116 | | note: This is an unsafe fix and may change runtime behavior @@ -226,10 +202,8 @@ F841 [*] Local variable `__class__` is assigned to but never used | ^^^^^^^^^ help: Remove assignment to unused variable `__class__` | -167 | def set_class(self, cls): - - __class__ = cls # F841 +168 - __class__ = cls # F841 168 + pass # F841 -169 | | note: This is an unsafe fix and may change runtime behavior @@ -242,10 +216,8 @@ F841 [*] Local variable `__class__` is assigned to but never used | ^^^^^^^^^ help: Remove assignment to unused variable `__class__` | -173 | def set_class(self, cls): - - __class__ = cls # F841 +174 - __class__ = cls # F841 174 + pass # F841 -175 | | note: This is an unsafe fix and may change runtime behavior @@ -258,9 +230,7 @@ F841 [*] Local variable `__class__` is assigned to but never used | ^^^^^^^^^ help: Remove assignment to unused variable `__class__` | -181 | def set_class(self, cls): - - __class__ = cls # F841 +182 - __class__ = cls # F841 182 + pass # F841 -183 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F841_F841_1.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F841_F841_1.py.snap index 796f69c96d87f..25ff155979ad7 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F841_F841_1.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F841_F841_1.py.snap @@ -9,11 +9,8 @@ F841 [*] Local variable `x` is assigned to but never used | ^ help: Remove assignment to unused variable `x` | -5 | def f(): - - x, y = 1, 2 # this triggers F841 as it's just a simple assignment where unpacking isn't needed -6 + _x, y = 1, 2 # this triggers F841 as it's just a simple assignment where unpacking isn't needed -7 | - | +6 | _x, y = 1, 2 # this triggers F841 as it's just a simple assignment where unpacking isn't needed + | + note: This is an unsafe fix and may change runtime behavior F841 [*] Local variable `y` is assigned to but never used @@ -24,11 +21,8 @@ F841 [*] Local variable `y` is assigned to but never used | ^ help: Remove assignment to unused variable `y` | -5 | def f(): - - x, y = 1, 2 # this triggers F841 as it's just a simple assignment where unpacking isn't needed -6 + x, _y = 1, 2 # this triggers F841 as it's just a simple assignment where unpacking isn't needed -7 | - | +6 | x, _y = 1, 2 # this triggers F841 as it's just a simple assignment where unpacking isn't needed + | + note: This is an unsafe fix and may change runtime behavior F841 [*] Local variable `coords` is assigned to but never used @@ -39,10 +33,8 @@ F841 [*] Local variable `coords` is assigned to but never used | ^^^^^^ help: Remove assignment to unused variable `coords` | -15 | def f(): - - (x, y) = coords = 1, 2 +16 - (x, y) = coords = 1, 2 16 + (x, y) = 1, 2 -17 | | note: This is an unsafe fix and may change runtime behavior @@ -54,10 +46,8 @@ F841 [*] Local variable `coords` is assigned to but never used | ^^^^^^ help: Remove assignment to unused variable `coords` | -19 | def f(): - - coords = (x, y) = 1, 2 +20 - coords = (x, y) = 1, 2 20 + (x, y) = 1, 2 -21 | | note: This is an unsafe fix and may change runtime behavior @@ -69,10 +59,8 @@ F841 [*] Local variable `a` is assigned to but never used | ^ help: Remove assignment to unused variable `a` | -23 | def f(): - - (a, b) = (x, y) = 1, 2 # this triggers F841 on everything -24 + (_a, b) = (x, y) = 1, 2 # this triggers F841 on everything - | +24 | (_a, b) = (x, y) = 1, 2 # this triggers F841 on everything + | + note: This is an unsafe fix and may change runtime behavior F841 [*] Local variable `b` is assigned to but never used @@ -83,10 +71,8 @@ F841 [*] Local variable `b` is assigned to but never used | ^ help: Remove assignment to unused variable `b` | -23 | def f(): - - (a, b) = (x, y) = 1, 2 # this triggers F841 on everything -24 + (a, _b) = (x, y) = 1, 2 # this triggers F841 on everything - | +24 | (a, _b) = (x, y) = 1, 2 # this triggers F841 on everything + | + note: This is an unsafe fix and may change runtime behavior F841 [*] Local variable `x` is assigned to but never used @@ -97,10 +83,8 @@ F841 [*] Local variable `x` is assigned to but never used | ^ help: Remove assignment to unused variable `x` | -23 | def f(): - - (a, b) = (x, y) = 1, 2 # this triggers F841 on everything -24 + (a, b) = (_x, y) = 1, 2 # this triggers F841 on everything - | +24 | (a, b) = (_x, y) = 1, 2 # this triggers F841 on everything + | + note: This is an unsafe fix and may change runtime behavior F841 [*] Local variable `y` is assigned to but never used @@ -111,8 +95,6 @@ F841 [*] Local variable `y` is assigned to but never used | ^ help: Remove assignment to unused variable `y` | -23 | def f(): - - (a, b) = (x, y) = 1, 2 # this triggers F841 on everything -24 + (a, b) = (x, _y) = 1, 2 # this triggers F841 on everything - | +24 | (a, b) = (x, _y) = 1, 2 # this triggers F841 on everything + | + note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F841_F841_3.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F841_F841_3.py.snap index 50f8c9deb6906..047cc804e60f1 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F841_F841_3.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F841_F841_3.py.snap @@ -11,9 +11,7 @@ F841 [*] Local variable `x` is assigned to but never used | help: Remove assignment to unused variable `x` | -4 | def f(): - - x = 1 -5 | y = 2 +5 - x = 1 | note: This is an unsafe fix and may change runtime behavior @@ -29,9 +27,7 @@ F841 [*] Local variable `y` is assigned to but never used | help: Remove assignment to unused variable `y` | -5 | x = 1 - - y = 2 -6 | +6 - y = 2 | note: This is an unsafe fix and may change runtime behavior @@ -45,9 +41,7 @@ F841 [*] Local variable `x` is assigned to but never used | help: Remove assignment to unused variable `x` | -12 | def f(): - - x: int = 1 -13 | y: int = 2 +13 - x: int = 1 | note: This is an unsafe fix and may change runtime behavior @@ -63,9 +57,7 @@ F841 [*] Local variable `y` is assigned to but never used | help: Remove assignment to unused variable `y` | -13 | x: int = 1 - - y: int = 2 -14 | +14 - y: int = 2 | note: This is an unsafe fix and may change runtime behavior @@ -79,10 +71,8 @@ F841 [*] Local variable `x1` is assigned to but never used | help: Remove assignment to unused variable `x1` | -20 | def f(): - - with foo() as x1: +21 - with foo() as x1: 21 + with foo(): -22 | pass | note: This is an unsafe fix and may change runtime behavior @@ -97,10 +87,8 @@ F841 [*] Local variable `x3` is assigned to but never used | help: Remove assignment to unused variable `x3` | -26 | - - with (foo() as x3, foo() as y3, foo() as z3): +27 - with (foo() as x3, foo() as y3, foo() as z3): 27 + with (foo(), foo() as y3, foo() as z3): -28 | pass | note: This is an unsafe fix and may change runtime behavior @@ -115,10 +103,8 @@ F841 [*] Local variable `y3` is assigned to but never used | help: Remove assignment to unused variable `y3` | -26 | - - with (foo() as x3, foo() as y3, foo() as z3): +27 - with (foo() as x3, foo() as y3, foo() as z3): 27 + with (foo() as x3, foo(), foo() as z3): -28 | pass | note: This is an unsafe fix and may change runtime behavior @@ -133,10 +119,8 @@ F841 [*] Local variable `z3` is assigned to but never used | help: Remove assignment to unused variable `z3` | -26 | - - with (foo() as x3, foo() as y3, foo() as z3): +27 - with (foo() as x3, foo() as y3, foo() as z3): 27 + with (foo() as x3, foo() as y3, foo()): -28 | pass | note: This is an unsafe fix and may change runtime behavior @@ -151,11 +135,8 @@ F841 [*] Local variable `x1` is assigned to but never used | help: Remove assignment to unused variable `x1` | -31 | def f(): - - (x1, y1) = (1, 2) -32 + (_x1, y1) = (1, 2) -33 | (x2, y2) = coords2 = (1, 2) - | +32 | (_x1, y1) = (1, 2) + | + note: This is an unsafe fix and may change runtime behavior F841 [*] Local variable `y1` is assigned to but never used @@ -169,11 +150,8 @@ F841 [*] Local variable `y1` is assigned to but never used | help: Remove assignment to unused variable `y1` | -31 | def f(): - - (x1, y1) = (1, 2) -32 + (x1, _y1) = (1, 2) -33 | (x2, y2) = coords2 = (1, 2) - | +32 | (x1, _y1) = (1, 2) + | + note: This is an unsafe fix and may change runtime behavior F841 [*] Local variable `coords2` is assigned to but never used @@ -187,10 +165,8 @@ F841 [*] Local variable `coords2` is assigned to but never used | help: Remove assignment to unused variable `coords2` | -32 | (x1, y1) = (1, 2) - - (x2, y2) = coords2 = (1, 2) +33 - (x2, y2) = coords2 = (1, 2) 33 + (x2, y2) = (1, 2) -34 | coords3 = (x3, y3) = (1, 2) | note: This is an unsafe fix and may change runtime behavior @@ -203,10 +179,8 @@ F841 [*] Local variable `coords3` is assigned to but never used | ^^^^^^^ help: Remove assignment to unused variable `coords3` | -33 | (x2, y2) = coords2 = (1, 2) - - coords3 = (x3, y3) = (1, 2) +34 - coords3 = (x3, y3) = (1, 2) 34 + (x3, y3) = (1, 2) -35 | | note: This is an unsafe fix and may change runtime behavior @@ -221,10 +195,8 @@ F841 [*] Local variable `x1` is assigned to but never used | help: Remove assignment to unused variable `x1` | -39 | 1 / 0 - - except ValueError as x1: +40 - except ValueError as x1: 40 + except ValueError: -41 | pass | F841 [*] Local variable `x2` is assigned to but never used @@ -238,10 +210,8 @@ F841 [*] Local variable `x2` is assigned to but never used | help: Remove assignment to unused variable `x2` | -44 | 1 / 0 - - except (ValueError, ZeroDivisionError) as x2: +45 - except (ValueError, ZeroDivisionError) as x2: 45 + except (ValueError, ZeroDivisionError): -46 | pass | F841 [*] Local variable `x` is assigned to but never used @@ -255,10 +225,8 @@ F841 [*] Local variable `x` is assigned to but never used | help: Remove assignment to unused variable `x` | -49 | def f(a, b): - - x = ( +50 - x = ( 50 + ( -51 | a() | note: This is an unsafe fix and may change runtime behavior @@ -273,11 +241,9 @@ F841 [*] Local variable `y` is assigned to but never used | help: Remove assignment to unused variable `y` | -55 | - - y = \ - - a() if a is not None else b +56 - y = \ +57 - a() if a is not None else b 56 + a() if a is not None else b -57 | | note: This is an unsafe fix and may change runtime behavior @@ -292,13 +258,11 @@ F841 [*] Local variable `x` is assigned to but never used | help: Remove assignment to unused variable `x` | -60 | def f(a, b): - - x = ( - - a - - if a is not None - - else b - - ) -61 | +61 - x = ( +62 - a +63 - if a is not None +64 - else b +65 - ) | note: This is an unsafe fix and may change runtime behavior @@ -313,10 +277,8 @@ F841 [*] Local variable `y` is assigned to but never used | help: Remove assignment to unused variable `y` | -66 | - - y = \ - - a if a is not None else b -67 | +67 - y = \ +68 - a if a is not None else b | note: This is an unsafe fix and may change runtime behavior @@ -330,10 +292,8 @@ F841 [*] Local variable `cm` is assigned to but never used | help: Remove assignment to unused variable `cm` | -71 | def f(): - - with Nested(m) as (cm): +72 - with Nested(m) as (cm): 72 + with Nested(m): -73 | pass | note: This is an unsafe fix and may change runtime behavior @@ -347,10 +307,8 @@ F841 [*] Local variable `cm` is assigned to but never used | help: Remove assignment to unused variable `cm` | -76 | def f(): - - with (Nested(m) as (cm),): +77 - with (Nested(m) as (cm),): 77 + with (Nested(m),): -78 | pass | note: This is an unsafe fix and may change runtime behavior @@ -364,10 +322,8 @@ F841 [*] Local variable `cm` is assigned to but never used | help: Remove assignment to unused variable `cm` | -86 | def f(): - - with (Nested(m)) as (cm): +87 - with (Nested(m)) as (cm): 87 + with (Nested(m)): -88 | pass | note: This is an unsafe fix and may change runtime behavior @@ -382,10 +338,8 @@ F841 [*] Local variable `toplevel` is assigned to but never used | help: Remove assignment to unused variable `toplevel` | -91 | def f(): - - toplevel = tt = lexer.get_token() +92 - toplevel = tt = lexer.get_token() 92 + tt = lexer.get_token() -93 | if not tt: | note: This is an unsafe fix and may change runtime behavior @@ -397,10 +351,8 @@ F841 [*] Local variable `toplevel` is assigned to but never used | ^^^^^^^^ help: Remove assignment to unused variable `toplevel` | -97 | def f(): - - toplevel = tt = lexer.get_token() +98 - toplevel = tt = lexer.get_token() 98 + tt = lexer.get_token() -99 | | note: This is an unsafe fix and may change runtime behavior @@ -412,10 +364,8 @@ F841 [*] Local variable `tt` is assigned to but never used | ^^ help: Remove assignment to unused variable `tt` | -97 | def f(): - - toplevel = tt = lexer.get_token() +98 - toplevel = tt = lexer.get_token() 98 + toplevel = lexer.get_token() -99 | | note: This is an unsafe fix and may change runtime behavior @@ -427,10 +377,8 @@ F841 [*] Local variable `toplevel` is assigned to but never used | ^^^^^^^^ help: Remove assignment to unused variable `toplevel` | -101 | def f(): - - toplevel = (a, b) = lexer.get_token() +102 - toplevel = (a, b) = lexer.get_token() 102 + (a, b) = lexer.get_token() -103 | | note: This is an unsafe fix and may change runtime behavior @@ -442,10 +390,8 @@ F841 [*] Local variable `toplevel` is assigned to but never used | ^^^^^^^^ help: Remove assignment to unused variable `toplevel` | -105 | def f(): - - (a, b) = toplevel = lexer.get_token() +106 - (a, b) = toplevel = lexer.get_token() 106 + (a, b) = lexer.get_token() -107 | | note: This is an unsafe fix and may change runtime behavior @@ -457,10 +403,8 @@ F841 [*] Local variable `toplevel` is assigned to but never used | ^^^^^^^^ help: Remove assignment to unused variable `toplevel` | -109 | def f(): - - toplevel = tt = 1 +110 - toplevel = tt = 1 110 + tt = 1 -111 | | note: This is an unsafe fix and may change runtime behavior @@ -472,10 +416,8 @@ F841 [*] Local variable `tt` is assigned to but never used | ^^ help: Remove assignment to unused variable `tt` | -109 | def f(): - - toplevel = tt = 1 +110 - toplevel = tt = 1 110 + toplevel = 1 -111 | | note: This is an unsafe fix and may change runtime behavior @@ -556,10 +498,8 @@ F841 [*] Local variable `e` is assigned to but never used | help: Remove assignment to unused variable `e` | -154 | print("hello") - - except A as e : +155 - except A as e : 155 + except A: -156 | print("oh no!") | F841 [*] Local variable `x` is assigned to but never used @@ -572,9 +512,7 @@ F841 [*] Local variable `x` is assigned to but never used | help: Remove assignment to unused variable `x` | -159 | def f(): - - x = 1 -160 | y = 2 +160 - x = 1 | note: This is an unsafe fix and may change runtime behavior @@ -587,9 +525,7 @@ F841 [*] Local variable `y` is assigned to but never used | ^ help: Remove assignment to unused variable `y` | -160 | x = 1 - - y = 2 -161 | +161 - y = 2 | note: This is an unsafe fix and may change runtime behavior @@ -604,9 +540,7 @@ F841 [*] Local variable `x` is assigned to but never used | help: Remove assignment to unused variable `x` | -164 | def f(): - - x = 1 -165 | +165 - x = 1 | note: This is an unsafe fix and may change runtime behavior @@ -619,9 +553,7 @@ F841 [*] Local variable `y` is assigned to but never used | ^ help: Remove assignment to unused variable `y` | -166 | - - y = 2 -167 | +167 - y = 2 | note: This is an unsafe fix and may change runtime behavior @@ -634,8 +566,7 @@ F841 [*] Local variable `x` is assigned to but never used | ^ help: Remove assignment to unused variable `x` | -172 | ((x)) = foo() - - (x) = (y.z) = foo() +173 - (x) = (y.z) = foo() 173 + (y.z) = foo() | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F901_F901.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F901_F901.py.snap index a4bbb7c51fcfe..4227596b3297f 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F901_F901.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F901_F901.py.snap @@ -9,11 +9,8 @@ F901 [*] `raise NotImplemented` should be `raise NotImplementedError` | ^^^^^^^^^^^^^^ help: Use `raise NotImplementedError` | -1 | def f() -> None: - - raise NotImplemented() -2 + raise NotImplementedError() -3 | - | +2 | raise NotImplementedError() + | +++++ F901 [*] `raise NotImplemented` should be `raise NotImplementedError` --> F901.py:6:11 @@ -23,11 +20,8 @@ F901 [*] `raise NotImplemented` should be `raise NotImplementedError` | ^^^^^^^^^^^^^^ help: Use `raise NotImplementedError` | -5 | def g() -> None: - - raise NotImplemented -6 + raise NotImplementedError -7 | - | +6 | raise NotImplementedError + | +++++ F901 [*] `raise NotImplemented` should be `raise NotImplementedError` --> F901.py:11:11 @@ -38,10 +32,10 @@ F901 [*] `raise NotImplemented` should be `raise NotImplementedError` | ^^^^^^^^^^^^^^ help: Use `raise NotImplementedError` | -1 + import builtins -2 | def f() -> None: --------------------------------------------------------------------------------- + 1 + import builtins + 2 | def f() -> None: + 3 | raise NotImplemented() + … 11 | NotImplementedError = "foo" - - raise NotImplemented -12 + raise builtins.NotImplementedError +12 ~ raise builtins.NotImplementedError | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__del_shadowed_global_import_in_global_scope.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__del_shadowed_global_import_in_global_scope.snap index 90b5fd53dbc6d..287f4c305475a 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__del_shadowed_global_import_in_global_scope.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__del_shadowed_global_import_in_global_scope.snap @@ -12,8 +12,6 @@ F401 [*] `os` imported but unused | help: Remove unused import: `os` | -4 | def f(): - - import os +5 - import os 5 + pass -6 | | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__del_shadowed_global_import_in_local_scope.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__del_shadowed_global_import_in_local_scope.snap index 7ee75ac2a27cd..03706e94a8567 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__del_shadowed_global_import_in_local_scope.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__del_shadowed_global_import_in_local_scope.snap @@ -11,9 +11,7 @@ F401 [*] `os` imported but unused | help: Remove unused import: `os` | -1 | - - import os -2 | +2 - import os | F811 [*] Redefinition of unused `os` from line 2 @@ -30,7 +28,5 @@ F811 [*] Redefinition of unused `os` from line 2 | help: Remove definition: `os` | -4 | def f(): - - import os -5 | +5 - import os | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__del_shadowed_import_shadow_in_local_scope.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__del_shadowed_import_shadow_in_local_scope.snap index c4c0211abdfcf..07fef1ac28fc5 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__del_shadowed_import_shadow_in_local_scope.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__del_shadowed_import_shadow_in_local_scope.snap @@ -11,9 +11,7 @@ F401 [*] `os` imported but unused | help: Remove unused import: `os` | -1 | - - import os -2 | +2 - import os | F811 Redefinition of unused `os` from line 2 diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__del_shadowed_local_import_in_local_scope.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__del_shadowed_local_import_in_local_scope.snap index 3f3e2d46a8ceb..e8e3b6c89b6b9 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__del_shadowed_local_import_in_local_scope.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__del_shadowed_local_import_in_local_scope.snap @@ -14,7 +14,5 @@ F811 [*] Redefinition of unused `os` from line 3 | help: Remove definition: `os` | -3 | import os - - import os -4 | +4 - import os | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_allowed_unused_imports_option.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_allowed_unused_imports_option.snap index 52fe179d2b6ae..a5745ce7dfcde 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_allowed_unused_imports_option.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_allowed_unused_imports_option.snap @@ -9,6 +9,5 @@ F401 [*] `hvplot.pandas_alias.scatter_matrix` imported but unused | ^^^^^^^^^^^^^^ help: Remove unused import: `hvplot.pandas_alias.scatter_matrix` | -11 | # Errors - - from hvplot.pandas_alias import scatter_matrix +12 - from hvplot.pandas_alias import scatter_matrix | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_import_submodules_but_use_top_level.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_import_submodules_but_use_top_level.snap index 6554c0bccf41b..a0c49c804040b 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_import_submodules_but_use_top_level.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_import_submodules_but_use_top_level.snap @@ -11,7 +11,5 @@ F401 [*] `a.b` imported but unused | help: Remove unused import: `a.b` | -2 | import a.c - - import a.b -3 | a.foo() +3 - import a.b | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_import_submodules_different_lengths_but_use_top_level.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_import_submodules_different_lengths_but_use_top_level.snap index f936b9c3737b7..710a2a192e1e2 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_import_submodules_different_lengths_but_use_top_level.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_import_submodules_different_lengths_but_use_top_level.snap @@ -11,7 +11,5 @@ F401 [*] `a.b.d` imported but unused | help: Remove unused import: `a.b.d` | -2 | import a.c - - import a.b.d -3 | a.foo() +3 - import a.b.d | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_import_submodules_in_function_scope.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_import_submodules_in_function_scope.snap index c2029b68afbdd..5e2032ab7bc4a 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_import_submodules_in_function_scope.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_import_submodules_in_function_scope.snap @@ -12,7 +12,5 @@ F401 [*] `a` imported but unused | help: Remove unused import: `a` | -2 | # refined logic only applied _within_ scope - - import a -3 | def foo(): +3 - import a | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_multiple_unused_submodules.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_multiple_unused_submodules.snap index b6107c54f5c58..4972637205d1f 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_multiple_unused_submodules.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_multiple_unused_submodules.snap @@ -11,9 +11,7 @@ F401 [*] `a` imported but unused | help: Remove unused import: `a` | -1 | - - import a -2 | import a.b +2 - import a | F401 [*] `a.b` imported but unused @@ -26,9 +24,7 @@ F401 [*] `a.b` imported but unused | help: Remove unused import: `a.b` | -2 | import a - - import a.b -3 | import a.c +3 - import a.b | F401 [*] `a.c` imported but unused @@ -40,6 +36,5 @@ F401 [*] `a.c` imported but unused | ^^^ help: Remove unused import: `a.c` | -3 | import a.b - - import a.c +4 - import a.c | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_preview_dunder_all_multiple_bindings.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_preview_dunder_all_multiple_bindings.snap index c2392143acf0d..02855ce960067 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_preview_dunder_all_multiple_bindings.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_preview_dunder_all_multiple_bindings.snap @@ -12,8 +12,6 @@ F401 [*] `submodule.baz` imported but unused | help: Remove unused import: `submodule.baz` | -2 | import submodule.bar - - import submodule.baz -3 | __all__ = ['submodule'] +3 - import submodule.baz | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_preview_first_party_submodule_dunder_all.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_preview_first_party_submodule_dunder_all.snap index 84a637e7a9fa2..1ad80fa797f65 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_preview_first_party_submodule_dunder_all.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_preview_first_party_submodule_dunder_all.snap @@ -11,8 +11,5 @@ F401 [*] `submodule.a` imported but unused; consider removing, adding to `__all_ | help: Add `submodule` to __all__ | -2 | import submodule.a - - __all__ = ['FOO'] -3 + __all__ = ['FOO', 'submodule'] -4 | FOO = 42 - | +3 | __all__ = ['FOO', 'submodule'] + | +++++++++++++ diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_same_branch.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_same_branch.snap index 82df6d7f12101..93c3e7f08f91b 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_same_branch.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_same_branch.snap @@ -12,7 +12,5 @@ F401 [*] `a.b` imported but unused | help: Remove unused import: `a.b` | -3 | import a - - import a.b -4 | a.foo() +4 - import a.b | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_type_checking.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_type_checking.snap index 5a4fdbc283418..c8a32f52d308c 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_type_checking.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_type_checking.snap @@ -11,9 +11,7 @@ F401 [*] `mlflow.pyfunc.loaders.chat_agent` imported but unused | help: Remove unused import: `mlflow.pyfunc.loaders.chat_agent` | -1 | - - import mlflow.pyfunc.loaders.chat_agent -2 | import mlflow.pyfunc.loaders.chat_model +2 - import mlflow.pyfunc.loaders.chat_agent | F401 [*] `mlflow.pyfunc.loaders.chat_model` imported but unused @@ -27,9 +25,7 @@ F401 [*] `mlflow.pyfunc.loaders.chat_model` imported but unused | help: Remove unused import: `mlflow.pyfunc.loaders.chat_model` | -2 | import mlflow.pyfunc.loaders.chat_agent - - import mlflow.pyfunc.loaders.chat_model -3 | import mlflow.pyfunc.loaders.code_model +3 - import mlflow.pyfunc.loaders.chat_model | F401 [*] `mlflow.pyfunc.loaders.code_model` imported but unused @@ -43,9 +39,7 @@ F401 [*] `mlflow.pyfunc.loaders.code_model` imported but unused | help: Remove unused import: `mlflow.pyfunc.loaders.code_model` | -3 | import mlflow.pyfunc.loaders.chat_model - - import mlflow.pyfunc.loaders.code_model -4 | from mlflow.utils.pydantic_utils import IS_PYDANTIC_V2_OR_NEWER +4 - import mlflow.pyfunc.loaders.code_model | F401 [*] `mlflow.pyfunc.loaders.responses_agent` imported but unused @@ -56,7 +50,6 @@ F401 [*] `mlflow.pyfunc.loaders.responses_agent` imported but unused | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove unused import: `mlflow.pyfunc.loaders.responses_agent` | -7 | if IS_PYDANTIC_V2_OR_NEWER: - - import mlflow.pyfunc.loaders.responses_agent +8 - import mlflow.pyfunc.loaders.responses_agent 8 + pass | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_use_in_dunder_all.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_use_in_dunder_all.snap index 2359335f73af0..b185d84487222 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_use_in_dunder_all.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_use_in_dunder_all.snap @@ -11,7 +11,5 @@ F401 [*] `a.b` imported but unused | help: Remove unused import: `a.b` | -2 | import a - - import a.b -3 | __all__ = ["a"] +3 - import a.b | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_use_top_member.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_use_top_member.snap index d9a53043ba518..73f3c11b41902 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_use_top_member.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_use_top_member.snap @@ -11,7 +11,5 @@ F401 [*] `a.b` imported but unused | help: Remove unused import: `a.b` | -2 | import a - - import a.b -3 | a.foo() +3 - import a.b | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_use_top_member_twice.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_use_top_member_twice.snap index 2470a4e3370b4..6cd939ec51bd3 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_use_top_member_twice.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f401_use_top_member_twice.snap @@ -12,7 +12,5 @@ F401 [*] `a.b` imported but unused | help: Remove unused import: `a.b` | -2 | import a - - import a.b -3 | a.foo() +3 - import a.b | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f841_dummy_variable_rgx.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f841_dummy_variable_rgx.snap index c0080449f792e..6f5184d50af6f 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f841_dummy_variable_rgx.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__f841_dummy_variable_rgx.snap @@ -12,10 +12,8 @@ F841 [*] Local variable `e` is assigned to but never used | help: Remove assignment to unused variable `e` | -2 | 1 / 0 - - except ValueError as e: +3 - except ValueError as e: 3 + except ValueError: -4 | pass | F841 [*] Local variable `foo` is assigned to but never used @@ -28,9 +26,7 @@ F841 [*] Local variable `foo` is assigned to but never used | help: Remove assignment to unused variable `foo` | -19 | def f(): - - foo = (1, 2) -20 | (a, b) = (1, 2) +20 - foo = (1, 2) | note: This is an unsafe fix and may change runtime behavior @@ -67,10 +63,8 @@ F841 [*] Local variable `baz` is assigned to but never used | ^^^ help: Remove assignment to unused variable `baz` | -25 | - - (x, y) = baz = bar +26 - (x, y) = baz = bar 26 + (x, y) = bar -27 | | note: This is an unsafe fix and may change runtime behavior @@ -85,9 +79,7 @@ F841 [*] Local variable `_` is assigned to but never used | help: Remove assignment to unused variable `_` | -34 | def f(): - - _ = 1 -35 | __ = 1 +35 - _ = 1 | note: This is an unsafe fix and may change runtime behavior @@ -102,9 +94,7 @@ F841 [*] Local variable `__` is assigned to but never used | help: Remove assignment to unused variable `__` | -35 | _ = 1 - - __ = 1 -36 | _discarded = 1 +36 - __ = 1 | note: This is an unsafe fix and may change runtime behavior @@ -117,9 +107,7 @@ F841 [*] Local variable `_discarded` is assigned to but never used | ^^^^^^^^^^ help: Remove assignment to unused variable `_discarded` | -36 | __ = 1 - - _discarded = 1 -37 | +37 - _discarded = 1 | note: This is an unsafe fix and may change runtime behavior @@ -135,10 +123,8 @@ F841 [*] Local variable `b` is assigned to but never used | help: Remove assignment to unused variable `b` | -50 | # F841 - - b = 1 +51 - b = 1 51 + pass -52 | | note: This is an unsafe fix and may change runtime behavior @@ -152,10 +138,8 @@ F841 [*] Local variable `my_file` is assigned to but never used | help: Remove assignment to unused variable `my_file` | -78 | def f(): - - with open("file") as my_file, open("") as ((this, that)): +79 - with open("file") as my_file, open("") as ((this, that)): 79 + with open("file"), open("") as ((this, that)): -80 | print("hello") | note: This is an unsafe fix and may change runtime behavior @@ -171,10 +155,8 @@ F841 [*] Local variable `my_file` is assigned to but never used | help: Remove assignment to unused variable `my_file` | -84 | with ( - - open("file") as my_file, +85 - open("file") as my_file, 85 + open("file"), -86 | open("") as ((this, that)), | note: This is an unsafe fix and may change runtime behavior @@ -190,9 +172,7 @@ F841 [*] Local variable `msg3` is assigned to but never used | help: Remove assignment to unused variable `msg3` | -101 | msg2 = "Hello, world!" - - msg3 = "Hello, world!" -102 | match x: +102 - msg3 = "Hello, world!" | note: This is an unsafe fix and may change runtime behavior @@ -208,10 +188,8 @@ F841 [*] Local variable `Baz` is assigned to but never used | help: Remove assignment to unused variable `Baz` | -114 | Bar = enum.Enum("Bar", "A B") - - Baz = enum.Enum("Baz", "A B") +115 - Baz = enum.Enum("Baz", "A B") 115 + enum.Enum("Baz", "A B") -116 | | note: This is an unsafe fix and may change runtime behavior @@ -247,10 +225,8 @@ F841 [*] Local variable `_` is assigned to but never used | help: Remove assignment to unused variable `_` | -151 | pass - - except Exception as _: +152 - except Exception as _: 152 + except Exception: -153 | pass | F841 [*] Local variable `__class__` is assigned to but never used @@ -262,10 +238,8 @@ F841 [*] Local variable `__class__` is assigned to but never used | ^^^^^^^^^ help: Remove assignment to unused variable `__class__` | -167 | def set_class(self, cls): - - __class__ = cls # F841 +168 - __class__ = cls # F841 168 + pass # F841 -169 | | note: This is an unsafe fix and may change runtime behavior @@ -278,10 +252,8 @@ F841 [*] Local variable `__class__` is assigned to but never used | ^^^^^^^^^ help: Remove assignment to unused variable `__class__` | -173 | def set_class(self, cls): - - __class__ = cls # F841 +174 - __class__ = cls # F841 174 + pass # F841 -175 | | note: This is an unsafe fix and may change runtime behavior @@ -294,9 +266,7 @@ F841 [*] Local variable `__class__` is assigned to but never used | ^^^^^^^^^ help: Remove assignment to unused variable `__class__` | -181 | def set_class(self, cls): - - __class__ = cls # F841 +182 - __class__ = cls # F841 182 + pass # F841 -183 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__future_annotations.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__future_annotations.snap index 3ce076504fc94..dea552c526bdb 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__future_annotations.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__future_annotations.snap @@ -12,9 +12,9 @@ F401 [*] `models.Nut` imported but unused | help: Remove unused import: `models.Nut` | -7 | Fruit, - - Nut, -8 | ) +6 + from models import ( +7 + Fruit, +8 + ) | F821 Undefined name `Bar` diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__load_after_multiple_unbinds_from_module_scope.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__load_after_multiple_unbinds_from_module_scope.snap index 5b983cf432160..02ac1d479fc62 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__load_after_multiple_unbinds_from_module_scope.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__load_after_multiple_unbinds_from_module_scope.snap @@ -12,10 +12,8 @@ F841 [*] Local variable `x` is assigned to but never used | help: Remove assignment to unused variable `x` | -6 | pass - - except ValueError as x: +7 - except ValueError as x: 7 + except ValueError: -8 | pass | F841 [*] Local variable `x` is assigned to but never used @@ -29,8 +27,6 @@ F841 [*] Local variable `x` is assigned to but never used | help: Remove assignment to unused variable `x` | -11 | pass - - except ValueError as x: +12 - except ValueError as x: 12 + except ValueError: -13 | pass | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__load_after_unbind_from_class_scope.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__load_after_unbind_from_class_scope.snap index 40050a846a5f9..8ef86eff272e4 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__load_after_unbind_from_class_scope.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__load_after_unbind_from_class_scope.snap @@ -12,10 +12,8 @@ F841 [*] Local variable `x` is assigned to but never used | help: Remove assignment to unused variable `x` | -7 | pass - - except ValueError as x: +8 - except ValueError as x: 8 + except ValueError: -9 | pass | F821 Undefined name `x` diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__load_after_unbind_from_module_scope.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__load_after_unbind_from_module_scope.snap index 3619845ec57a8..9821358436876 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__load_after_unbind_from_module_scope.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__load_after_unbind_from_module_scope.snap @@ -12,8 +12,6 @@ F841 [*] Local variable `x` is assigned to but never used | help: Remove assignment to unused variable `x` | -6 | pass - - except ValueError as x: +7 - except ValueError as x: 7 + except ValueError: -8 | pass | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__load_after_unbind_from_nested_module_scope.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__load_after_unbind_from_nested_module_scope.snap index 9cecfeaded52c..8f20150fbcac7 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__load_after_unbind_from_nested_module_scope.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__load_after_unbind_from_nested_module_scope.snap @@ -12,10 +12,8 @@ F841 [*] Local variable `x` is assigned to but never used | help: Remove assignment to unused variable `x` | -6 | pass - - except ValueError as x: +7 - except ValueError as x: 7 + except ValueError: -8 | pass | F841 [*] Local variable `x` is assigned to but never used @@ -29,8 +27,6 @@ F841 [*] Local variable `x` is assigned to but never used | help: Remove assignment to unused variable `x` | -12 | pass - - except ValueError as x: +13 - except ValueError as x: 13 + except ValueError: -14 | pass | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__multi_statement_lines.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__multi_statement_lines.snap index 7a2cac0005110..cdea40a2e12a3 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__multi_statement_lines.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__multi_statement_lines.snap @@ -11,10 +11,8 @@ F401 [*] `foo1` imported but unused | help: Remove unused import: `foo1` | -1 | if True: - - import foo1; x = 1 +2 - import foo1; x = 1 2 + x = 1 -3 | import foo2; x = 1 | F401 [*] `foo2` imported but unused @@ -29,10 +27,8 @@ F401 [*] `foo2` imported but unused | help: Remove unused import: `foo2` | -2 | import foo1; x = 1 - - import foo2; x = 1 +3 - import foo2; x = 1 3 + x = 1 -4 | | F401 [*] `foo3` imported but unused @@ -45,11 +41,8 @@ F401 [*] `foo3` imported but unused | help: Remove unused import: `foo3` | -5 | if True: - - import foo3; \ - - x = 1 -6 + x = 1 -7 | +6 - import foo3; \ +7 - x = 1 | F401 [*] `foo4` imported but unused @@ -62,11 +55,9 @@ F401 [*] `foo4` imported but unused | help: Remove unused import: `foo4` | -9 | if True: - - import foo4 \ - - ; x = 1 +10 - import foo4 \ +11 - ; x = 1 10 + x = 1 -11 | | F401 [*] `foo5` imported but unused @@ -77,10 +68,8 @@ F401 [*] `foo5` imported but unused | ^^^^ help: Remove unused import: `foo5` | -13 | if True: - - x = 1; import foo5 +14 - x = 1; import foo5 14 + x = 1; -15 | | F401 [*] `foo6` imported but unused @@ -95,11 +84,9 @@ F401 [*] `foo6` imported but unused | help: Remove unused import: `foo6` | -17 | if True: - - x = 1; \ - - import foo6 +18 - x = 1; \ +19 - import foo6 18 + x = 1; -19 | | F401 [*] `foo7` imported but unused @@ -114,10 +101,8 @@ F401 [*] `foo7` imported but unused | help: Remove unused import: `foo7` | -22 | x = 1 \ - - ; import foo7 +23 - ; import foo7 23 + ; -24 | | F401 [*] `foo8` imported but unused @@ -130,10 +115,8 @@ F401 [*] `foo8` imported but unused | help: Remove unused import: `foo8` | -25 | if True: - - x = 1; import foo8; x = 1 +26 - x = 1; import foo8; x = 1 26 + x = 1; x = 1 -27 | x = 1; import foo9; x = 1 | F401 [*] `foo9` imported but unused @@ -148,10 +131,8 @@ F401 [*] `foo9` imported but unused | help: Remove unused import: `foo9` | -26 | x = 1; import foo8; x = 1 - - x = 1; import foo9; x = 1 +27 - x = 1; import foo9; x = 1 27 + x = 1; x = 1 -28 | | F401 [*] `foo10` imported but unused @@ -165,11 +146,9 @@ F401 [*] `foo10` imported but unused | help: Remove unused import: `foo10` | -30 | x = 1; \ - - import foo10; \ - - x = 1 +31 - import foo10; \ +32 - x = 1 31 + x = 1 -32 | | F401 [*] `foo11` imported but unused @@ -183,9 +162,7 @@ F401 [*] `foo11` imported but unused | help: Remove unused import: `foo11` | -35 | x = 1 \ - - ;import foo11 \ -36 | ;x = 1 +36 - ;import foo11 \ | F401 [*] `foo12` imported but unused @@ -200,12 +177,10 @@ F401 [*] `foo12` imported but unused | help: Remove unused import: `foo12` | -39 | if True: - - x = 1; \ - - \ - - import foo12 +40 - x = 1; \ +41 - \ +42 - import foo12 40 + x = 1; -41 | | F401 [*] `foo13` imported but unused @@ -217,12 +192,10 @@ F401 [*] `foo13` imported but unused | ^^^^^ help: Remove unused import: `foo13` | -44 | if True: - - x = 1; \ - - \ - - import foo13 +45 - x = 1; \ +46 - \ +47 - import foo13 45 + x = 1; -46 | | F401 [*] `foo14` imported but unused @@ -237,9 +210,7 @@ F401 [*] `foo14` imported but unused | help: Remove unused import: `foo14` | -52 | # \ - - import foo14 -53 | +53 - import foo14 | F401 [*] `foo15` imported but unused @@ -254,11 +225,9 @@ F401 [*] `foo15` imported but unused | help: Remove unused import: `foo15` | -55 | # Continuation, but not as the last content in the file. - - x = 1; \ - - import foo15 +56 - x = 1; \ +57 - import foo15 56 + x = 1; -57 | | F401 [*] `foo16` imported but unused @@ -270,8 +239,7 @@ F401 [*] `foo16` imported but unused | ^^^^^ help: Remove unused import: `foo16` | -60 | # error.) - - x = 1; \ - - import foo16 +61 - x = 1; \ +62 - import foo16 61 + x = 1; | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401_F401_24____init__.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401_F401_24____init__.py.snap index b5dc23d607b5c..1d3e0ffd35fff 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401_F401_24____init__.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401_F401_24____init__.py.snap @@ -8,9 +8,7 @@ F401 [*] `sys` imported but unused | ^^^ help: Remove unused import: `sys` | -18 | - - import sys # F401: remove unused -19 | +19 - import sys # F401: remove unused | note: This is an unsafe fix and may change runtime behavior @@ -21,11 +19,8 @@ F401 [*] `.unused` imported but unused; consider removing, adding to `__all__`, | ^^^^^^ help: Use an explicit re-export: `unused as unused` | -32 | - - from . import unused # F401: change to redundant alias -33 + from . import unused as unused # F401: change to redundant alias -34 | - | +33 | from . import unused as unused # F401: change to redundant alias + | +++++++++ F401 `.renamed` imported but unused; consider removing, adding to `__all__`, or using a redundant alias --> __init__.py:36:26 diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401_F401_25__all_nonempty____init__.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401_F401_25__all_nonempty____init__.py.snap index 23c50e1af716d..4dc39d70cc5f7 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401_F401_25__all_nonempty____init__.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401_F401_25__all_nonempty____init__.py.snap @@ -8,9 +8,7 @@ F401 [*] `sys` imported but unused | ^^^ help: Remove unused import: `sys` | -18 | - - import sys # F401: remove unused -19 | +19 - import sys # F401: remove unused | note: This is an unsafe fix and may change runtime behavior @@ -21,10 +19,8 @@ F401 [*] `.unused` imported but unused; consider removing, adding to `__all__`, | ^^^^^^ help: Add unused import `unused` to __all__ | -41 | - - __all__ = ["argparse", "exported"] -42 + __all__ = ["argparse", "exported", "unused"] - | +42 | __all__ = ["argparse", "exported", "unused"] + | ++++++++++ F401 [*] `.renamed` imported but unused; consider removing, adding to `__all__`, or using a redundant alias --> __init__.py:39:26 @@ -33,7 +29,5 @@ F401 [*] `.renamed` imported but unused; consider removing, adding to `__all__`, | ^^^^ help: Add unused import `bees` to __all__ | -41 | - - __all__ = ["argparse", "exported"] -42 + __all__ = ["argparse", "exported", "bees"] - | +42 | __all__ = ["argparse", "exported", "bees"] + | ++++++++ diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401_F401_26__all_empty____init__.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401_F401_26__all_empty____init__.py.snap index 83b777d7788e3..1efc5de6dd0ef 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401_F401_26__all_empty____init__.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401_F401_26__all_empty____init__.py.snap @@ -8,10 +8,8 @@ F401 [*] `.unused` imported but unused; consider removing, adding to `__all__`, | ^^^^^^ help: Add unused import `unused` to __all__ | -10 | - - __all__ = [] -11 + __all__ = ["unused"] - | +11 | __all__ = ["unused"] + | ++++++++ F401 [*] `.renamed` imported but unused; consider removing, adding to `__all__`, or using a redundant alias --> __init__.py:8:26 @@ -20,7 +18,5 @@ F401 [*] `.renamed` imported but unused; consider removing, adding to `__all__`, | ^^^^ help: Add unused import `bees` to __all__ | -10 | - - __all__ = [] -11 + __all__ = ["bees"] - | +11 | __all__ = ["bees"] + | ++++++ diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401_F401_28__all_multiple____init__.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401_F401_28__all_multiple____init__.py.snap index 40f374f67158d..3fd18e5870c45 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401_F401_28__all_multiple____init__.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401_F401_28__all_multiple____init__.py.snap @@ -8,10 +8,8 @@ F401 [*] `.unused` imported but unused; consider removing, adding to `__all__`, | ^^^^^^ help: Add unused import `unused` to __all__ | -7 | - - __all__ = []; -8 + __all__ = ["bees", "unused"]; - | +8 | __all__ = ["bees", "unused"]; + | ++++++++++++++++ F401 [*] `.renamed` imported but unused; consider removing, adding to `__all__`, or using a redundant alias --> __init__.py:5:34 @@ -20,7 +18,5 @@ F401 [*] `.renamed` imported but unused; consider removing, adding to `__all__`, | ^^^^ help: Add unused import `bees` to __all__ | -7 | - - __all__ = []; -8 + __all__ = ["bees", "unused"]; - | +8 | __all__ = ["bees", "unused"]; + | ++++++++++++++++ diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401_F401_33____init__.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401_F401_33____init__.py.snap index 683e0d1da5f01..46a0efe220c6f 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401_F401_33____init__.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401_F401_33____init__.py.snap @@ -10,8 +10,7 @@ F401 [*] `F401_33.other.Ham` imported but unused | ^^^ help: Remove unused import: `F401_33.other.Ham` | -7 | def __init__(self) -> None: - - from F401_33.other import Ham +8 - from F401_33.other import Ham 8 + pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401___init__.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401___init__.py.snap index 79afd809d5900..db19a8cb994c4 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401___init__.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F401___init__.py.snap @@ -11,7 +11,6 @@ F401 [*] `os` imported but unused | help: Remove unused import: `os` | - - import os -1 | +1 - import os | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F811_F811_36.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F811_F811_36.py.snap index c9d5172c65193..dc31e0f58b1c3 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F811_F811_36.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview__F811_F811_36.py.snap @@ -17,7 +17,5 @@ F811 [*] Redefinition of unused `BrokerUsecase` from line 2 | help: Remove definition: `BrokerUsecase` | -6 | # should detect -------------------------vvvvvvvvvvvvv - - from faststream._internal.broker import BrokerUsecase -7 | from faststream.specification.schema import Contact, License +7 - from faststream._internal.broker import BrokerUsecase | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview_diff__F401_0.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview_diff__F401_0.py.snap index da79720133111..a816d7b299104 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview_diff__F401_0.py.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__preview_diff__F401_0.py.snap @@ -22,9 +22,7 @@ F401 [*] `multiprocessing.process` imported but unused | help: Remove unused import: `multiprocessing.process` | -9 | import multiprocessing.pool - - import multiprocessing.process -10 | import logging.config +10 - import multiprocessing.process | @@ -40,7 +38,5 @@ F401 [*] `logging.config` imported but unused | help: Remove unused import: `logging.config` | -10 | import multiprocessing.process - - import logging.config -11 | import logging.handlers +11 - import logging.config | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__print_in_body_after_double_shadowing_except.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__print_in_body_after_double_shadowing_except.snap index 828b9260b93ed..cd19a7d617f27 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__print_in_body_after_double_shadowing_except.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__print_in_body_after_double_shadowing_except.snap @@ -13,10 +13,8 @@ F841 [*] Local variable `x` is assigned to but never used | help: Remove assignment to unused variable `x` | -6 | 1 / 0 - - except ValueError as x: +7 - except ValueError as x: 7 + except ValueError: -8 | pass | F841 [*] Local variable `x` is assigned to but never used @@ -29,9 +27,7 @@ F841 [*] Local variable `x` is assigned to but never used 10 | pass | help: Remove assignment to unused variable `x` - | -8 | pass - - except ImportError as x: -9 + except ImportError: -10 | pass - | + | +9 - except ImportError as x: +9 + except ImportError: + | diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__print_in_body_after_shadowing_except.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__print_in_body_after_shadowing_except.snap index a8974998e6361..ef2d7168e9530 100644 --- a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__print_in_body_after_shadowing_except.snap +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__print_in_body_after_shadowing_except.snap @@ -12,8 +12,6 @@ F841 [*] Local variable `x` is assigned to but never used | help: Remove assignment to unused variable `x` | -6 | 1 / 0 - - except Exception as x: +7 - except Exception as x: 7 + except Exception: -8 | pass | diff --git a/crates/ruff_linter/src/rules/pygrep_hooks/snapshots/ruff_linter__rules__pygrep_hooks__tests__PGH004_PGH004_0.py.snap b/crates/ruff_linter/src/rules/pygrep_hooks/snapshots/ruff_linter__rules__pygrep_hooks__tests__PGH004_PGH004_0.py.snap index ef176e3bd0761..86607be0869c9 100644 --- a/crates/ruff_linter/src/rules/pygrep_hooks/snapshots/ruff_linter__rules__pygrep_hooks__tests__PGH004_PGH004_0.py.snap +++ b/crates/ruff_linter/src/rules/pygrep_hooks/snapshots/ruff_linter__rules__pygrep_hooks__tests__PGH004_PGH004_0.py.snap @@ -43,11 +43,8 @@ PGH004 [*] Use a colon when specifying `noqa` rule codes | help: Add missing colon | -17 | # PGH004 - - x = 2 # noqa X100 -18 + x = 2 # noqa: X100 -19 | - | +18 | x = 2 # noqa: X100 + | + note: This is an unsafe fix and may change runtime behavior PGH004 [*] Use a colon when specifying `noqa` rule codes @@ -61,9 +58,6 @@ PGH004 [*] Use a colon when specifying `noqa` rule codes | help: Add missing colon | -20 | # PGH004 - - x = 2 # noqa X100, X200 -21 + x = 2 # noqa: X100, X200 -22 | - | +21 | x = 2 # noqa: X100, X200 + | + note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLC0207_missing_maxsplit_arg.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLC0207_missing_maxsplit_arg.py.snap index 9909ef3078a4a..d3999ee761fc6 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLC0207_missing_maxsplit_arg.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLC0207_missing_maxsplit_arg.py.snap @@ -13,11 +13,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.split()` | -13 | ## Test split called directly on string literal - - "1,2,3".split(",")[0] # [missing-maxsplit-arg] -14 + "1,2,3".split(",", maxsplit=1)[0] # [missing-maxsplit-arg] -15 | "1,2,3".split(",")[-1] # [missing-maxsplit-arg] - | +14 | "1,2,3".split(",", maxsplit=1)[0] # [missing-maxsplit-arg] + | ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:15:1 @@ -31,11 +28,8 @@ PLC0207 [*] String is split more times than necessary | help: Use `str.rsplit()` and pass `maxsplit=1` | -14 | "1,2,3".split(",")[0] # [missing-maxsplit-arg] - - "1,2,3".split(",")[-1] # [missing-maxsplit-arg] -15 + "1,2,3".rsplit(",", maxsplit=1)[-1] # [missing-maxsplit-arg] -16 | "1,2,3".rsplit(",")[0] # [missing-maxsplit-arg] - | +15 | "1,2,3".rsplit(",", maxsplit=1)[-1] # [missing-maxsplit-arg] + | + ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:16:1 @@ -48,10 +42,8 @@ PLC0207 [*] String is split more times than necessary | help: Use `str.split()` and pass `maxsplit=1` | -15 | "1,2,3".split(",")[-1] # [missing-maxsplit-arg] - - "1,2,3".rsplit(",")[0] # [missing-maxsplit-arg] +16 - "1,2,3".rsplit(",")[0] # [missing-maxsplit-arg] 16 + "1,2,3".split(",", maxsplit=1)[0] # [missing-maxsplit-arg] -17 | "1,2,3".rsplit(",")[-1] # [missing-maxsplit-arg] | PLC0207 [*] String is split more times than necessary @@ -66,11 +58,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.rsplit()` | -16 | "1,2,3".rsplit(",")[0] # [missing-maxsplit-arg] - - "1,2,3".rsplit(",")[-1] # [missing-maxsplit-arg] -17 + "1,2,3".rsplit(",", maxsplit=1)[-1] # [missing-maxsplit-arg] -18 | - | +17 | "1,2,3".rsplit(",", maxsplit=1)[-1] # [missing-maxsplit-arg] + | ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:20:1 @@ -83,11 +72,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.split()` | -19 | ## Test split called on string variable - - SEQ.split(",")[0] # [missing-maxsplit-arg] -20 + SEQ.split(",", maxsplit=1)[0] # [missing-maxsplit-arg] -21 | SEQ.split(",")[-1] # [missing-maxsplit-arg] - | +20 | SEQ.split(",", maxsplit=1)[0] # [missing-maxsplit-arg] + | ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:21:1 @@ -101,11 +87,8 @@ PLC0207 [*] String is split more times than necessary | help: Use `str.rsplit()` and pass `maxsplit=1` | -20 | SEQ.split(",")[0] # [missing-maxsplit-arg] - - SEQ.split(",")[-1] # [missing-maxsplit-arg] -21 + SEQ.rsplit(",", maxsplit=1)[-1] # [missing-maxsplit-arg] -22 | SEQ.rsplit(",")[0] # [missing-maxsplit-arg] - | +21 | SEQ.rsplit(",", maxsplit=1)[-1] # [missing-maxsplit-arg] + | + ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:22:1 @@ -118,10 +101,8 @@ PLC0207 [*] String is split more times than necessary | help: Use `str.split()` and pass `maxsplit=1` | -21 | SEQ.split(",")[-1] # [missing-maxsplit-arg] - - SEQ.rsplit(",")[0] # [missing-maxsplit-arg] +22 - SEQ.rsplit(",")[0] # [missing-maxsplit-arg] 22 + SEQ.split(",", maxsplit=1)[0] # [missing-maxsplit-arg] -23 | SEQ.rsplit(",")[-1] # [missing-maxsplit-arg] | PLC0207 [*] String is split more times than necessary @@ -136,11 +117,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.rsplit()` | -22 | SEQ.rsplit(",")[0] # [missing-maxsplit-arg] - - SEQ.rsplit(",")[-1] # [missing-maxsplit-arg] -23 + SEQ.rsplit(",", maxsplit=1)[-1] # [missing-maxsplit-arg] -24 | - | +23 | SEQ.rsplit(",", maxsplit=1)[-1] # [missing-maxsplit-arg] + | ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:26:1 @@ -153,11 +131,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.split()` | -25 | ## Test split called on class attribute - - Foo.class_str.split(",")[0] # [missing-maxsplit-arg] -26 + Foo.class_str.split(",", maxsplit=1)[0] # [missing-maxsplit-arg] -27 | Foo.class_str.split(",")[-1] # [missing-maxsplit-arg] - | +26 | Foo.class_str.split(",", maxsplit=1)[0] # [missing-maxsplit-arg] + | ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:27:1 @@ -171,11 +146,8 @@ PLC0207 [*] String is split more times than necessary | help: Use `str.rsplit()` and pass `maxsplit=1` | -26 | Foo.class_str.split(",")[0] # [missing-maxsplit-arg] - - Foo.class_str.split(",")[-1] # [missing-maxsplit-arg] -27 + Foo.class_str.rsplit(",", maxsplit=1)[-1] # [missing-maxsplit-arg] -28 | Foo.class_str.rsplit(",")[0] # [missing-maxsplit-arg] - | +27 | Foo.class_str.rsplit(",", maxsplit=1)[-1] # [missing-maxsplit-arg] + | + ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:28:1 @@ -188,10 +160,8 @@ PLC0207 [*] String is split more times than necessary | help: Use `str.split()` and pass `maxsplit=1` | -27 | Foo.class_str.split(",")[-1] # [missing-maxsplit-arg] - - Foo.class_str.rsplit(",")[0] # [missing-maxsplit-arg] +28 - Foo.class_str.rsplit(",")[0] # [missing-maxsplit-arg] 28 + Foo.class_str.split(",", maxsplit=1)[0] # [missing-maxsplit-arg] -29 | Foo.class_str.rsplit(",")[-1] # [missing-maxsplit-arg] | PLC0207 [*] String is split more times than necessary @@ -206,11 +176,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.rsplit()` | -28 | Foo.class_str.rsplit(",")[0] # [missing-maxsplit-arg] - - Foo.class_str.rsplit(",")[-1] # [missing-maxsplit-arg] -29 + Foo.class_str.rsplit(",", maxsplit=1)[-1] # [missing-maxsplit-arg] -30 | - | +29 | Foo.class_str.rsplit(",", maxsplit=1)[-1] # [missing-maxsplit-arg] + | ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:32:1 @@ -223,11 +190,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.split()` | -31 | ## Test split called on sliced string - - "1,2,3"[::-1].split(",")[0] # [missing-maxsplit-arg] -32 + "1,2,3"[::-1].split(",", maxsplit=1)[0] # [missing-maxsplit-arg] -33 | "1,2,3"[::-1][::-1].split(",")[0] # [missing-maxsplit-arg] - | +32 | "1,2,3"[::-1].split(",", maxsplit=1)[0] # [missing-maxsplit-arg] + | ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:33:1 @@ -241,11 +205,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.split()` | -32 | "1,2,3"[::-1].split(",")[0] # [missing-maxsplit-arg] - - "1,2,3"[::-1][::-1].split(",")[0] # [missing-maxsplit-arg] -33 + "1,2,3"[::-1][::-1].split(",", maxsplit=1)[0] # [missing-maxsplit-arg] -34 | SEQ[:3].split(",")[0] # [missing-maxsplit-arg] - | +33 | "1,2,3"[::-1][::-1].split(",", maxsplit=1)[0] # [missing-maxsplit-arg] + | ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:34:1 @@ -259,11 +220,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.split()` | -33 | "1,2,3"[::-1][::-1].split(",")[0] # [missing-maxsplit-arg] - - SEQ[:3].split(",")[0] # [missing-maxsplit-arg] -34 + SEQ[:3].split(",", maxsplit=1)[0] # [missing-maxsplit-arg] -35 | Foo.class_str[1:3].split(",")[-1] # [missing-maxsplit-arg] - | +34 | SEQ[:3].split(",", maxsplit=1)[0] # [missing-maxsplit-arg] + | ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:35:1 @@ -277,11 +235,8 @@ PLC0207 [*] String is split more times than necessary | help: Use `str.rsplit()` and pass `maxsplit=1` | -34 | SEQ[:3].split(",")[0] # [missing-maxsplit-arg] - - Foo.class_str[1:3].split(",")[-1] # [missing-maxsplit-arg] -35 + Foo.class_str[1:3].rsplit(",", maxsplit=1)[-1] # [missing-maxsplit-arg] -36 | "1,2,3"[::-1].rsplit(",")[0] # [missing-maxsplit-arg] - | +35 | Foo.class_str[1:3].rsplit(",", maxsplit=1)[-1] # [missing-maxsplit-arg] + | + ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:36:1 @@ -295,10 +250,8 @@ PLC0207 [*] String is split more times than necessary | help: Use `str.split()` and pass `maxsplit=1` | -35 | Foo.class_str[1:3].split(",")[-1] # [missing-maxsplit-arg] - - "1,2,3"[::-1].rsplit(",")[0] # [missing-maxsplit-arg] +36 - "1,2,3"[::-1].rsplit(",")[0] # [missing-maxsplit-arg] 36 + "1,2,3"[::-1].split(",", maxsplit=1)[0] # [missing-maxsplit-arg] -37 | SEQ[:3].rsplit(",")[0] # [missing-maxsplit-arg] | PLC0207 [*] String is split more times than necessary @@ -312,10 +265,8 @@ PLC0207 [*] String is split more times than necessary | help: Use `str.split()` and pass `maxsplit=1` | -36 | "1,2,3"[::-1].rsplit(",")[0] # [missing-maxsplit-arg] - - SEQ[:3].rsplit(",")[0] # [missing-maxsplit-arg] +37 - SEQ[:3].rsplit(",")[0] # [missing-maxsplit-arg] 37 + SEQ[:3].split(",", maxsplit=1)[0] # [missing-maxsplit-arg] -38 | Foo.class_str[1:3].rsplit(",")[-1] # [missing-maxsplit-arg] | PLC0207 [*] String is split more times than necessary @@ -330,11 +281,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.rsplit()` | -37 | SEQ[:3].rsplit(",")[0] # [missing-maxsplit-arg] - - Foo.class_str[1:3].rsplit(",")[-1] # [missing-maxsplit-arg] -38 + Foo.class_str[1:3].rsplit(",", maxsplit=1)[-1] # [missing-maxsplit-arg] -39 | - | +38 | Foo.class_str[1:3].rsplit(",", maxsplit=1)[-1] # [missing-maxsplit-arg] + | ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:41:1 @@ -347,11 +295,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.split()` | -40 | ## Test sep given as named argument - - "1,2,3".split(sep=",")[0] # [missing-maxsplit-arg] -41 + "1,2,3".split(maxsplit=1, sep=",")[0] # [missing-maxsplit-arg] -42 | "1,2,3".split(sep=",")[-1] # [missing-maxsplit-arg] - | +41 | "1,2,3".split(maxsplit=1, sep=",")[0] # [missing-maxsplit-arg] + | +++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:42:1 @@ -365,11 +310,8 @@ PLC0207 [*] String is split more times than necessary | help: Use `str.rsplit()` and pass `maxsplit=1` | -41 | "1,2,3".split(sep=",")[0] # [missing-maxsplit-arg] - - "1,2,3".split(sep=",")[-1] # [missing-maxsplit-arg] -42 + "1,2,3".rsplit(maxsplit=1, sep=",")[-1] # [missing-maxsplit-arg] -43 | "1,2,3".rsplit(sep=",")[0] # [missing-maxsplit-arg] - | +42 | "1,2,3".rsplit(maxsplit=1, sep=",")[-1] # [missing-maxsplit-arg] + | + +++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:43:1 @@ -382,10 +324,8 @@ PLC0207 [*] String is split more times than necessary | help: Use `str.split()` and pass `maxsplit=1` | -42 | "1,2,3".split(sep=",")[-1] # [missing-maxsplit-arg] - - "1,2,3".rsplit(sep=",")[0] # [missing-maxsplit-arg] +43 - "1,2,3".rsplit(sep=",")[0] # [missing-maxsplit-arg] 43 + "1,2,3".split(maxsplit=1, sep=",")[0] # [missing-maxsplit-arg] -44 | "1,2,3".rsplit(sep=",")[-1] # [missing-maxsplit-arg] | PLC0207 [*] String is split more times than necessary @@ -400,11 +340,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.rsplit()` | -43 | "1,2,3".rsplit(sep=",")[0] # [missing-maxsplit-arg] - - "1,2,3".rsplit(sep=",")[-1] # [missing-maxsplit-arg] -44 + "1,2,3".rsplit(maxsplit=1, sep=",")[-1] # [missing-maxsplit-arg] -45 | - | +44 | "1,2,3".rsplit(maxsplit=1, sep=",")[-1] # [missing-maxsplit-arg] + | +++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:47:1 @@ -417,11 +354,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.split()` | -46 | ## Special cases - - "1,2,3".split("\n")[0] # [missing-maxsplit-arg] -47 + "1,2,3".split("\n", maxsplit=1)[0] # [missing-maxsplit-arg] -48 | "1,2,3".split("split")[-1] # [missing-maxsplit-arg] - | +47 | "1,2,3".split("\n", maxsplit=1)[0] # [missing-maxsplit-arg] + | ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:48:1 @@ -434,11 +368,8 @@ PLC0207 [*] String is split more times than necessary | help: Use `str.rsplit()` and pass `maxsplit=1` | -47 | "1,2,3".split("\n")[0] # [missing-maxsplit-arg] - - "1,2,3".split("split")[-1] # [missing-maxsplit-arg] -48 + "1,2,3".rsplit("split", maxsplit=1)[-1] # [missing-maxsplit-arg] -49 | "1,2,3".rsplit("rsplit")[0] # [missing-maxsplit-arg] - | +48 | "1,2,3".rsplit("split", maxsplit=1)[-1] # [missing-maxsplit-arg] + | + ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:49:1 @@ -452,10 +383,8 @@ PLC0207 [*] String is split more times than necessary | help: Use `str.split()` and pass `maxsplit=1` | -48 | "1,2,3".split("split")[-1] # [missing-maxsplit-arg] - - "1,2,3".rsplit("rsplit")[0] # [missing-maxsplit-arg] +49 - "1,2,3".rsplit("rsplit")[0] # [missing-maxsplit-arg] 49 + "1,2,3".split("rsplit", maxsplit=1)[0] # [missing-maxsplit-arg] -50 | | PLC0207 [*] String is split more times than necessary @@ -469,11 +398,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.split()` | -51 | ## Test class attribute named split - - Bar.split.split(",")[0] # [missing-maxsplit-arg] -52 + Bar.split.split(",", maxsplit=1)[0] # [missing-maxsplit-arg] -53 | Bar.split.split(",")[-1] # [missing-maxsplit-arg] - | +52 | Bar.split.split(",", maxsplit=1)[0] # [missing-maxsplit-arg] + | ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:53:1 @@ -487,11 +413,8 @@ PLC0207 [*] String is split more times than necessary | help: Use `str.rsplit()` and pass `maxsplit=1` | -52 | Bar.split.split(",")[0] # [missing-maxsplit-arg] - - Bar.split.split(",")[-1] # [missing-maxsplit-arg] -53 + Bar.split.rsplit(",", maxsplit=1)[-1] # [missing-maxsplit-arg] -54 | Bar.split.rsplit(",")[0] # [missing-maxsplit-arg] - | +53 | Bar.split.rsplit(",", maxsplit=1)[-1] # [missing-maxsplit-arg] + | + ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:54:1 @@ -504,10 +427,8 @@ PLC0207 [*] String is split more times than necessary | help: Use `str.split()` and pass `maxsplit=1` | -53 | Bar.split.split(",")[-1] # [missing-maxsplit-arg] - - Bar.split.rsplit(",")[0] # [missing-maxsplit-arg] +54 - Bar.split.rsplit(",")[0] # [missing-maxsplit-arg] 54 + Bar.split.split(",", maxsplit=1)[0] # [missing-maxsplit-arg] -55 | Bar.split.rsplit(",")[-1] # [missing-maxsplit-arg] | PLC0207 [*] String is split more times than necessary @@ -522,11 +443,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.rsplit()` | -54 | Bar.split.rsplit(",")[0] # [missing-maxsplit-arg] - - Bar.split.rsplit(",")[-1] # [missing-maxsplit-arg] -55 + Bar.split.rsplit(",", maxsplit=1)[-1] # [missing-maxsplit-arg] -56 | - | +55 | Bar.split.rsplit(",", maxsplit=1)[-1] # [missing-maxsplit-arg] + | ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:58:1 @@ -539,11 +457,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.split()` | -57 | ## Test unpacked dict literal kwargs - - "1,2,3".split(**{"sep": ","})[0] # [missing-maxsplit-arg] -58 + "1,2,3".split(maxsplit=1, **{"sep": ","})[0] # [missing-maxsplit-arg] -59 | - | +58 | "1,2,3".split(maxsplit=1, **{"sep": ","})[0] # [missing-maxsplit-arg] + | +++++++++++ note: This is an unsafe fix and may change runtime behavior PLC0207 [*] String is split more times than necessary @@ -557,11 +472,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.split()` | -60 | ## Test chained splits - - SEQ.split("(")[0].split("[")[0] # [missing-maxsplit-arg] -61 + SEQ.split("(", maxsplit=1)[0].split("[")[0] # [missing-maxsplit-arg] -62 | SEQ.split("(")[0].split("[")[-1] # [missing-maxsplit-arg] - | +61 | SEQ.split("(", maxsplit=1)[0].split("[")[0] # [missing-maxsplit-arg] + | ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:61:1 @@ -574,11 +486,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.split()` | -60 | ## Test chained splits - - SEQ.split("(")[0].split("[")[0] # [missing-maxsplit-arg] -61 + SEQ.split("(")[0].split("[", maxsplit=1)[0] # [missing-maxsplit-arg] -62 | SEQ.split("(")[0].split("[")[-1] # [missing-maxsplit-arg] - | +61 | SEQ.split("(")[0].split("[", maxsplit=1)[0] # [missing-maxsplit-arg] + | ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:62:1 @@ -591,11 +500,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.split()` | -61 | SEQ.split("(")[0].split("[")[0] # [missing-maxsplit-arg] - - SEQ.split("(")[0].split("[")[-1] # [missing-maxsplit-arg] -62 + SEQ.split("(", maxsplit=1)[0].split("[")[-1] # [missing-maxsplit-arg] -63 | SEQ.split("(")[0].split("[")[0].split(".")[-1] # [missing-maxsplit-arg] - | +62 | SEQ.split("(", maxsplit=1)[0].split("[")[-1] # [missing-maxsplit-arg] + | ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:62:1 @@ -608,11 +514,8 @@ PLC0207 [*] String is split more times than necessary | help: Use `str.rsplit()` and pass `maxsplit=1` | -61 | SEQ.split("(")[0].split("[")[0] # [missing-maxsplit-arg] - - SEQ.split("(")[0].split("[")[-1] # [missing-maxsplit-arg] -62 + SEQ.split("(")[0].rsplit("[", maxsplit=1)[-1] # [missing-maxsplit-arg] -63 | SEQ.split("(")[0].split("[")[0].split(".")[-1] # [missing-maxsplit-arg] - | +62 | SEQ.split("(")[0].rsplit("[", maxsplit=1)[-1] # [missing-maxsplit-arg] + | + ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:63:1 @@ -623,11 +526,8 @@ PLC0207 [*] String is split more times than necessary | ^^^^^^^^^^^^^^^^^ help: Pass `maxsplit=1` into `str.split()` | -62 | SEQ.split("(")[0].split("[")[-1] # [missing-maxsplit-arg] - - SEQ.split("(")[0].split("[")[0].split(".")[-1] # [missing-maxsplit-arg] -63 + SEQ.split("(", maxsplit=1)[0].split("[")[0].split(".")[-1] # [missing-maxsplit-arg] -64 | - | +63 | SEQ.split("(", maxsplit=1)[0].split("[")[0].split(".")[-1] # [missing-maxsplit-arg] + | ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:63:1 @@ -638,11 +538,8 @@ PLC0207 [*] String is split more times than necessary | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Pass `maxsplit=1` into `str.split()` | -62 | SEQ.split("(")[0].split("[")[-1] # [missing-maxsplit-arg] - - SEQ.split("(")[0].split("[")[0].split(".")[-1] # [missing-maxsplit-arg] -63 + SEQ.split("(")[0].split("[", maxsplit=1)[0].split(".")[-1] # [missing-maxsplit-arg] -64 | - | +63 | SEQ.split("(")[0].split("[", maxsplit=1)[0].split(".")[-1] # [missing-maxsplit-arg] + | ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:63:1 @@ -653,11 +550,8 @@ PLC0207 [*] String is split more times than necessary | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use `str.rsplit()` and pass `maxsplit=1` | -62 | SEQ.split("(")[0].split("[")[-1] # [missing-maxsplit-arg] - - SEQ.split("(")[0].split("[")[0].split(".")[-1] # [missing-maxsplit-arg] -63 + SEQ.split("(")[0].split("[")[0].rsplit(".", maxsplit=1)[-1] # [missing-maxsplit-arg] -64 | - | +63 | SEQ.split("(")[0].split("[")[0].rsplit(".", maxsplit=1)[-1] # [missing-maxsplit-arg] + | + ++++++++++++ PLC0207 [*] String is split more times than necessary --> missing_maxsplit_arg.py:184:1 @@ -671,11 +565,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.split()` | -183 | kwargs_without_maxsplit = {"seq": ","} - - "1,2,3".split(**kwargs_without_maxsplit)[0] # TODO: [missing-maxsplit-arg] -184 + "1,2,3".split(maxsplit=1, **kwargs_without_maxsplit)[0] # TODO: [missing-maxsplit-arg] -185 | # OK - | +184 | "1,2,3".split(maxsplit=1, **kwargs_without_maxsplit)[0] # TODO: [missing-maxsplit-arg] + | +++++++++++ note: This is an unsafe fix and may change runtime behavior PLC0207 [*] String is split more times than necessary @@ -690,11 +581,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.split()` | -186 | kwargs_with_maxsplit = {"maxsplit": 1} - - "1,2,3".split(",", **kwargs_with_maxsplit)[0] # TODO: false positive -187 + "1,2,3".split(",", maxsplit=1, **kwargs_with_maxsplit)[0] # TODO: false positive -188 | kwargs_with_maxsplit = {"sep": ",", "maxsplit": 1} - | +187 | "1,2,3".split(",", maxsplit=1, **kwargs_with_maxsplit)[0] # TODO: false positive + | +++++++++++ note: This is an unsafe fix and may change runtime behavior PLC0207 [*] String is split more times than necessary @@ -706,11 +594,8 @@ PLC0207 [*] String is split more times than necessary | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Pass `maxsplit=1` into `str.split()` | -188 | kwargs_with_maxsplit = {"sep": ",", "maxsplit": 1} - - "1,2,3".split(**kwargs_with_maxsplit)[0] # TODO: false positive -189 + "1,2,3".split(maxsplit=1, **kwargs_with_maxsplit)[0] # TODO: false positive -190 | - | +189 | "1,2,3".split(maxsplit=1, **kwargs_with_maxsplit)[0] # TODO: false positive + | +++++++++++ note: This is an unsafe fix and may change runtime behavior PLC0207 [*] String is split more times than necessary @@ -725,11 +610,8 @@ PLC0207 [*] String is split more times than necessary | help: Pass `maxsplit=1` into `str.split()` | -193 | # Errors - - "1,2,3".split(",", *[-1])[0] -194 + "1,2,3".split(",", *[-1], maxsplit=1)[0] -195 | - | +194 | "1,2,3".split(",", *[-1], maxsplit=1)[0] + | ++++++++++++ note: This is an unsafe fix and may change runtime behavior PLC0207 [*] String is split more times than necessary @@ -741,8 +623,6 @@ PLC0207 [*] String is split more times than necessary | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Pass `maxsplit=1` into `str.split()` | -198 | args_list = [-1] - - "1,2,3".split(",", *args_list)[0] -199 + "1,2,3".split(",", *args_list, maxsplit=1)[0] - | +199 | "1,2,3".split(",", *args_list, maxsplit=1)[0] + | ++++++++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLC0208_iteration_over_set.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLC0208_iteration_over_set.py.snap index b84dcad2aaa9d..575864386489b 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLC0208_iteration_over_set.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLC0208_iteration_over_set.py.snap @@ -12,10 +12,8 @@ PLC0208 [*] Use a sequence type instead of a `set` when iterating over values | help: Convert to `tuple` | -2 | - - for item in {1}: +3 - for item in {1}: 3 + for item in (1,): -4 | print(f"I can count to {item}!") | PLC0208 [*] Use a sequence type instead of a `set` when iterating over values @@ -29,10 +27,8 @@ PLC0208 [*] Use a sequence type instead of a `set` when iterating over values | help: Convert to `tuple` | -5 | - - for item in {"apples", "lemons", "water"}: # flags in-line set literals +6 - for item in {"apples", "lemons", "water"}: # flags in-line set literals 6 + for item in ("apples", "lemons", "water"): # flags in-line set literals -7 | print(f"I like {item}.") | PLC0208 [*] Use a sequence type instead of a `set` when iterating over values @@ -45,12 +41,10 @@ PLC0208 [*] Use a sequence type instead of a `set` when iterating over values 10 | print(f"I can count to {item}!") | help: Convert to `tuple` - | -8 | - - for item in {1,}: -9 + for item in (1,): -10 | print(f"I can count to {item}!") - | + | +9 - for item in {1,}: +9 + for item in (1,): + | PLC0208 [*] Use a sequence type instead of a `set` when iterating over values --> iteration_over_set.py:12:13 @@ -66,13 +60,9 @@ PLC0208 [*] Use a sequence type instead of a `set` when iterating over values | help: Convert to `tuple` | -11 | - - for item in { -12 + for item in ( -13 | "apples", "lemons", "water" - - }: # flags in-line set literals -14 + ): # flags in-line set literals -15 | print(f"I like {item}.") +12 ~ for item in ( +13 + "apples", "lemons", "water" +14 ~ ): # flags in-line set literals | PLC0208 [*] Use a sequence type instead of a `set` when iterating over values @@ -87,10 +77,8 @@ PLC0208 [*] Use a sequence type instead of a `set` when iterating over values | help: Convert to `tuple` | -16 | - - numbers_list = [i for i in {1, 2, 3}] # flags sets in list comprehensions +17 - numbers_list = [i for i in {1, 2, 3}] # flags sets in list comprehensions 17 + numbers_list = [i for i in (1, 2, 3)] # flags sets in list comprehensions -18 | | PLC0208 [*] Use a sequence type instead of a `set` when iterating over values @@ -105,10 +93,8 @@ PLC0208 [*] Use a sequence type instead of a `set` when iterating over values | help: Convert to `tuple` | -18 | - - numbers_set = {i for i in {1, 2, 3}} # flags sets in set comprehensions +19 - numbers_set = {i for i in {1, 2, 3}} # flags sets in set comprehensions 19 + numbers_set = {i for i in (1, 2, 3)} # flags sets in set comprehensions -20 | | PLC0208 [*] Use a sequence type instead of a `set` when iterating over values @@ -123,10 +109,8 @@ PLC0208 [*] Use a sequence type instead of a `set` when iterating over values | help: Convert to `tuple` | -20 | - - numbers_dict = {str(i): i for i in {1, 2, 3}} # flags sets in dict comprehensions +21 - numbers_dict = {str(i): i for i in {1, 2, 3}} # flags sets in dict comprehensions 21 + numbers_dict = {str(i): i for i in (1, 2, 3)} # flags sets in dict comprehensions -22 | | PLC0208 [*] Use a sequence type instead of a `set` when iterating over values @@ -141,8 +125,6 @@ PLC0208 [*] Use a sequence type instead of a `set` when iterating over values | help: Convert to `tuple` | -22 | - - numbers_gen = (i for i in {1, 2, 3}) # flags sets in generator expressions +23 - numbers_gen = (i for i in {1, 2, 3}) # flags sets in generator expressions 23 + numbers_gen = (i for i in (1, 2, 3)) # flags sets in generator expressions -24 | | diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLC0414_import_aliasing.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLC0414_import_aliasing.py.snap index 49e4185dcafce..569eb69fc0d6c 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLC0414_import_aliasing.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLC0414_import_aliasing.py.snap @@ -13,10 +13,8 @@ PLC0414 [*] Import alias does not rename original package | help: Remove import alias | -5 | - - import collections as collections # [useless-import-alias] +6 - import collections as collections # [useless-import-alias] 6 + import collections # [useless-import-alias] -7 | from collections import OrderedDict as OrderedDict # [useless-import-alias] | note: This is an unsafe fix and may change runtime behavior @@ -31,10 +29,8 @@ PLC0414 [*] Import alias does not rename original package | help: Remove import alias | -6 | import collections as collections # [useless-import-alias] - - from collections import OrderedDict as OrderedDict # [useless-import-alias] +7 - from collections import OrderedDict as OrderedDict # [useless-import-alias] 7 + from collections import OrderedDict # [useless-import-alias] -8 | from collections import OrderedDict as o_dict | note: This is an unsafe fix and may change runtime behavior @@ -50,10 +46,8 @@ PLC0414 [*] Import alias does not rename original package | help: Remove import alias | -15 | from sys import version - - from . import bar as bar # [useless-import-alias] +16 - from . import bar as bar # [useless-import-alias] 16 + from . import bar # [useless-import-alias] -17 | from . import bar as Bar | note: This is an unsafe fix and may change runtime behavior @@ -69,10 +63,8 @@ PLC0414 [*] Import alias does not rename original package | help: Remove import alias | -18 | from . import bar - - from ..foo import bar as bar # [useless-import-alias] +19 - from ..foo import bar as bar # [useless-import-alias] 19 + from ..foo import bar # [useless-import-alias] -20 | from ..foo.bar import foobar as foobar # [useless-import-alias] | note: This is an unsafe fix and may change runtime behavior @@ -88,10 +80,8 @@ PLC0414 [*] Import alias does not rename original package | help: Remove import alias | -19 | from ..foo import bar as bar # [useless-import-alias] - - from ..foo.bar import foobar as foobar # [useless-import-alias] +20 - from ..foo.bar import foobar as foobar # [useless-import-alias] 20 + from ..foo.bar import foobar # [useless-import-alias] -21 | from ..foo.bar import foobar as anotherfoobar | note: This is an unsafe fix and may change runtime behavior @@ -107,10 +97,8 @@ PLC0414 [*] Import alias does not rename original package | help: Remove import alias | -21 | from ..foo.bar import foobar as anotherfoobar - - from . import foo as foo, foo2 as bar2 # [useless-import-alias] +22 - from . import foo as foo, foo2 as bar2 # [useless-import-alias] 22 + from . import foo, foo2 as bar2 # [useless-import-alias] -23 | from . import foo as bar, foo2 as foo2 # [useless-import-alias] | note: This is an unsafe fix and may change runtime behavior @@ -126,10 +114,8 @@ PLC0414 [*] Import alias does not rename original package | help: Remove import alias | -22 | from . import foo as foo, foo2 as bar2 # [useless-import-alias] - - from . import foo as bar, foo2 as foo2 # [useless-import-alias] +23 - from . import foo as bar, foo2 as foo2 # [useless-import-alias] 23 + from . import foo as bar, foo2 # [useless-import-alias] -24 | from . import foo as bar, foo2 as bar2 | note: This is an unsafe fix and may change runtime behavior @@ -145,9 +131,7 @@ PLC0414 [*] Import alias does not rename original package | help: Remove import alias | -24 | from . import foo as bar, foo2 as bar2 - - from foo.bar import foobar as foobar # [useless-import-alias] +25 - from foo.bar import foobar as foobar # [useless-import-alias] 25 + from foo.bar import foobar # [useless-import-alias] -26 | from foo.bar import foobar as foo | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLC1802_len_as_condition.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLC1802_len_as_condition.py.snap index ce9ddb0d29175..316a970f6f580 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLC1802_len_as_condition.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLC1802_len_as_condition.py.snap @@ -10,9 +10,8 @@ PLC1802 [*] `len('TEST')` used as condition without comparison | help: Remove `len` | - - if len('TEST'): # [PLC1802] +1 - if len('TEST'): # [PLC1802] 1 + if 'TEST': # [PLC1802] -2 | pass | PLC1802 [*] `len('TEST')` used as condition without comparison @@ -26,10 +25,8 @@ PLC1802 [*] `len('TEST')` used as condition without comparison | help: Remove `len` | -3 | - - if not len('TEST'): # [PLC1802] +4 - if not len('TEST'): # [PLC1802] 4 + if not 'TEST': # [PLC1802] -5 | pass | PLC1802 [*] `len(['T', 'E', 'S', 'T'])` used as condition without comparison @@ -42,10 +39,8 @@ PLC1802 [*] `len(['T', 'E', 'S', 'T'])` used as condition without comparison | help: Remove `len` | -7 | z = [] - - if z and len(['T', 'E', 'S', 'T']): # [PLC1802] +8 - if z and len(['T', 'E', 'S', 'T']): # [PLC1802] 8 + if z and ['T', 'E', 'S', 'T']: # [PLC1802] -9 | pass | PLC1802 [*] `len('TEST')` used as condition without comparison @@ -59,10 +54,8 @@ PLC1802 [*] `len('TEST')` used as condition without comparison | help: Remove `len` | -10 | - - if True or len('TEST'): # [PLC1802] +11 - if True or len('TEST'): # [PLC1802] 11 + if True or 'TEST': # [PLC1802] -12 | pass | PLC1802 [*] `len('TEST')` used as condition without comparison @@ -76,10 +69,8 @@ PLC1802 [*] `len('TEST')` used as condition without comparison | help: Remove `len` | -52 | pass - - elif len('TEST'): # [PLC1802] +53 - elif len('TEST'): # [PLC1802] 53 + elif 'TEST': # [PLC1802] -54 | pass | PLC1802 [*] `len('TEST')` used as condition without comparison @@ -93,10 +84,8 @@ PLC1802 [*] `len('TEST')` used as condition without comparison | help: Remove `len` | -57 | pass - - elif not len('TEST'): # [PLC1802] +58 - elif not len('TEST'): # [PLC1802] 58 + elif not 'TEST': # [PLC1802] -59 | pass | PLC1802 [*] `len('TEST')` used as condition without comparison @@ -110,10 +99,8 @@ PLC1802 [*] `len('TEST')` used as condition without comparison | help: Remove `len` | -60 | - - while len('TEST'): # [PLC1802] +61 - while len('TEST'): # [PLC1802] 61 + while 'TEST': # [PLC1802] -62 | pass | PLC1802 [*] `len('TEST')` used as condition without comparison @@ -127,10 +114,8 @@ PLC1802 [*] `len('TEST')` used as condition without comparison | help: Remove `len` | -63 | - - while not len('TEST'): # [PLC1802] +64 - while not len('TEST'): # [PLC1802] 64 + while not 'TEST': # [PLC1802] -65 | pass | PLC1802 [*] `len('TEST')` used as condition without comparison @@ -144,10 +129,8 @@ PLC1802 [*] `len('TEST')` used as condition without comparison | help: Remove `len` | -66 | - - while z and len('TEST'): # [PLC1802] +67 - while z and len('TEST'): # [PLC1802] 67 + while z and 'TEST': # [PLC1802] -68 | pass | PLC1802 [*] `len('TEST')` used as condition without comparison @@ -161,10 +144,8 @@ PLC1802 [*] `len('TEST')` used as condition without comparison | help: Remove `len` | -69 | - - while not len('TEST') and z: # [PLC1802] +70 - while not len('TEST') and z: # [PLC1802] 70 + while not 'TEST' and z: # [PLC1802] -71 | pass | PLC1802 [*] `len(args)` used as condition without comparison @@ -178,10 +159,8 @@ PLC1802 [*] `len(args)` used as condition without comparison | help: Remove `len` | -92 | def github_issue_1331_v2(*args): - - assert len(args), args # [PLC1802] +93 - assert len(args), args # [PLC1802] 93 + assert args, args # [PLC1802] -94 | | PLC1802 [*] `len(args)` used as condition without comparison @@ -195,10 +174,8 @@ PLC1802 [*] `len(args)` used as condition without comparison | help: Remove `len` | -95 | def github_issue_1331_v3(*args): - - assert len(args) or z, args # [PLC1802] +96 - assert len(args) or z, args # [PLC1802] 96 + assert args or z, args # [PLC1802] -97 | | PLC1802 [*] `len(args)` used as condition without comparison @@ -211,12 +188,10 @@ PLC1802 [*] `len(args)` used as condition without comparison 101 | def github_issue_1331_v5(**args): | help: Remove `len` - | -98 | def github_issue_1331_v4(*args): - - assert z and len(args), args # [PLC1802] -99 + assert z and args, args # [PLC1802] -100 | - | + | +99 - assert z and len(args), args # [PLC1802] +99 + assert z and args, args # [PLC1802] + | PLC1802 [*] `len(args)` used as condition without comparison --> len_as_condition.py:102:18 @@ -229,10 +204,8 @@ PLC1802 [*] `len(args)` used as condition without comparison | help: Remove `len` | -101 | def github_issue_1331_v5(**args): - - assert z and len(args), args # [PLC1802] +102 - assert z and len(args), args # [PLC1802] 102 + assert z and args, args # [PLC1802] -103 | | PLC1802 [*] `len(z)` used as condition without comparison @@ -246,10 +219,8 @@ PLC1802 [*] `len(z)` used as condition without comparison | help: Remove `len` | -103 | - - b = bool(len(z)) # [PLC1802] +104 - b = bool(len(z)) # [PLC1802] 104 + b = bool(z) # [PLC1802] -105 | c = bool(len('TEST') or 42) # [PLC1802] | PLC1802 [*] `len('TEST')` used as condition without comparison @@ -263,10 +234,8 @@ PLC1802 [*] `len('TEST')` used as condition without comparison | help: Remove `len` | -104 | b = bool(len(z)) # [PLC1802] - - c = bool(len('TEST') or 42) # [PLC1802] +105 - c = bool(len('TEST') or 42) # [PLC1802] 105 + c = bool('TEST' or 42) # [PLC1802] -106 | | PLC1802 [*] `len(range(0))` used as condition without comparison @@ -281,10 +250,8 @@ PLC1802 [*] `len(range(0))` used as condition without comparison | help: Remove `len` | -125 | assert len(ChildClassWithoutBool()) # unintuitive?, in pylint: [PLC1802] - - assert len(range(0)) # [PLC1802] +126 - assert len(range(0)) # [PLC1802] 126 + assert range(0) # [PLC1802] -127 | assert len([t + 1 for t in []]) # [PLC1802] | PLC1802 [*] `len([t + 1 for t in []])` used as condition without comparison @@ -299,10 +266,8 @@ PLC1802 [*] `len([t + 1 for t in []])` used as condition without comparison | help: Remove `len` | -126 | assert len(range(0)) # [PLC1802] - - assert len([t + 1 for t in []]) # [PLC1802] +127 - assert len([t + 1 for t in []]) # [PLC1802] 127 + assert [t + 1 for t in []] # [PLC1802] -128 | # assert len(u + 1 for u in []) generator has no len | PLC1802 [*] `len({"1":(v + 1) for v in {}})` used as condition without comparison @@ -316,10 +281,8 @@ PLC1802 [*] `len({"1":(v + 1) for v in {}})` used as condition without compariso | help: Remove `len` | -128 | # assert len(u + 1 for u in []) generator has no len - - assert len({"1":(v + 1) for v in {}}) # [PLC1802] +129 - assert len({"1":(v + 1) for v in {}}) # [PLC1802] 129 + assert {"1":(v + 1) for v in {}} # [PLC1802] -130 | assert len(set((w + 1) for w in set())) # [PLC1802] | PLC1802 [*] `len(set((w + 1) for w in set()))` used as condition without comparison @@ -331,10 +294,8 @@ PLC1802 [*] `len(set((w + 1) for w in set()))` used as condition without compari | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove `len` | -129 | assert len({"1":(v + 1) for v in {}}) # [PLC1802] - - assert len(set((w + 1) for w in set())) # [PLC1802] +130 - assert len(set((w + 1) for w in set())) # [PLC1802] 130 + assert set((w + 1) for w in set()) # [PLC1802] -131 | | PLC1802 [*] `len(x)` used as condition without comparison @@ -348,10 +309,8 @@ PLC1802 [*] `len(x)` used as condition without comparison | help: Remove `len` | -192 | x = [4,5,6] - - if len(x): # this should be addressed +193 - if len(x): # this should be addressed 193 + if x: # this should be addressed -194 | print(x) | PLC1802 [*] `len(x)` used as condition without comparison @@ -366,10 +325,8 @@ PLC1802 [*] `len(x)` used as condition without comparison | help: Remove `len` | -199 | x = [4,5,6] - - if len(x): # this should be addressed +200 - if len(x): # this should be addressed 200 + if x: # this should be addressed -201 | print(x) | PLC1802 [*] `len(x)` used as condition without comparison @@ -383,10 +340,8 @@ PLC1802 [*] `len(x)` used as condition without comparison | help: Remove `len` | -213 | return x+1 - - if len(x): # [PLC1802] +214 - if len(x): # [PLC1802] 214 + if x: # [PLC1802] -215 | print(x) | PLC1802 [*] `len(x)` used as condition without comparison @@ -400,10 +355,8 @@ PLC1802 [*] `len(x)` used as condition without comparison | help: Remove `len` | -219 | x = [1, 2, 3] - - if len(x): # this should be addressed +220 - if len(x): # this should be addressed 220 + if x: # this should be addressed -221 | print(x) | PLC1802 [*] `len(x)` used as condition without comparison @@ -417,10 +370,8 @@ PLC1802 [*] `len(x)` used as condition without comparison | help: Remove `len` | -232 | x = [1, 2, 3] - - if len(x): # [PLC1802] should be fine +233 - if len(x): # [PLC1802] should be fine 233 + if x: # [PLC1802] should be fine -234 | print(x) | PLC1802 [*] `len(ascii(1))` used as condition without comparison @@ -433,10 +384,8 @@ PLC1802 [*] `len(ascii(1))` used as condition without comparison | help: Remove `len` | -236 | # regression tests for https://github.com/astral-sh/ruff/issues/14690 - - bool(len(ascii(1))) +237 - bool(len(ascii(1))) 237 + bool(ascii(1)) -238 | bool(len(sorted(""))) | PLC1802 [*] `len(sorted(""))` used as condition without comparison @@ -451,10 +400,8 @@ PLC1802 [*] `len(sorted(""))` used as condition without comparison | help: Remove `len` | -237 | bool(len(ascii(1))) - - bool(len(sorted(""))) +238 - bool(len(sorted(""))) 238 + bool(sorted("")) -239 | | PLC1802 [*] `len(fruits)` used as condition without comparison @@ -468,10 +415,8 @@ PLC1802 [*] `len(fruits)` used as condition without comparison | help: Remove `len` | -241 | fruits = [] - - if(len)(fruits): +242 - if(len)(fruits): 242 + if fruits: -243 | ... | PLC1802 [*] `len(fruits)` used as condition without comparison @@ -488,11 +433,9 @@ PLC1802 [*] `len(fruits)` used as condition without comparison | help: Remove `len` | -246 | fruits = [] - - if len( - - fruits # comment - - ): +247 - if len( +248 - fruits # comment +249 - ): 247 + if fruits: -248 | ... | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLC2801_unnecessary_dunder_call.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLC2801_unnecessary_dunder_call.py.snap index fb62b5f0f3b70..e3c3b8cbf88e1 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLC2801_unnecessary_dunder_call.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLC2801_unnecessary_dunder_call.py.snap @@ -12,10 +12,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -3 | a = 2 - - print((3.0).__add__(4.0)) # PLC2801 +4 - print((3.0).__add__(4.0)) # PLC2801 4 + print(3.0 + 4.0) # PLC2801 -5 | print((3.0).__sub__(4.0)) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -31,10 +29,8 @@ PLC2801 [*] Unnecessary dunder call to `__sub__`. Use `-` operator. | help: Use `-` operator | -4 | print((3.0).__add__(4.0)) # PLC2801 - - print((3.0).__sub__(4.0)) # PLC2801 +5 - print((3.0).__sub__(4.0)) # PLC2801 5 + print(3.0 - 4.0) # PLC2801 -6 | print((3.0).__mul__(4.0)) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -50,10 +46,8 @@ PLC2801 [*] Unnecessary dunder call to `__mul__`. Use `*` operator. | help: Use `*` operator | -5 | print((3.0).__sub__(4.0)) # PLC2801 - - print((3.0).__mul__(4.0)) # PLC2801 +6 - print((3.0).__mul__(4.0)) # PLC2801 6 + print(3.0 * 4.0) # PLC2801 -7 | print((3.0).__truediv__(4.0)) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -69,10 +63,8 @@ PLC2801 [*] Unnecessary dunder call to `__truediv__`. Use `/` operator. | help: Use `/` operator | -6 | print((3.0).__mul__(4.0)) # PLC2801 - - print((3.0).__truediv__(4.0)) # PLC2801 +7 - print((3.0).__truediv__(4.0)) # PLC2801 7 + print(3.0 / 4.0) # PLC2801 -8 | print((3.0).__floordiv__(4.0)) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -88,10 +80,8 @@ PLC2801 [*] Unnecessary dunder call to `__floordiv__`. Use `//` operator. | help: Use `//` operator | -7 | print((3.0).__truediv__(4.0)) # PLC2801 - - print((3.0).__floordiv__(4.0)) # PLC2801 +8 - print((3.0).__floordiv__(4.0)) # PLC2801 8 + print(3.0 // 4.0) # PLC2801 -9 | print((3.0).__mod__(4.0)) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -106,12 +96,10 @@ PLC2801 [*] Unnecessary dunder call to `__mod__`. Use `%` operator. 11 | print((3.0).__ne__(4.0)) # PLC2801 | help: Use `%` operator - | -8 | print((3.0).__floordiv__(4.0)) # PLC2801 - - print((3.0).__mod__(4.0)) # PLC2801 -9 + print(3.0 % 4.0) # PLC2801 -10 | print((3.0).__eq__(4.0)) # PLC2801 - | + | +9 - print((3.0).__mod__(4.0)) # PLC2801 +9 + print(3.0 % 4.0) # PLC2801 + | note: This is an unsafe fix and may change runtime behavior PLC2801 [*] Unnecessary dunder call to `__eq__`. Use `==` operator. @@ -126,10 +114,8 @@ PLC2801 [*] Unnecessary dunder call to `__eq__`. Use `==` operator. | help: Use `==` operator | -9 | print((3.0).__mod__(4.0)) # PLC2801 - - print((3.0).__eq__(4.0)) # PLC2801 +10 - print((3.0).__eq__(4.0)) # PLC2801 10 + print(3.0 == 4.0) # PLC2801 -11 | print((3.0).__ne__(4.0)) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -145,10 +131,8 @@ PLC2801 [*] Unnecessary dunder call to `__ne__`. Use `!=` operator. | help: Use `!=` operator | -10 | print((3.0).__eq__(4.0)) # PLC2801 - - print((3.0).__ne__(4.0)) # PLC2801 +11 - print((3.0).__ne__(4.0)) # PLC2801 11 + print(3.0 != 4.0) # PLC2801 -12 | print((3.0).__lt__(4.0)) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -164,10 +148,8 @@ PLC2801 [*] Unnecessary dunder call to `__lt__`. Use `<` operator. | help: Use `<` operator | -11 | print((3.0).__ne__(4.0)) # PLC2801 - - print((3.0).__lt__(4.0)) # PLC2801 +12 - print((3.0).__lt__(4.0)) # PLC2801 12 + print(3.0 < 4.0) # PLC2801 -13 | print((3.0).__le__(4.0)) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -183,10 +165,8 @@ PLC2801 [*] Unnecessary dunder call to `__le__`. Use `<=` operator. | help: Use `<=` operator | -12 | print((3.0).__lt__(4.0)) # PLC2801 - - print((3.0).__le__(4.0)) # PLC2801 +13 - print((3.0).__le__(4.0)) # PLC2801 13 + print(3.0 <= 4.0) # PLC2801 -14 | print((3.0).__gt__(4.0)) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -202,10 +182,8 @@ PLC2801 [*] Unnecessary dunder call to `__gt__`. Use `>` operator. | help: Use `>` operator | -13 | print((3.0).__le__(4.0)) # PLC2801 - - print((3.0).__gt__(4.0)) # PLC2801 +14 - print((3.0).__gt__(4.0)) # PLC2801 14 + print(3.0 > 4.0) # PLC2801 -15 | print((3.0).__ge__(4.0)) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -221,10 +199,8 @@ PLC2801 [*] Unnecessary dunder call to `__ge__`. Use `>=` operator. | help: Use `>=` operator | -14 | print((3.0).__gt__(4.0)) # PLC2801 - - print((3.0).__ge__(4.0)) # PLC2801 +15 - print((3.0).__ge__(4.0)) # PLC2801 15 + print(3.0 >= 4.0) # PLC2801 -16 | print((3.0).__str__()) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -240,10 +216,8 @@ PLC2801 [*] Unnecessary dunder call to `__str__`. Use `str()` builtin. | help: Use `str()` builtin | -15 | print((3.0).__ge__(4.0)) # PLC2801 - - print((3.0).__str__()) # PLC2801 +16 - print((3.0).__str__()) # PLC2801 16 + print(str(3.0)) # PLC2801 -17 | print((3.0).__repr__()) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -259,10 +233,8 @@ PLC2801 [*] Unnecessary dunder call to `__repr__`. Use `repr()` builtin. | help: Use `repr()` builtin | -16 | print((3.0).__str__()) # PLC2801 - - print((3.0).__repr__()) # PLC2801 +17 - print((3.0).__repr__()) # PLC2801 17 + print(repr(3.0)) # PLC2801 -18 | print([1, 2, 3].__len__()) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -278,10 +250,8 @@ PLC2801 [*] Unnecessary dunder call to `__len__`. Use `len()` builtin. | help: Use `len()` builtin | -17 | print((3.0).__repr__()) # PLC2801 - - print([1, 2, 3].__len__()) # PLC2801 +18 - print([1, 2, 3].__len__()) # PLC2801 18 + print(len([1, 2, 3])) # PLC2801 -19 | print((1).__neg__()) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -309,10 +279,8 @@ PLC2801 [*] Unnecessary dunder call to `__sub__`. Use `-` operator. | help: Use `-` operator | -19 | print((1).__neg__()) # PLC2801 - - print(-a.__sub__(1)) # PLC2801 +20 - print(-a.__sub__(1)) # PLC2801 20 + print(-(a - 1)) # PLC2801 -21 | print(-(a).__sub__(1)) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -328,10 +296,8 @@ PLC2801 [*] Unnecessary dunder call to `__sub__`. Use `-` operator. | help: Use `-` operator | -20 | print(-a.__sub__(1)) # PLC2801 - - print(-(a).__sub__(1)) # PLC2801 +21 - print(-(a).__sub__(1)) # PLC2801 21 + print(-(a - 1)) # PLC2801 -22 | print(-(-a.__sub__(1))) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -347,10 +313,8 @@ PLC2801 [*] Unnecessary dunder call to `__sub__`. Use `-` operator. | help: Use `-` operator | -21 | print(-(a).__sub__(1)) # PLC2801 - - print(-(-a.__sub__(1))) # PLC2801 +22 - print(-(-a.__sub__(1))) # PLC2801 22 + print(-(-(a - 1))) # PLC2801 -23 | print((5 - a).__sub__(1)) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -366,10 +330,8 @@ PLC2801 [*] Unnecessary dunder call to `__sub__`. Use `-` operator. | help: Use `-` operator | -22 | print(-(-a.__sub__(1))) # PLC2801 - - print((5 - a).__sub__(1)) # PLC2801 +23 - print((5 - a).__sub__(1)) # PLC2801 23 + print(5 - a - 1) # PLC2801 -24 | print(-(5 - a).__sub__(1)) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -385,10 +347,8 @@ PLC2801 [*] Unnecessary dunder call to `__sub__`. Use `-` operator. | help: Use `-` operator | -23 | print((5 - a).__sub__(1)) # PLC2801 - - print(-(5 - a).__sub__(1)) # PLC2801 +24 - print(-(5 - a).__sub__(1)) # PLC2801 24 + print(-(5 - a - 1)) # PLC2801 -25 | print(-(-5 - a).__sub__(1)) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -404,10 +364,8 @@ PLC2801 [*] Unnecessary dunder call to `__sub__`. Use `-` operator. | help: Use `-` operator | -24 | print(-(5 - a).__sub__(1)) # PLC2801 - - print(-(-5 - a).__sub__(1)) # PLC2801 +25 - print(-(-5 - a).__sub__(1)) # PLC2801 25 + print(-(-5 - a - 1)) # PLC2801 -26 | print(+-+-+-a.__sub__(1)) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -423,10 +381,8 @@ PLC2801 [*] Unnecessary dunder call to `__sub__`. Use `-` operator. | help: Use `-` operator | -25 | print(-(-5 - a).__sub__(1)) # PLC2801 - - print(+-+-+-a.__sub__(1)) # PLC2801 +26 - print(+-+-+-a.__sub__(1)) # PLC2801 26 + print(+-+-+-(a - 1)) # PLC2801 -27 | print(a.__rsub__(2 - 1)) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -442,10 +398,8 @@ PLC2801 [*] Unnecessary dunder call to `__rsub__`. Use `-` operator. | help: Use `-` operator | -26 | print(+-+-+-a.__sub__(1)) # PLC2801 - - print(a.__rsub__(2 - 1)) # PLC2801 +27 - print(a.__rsub__(2 - 1)) # PLC2801 27 + print((2 - 1) - a) # PLC2801 -28 | print(a.__sub__(((((1)))))) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -461,10 +415,8 @@ PLC2801 [*] Unnecessary dunder call to `__sub__`. Use `-` operator. | help: Use `-` operator | -27 | print(a.__rsub__(2 - 1)) # PLC2801 - - print(a.__sub__(((((1)))))) # PLC2801 +28 - print(a.__sub__(((((1)))))) # PLC2801 28 + print(a - 1) # PLC2801 -29 | print(a.__sub__(((((2 - 1)))))) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -480,10 +432,8 @@ PLC2801 [*] Unnecessary dunder call to `__sub__`. Use `-` operator. | help: Use `-` operator | -28 | print(a.__sub__(((((1)))))) # PLC2801 - - print(a.__sub__(((((2 - 1)))))) # PLC2801 +29 - print(a.__sub__(((((2 - 1)))))) # PLC2801 29 + print(a - (2 - 1)) # PLC2801 -30 | print(a.__sub__( | note: This is an unsafe fix and may change runtime behavior @@ -504,15 +454,9 @@ PLC2801 [*] Unnecessary dunder call to `__sub__`. Use `-` operator. | help: Use `-` operator | -29 | print(a.__sub__(((((2 - 1)))))) # PLC2801 - - print(a.__sub__( - - 3 -30 + print(a - (3 -31 | + - - 4 - - )) -32 + 4)) -33 | print(a.__rsub__( +30 ~ print(a - (3 +31 + + +32 ~ 4)) | note: This is an unsafe fix and may change runtime behavior @@ -533,15 +477,9 @@ PLC2801 [*] Unnecessary dunder call to `__rsub__`. Use `-` operator. | help: Use `-` operator | -34 | )) - - print(a.__rsub__( - - 3 -35 + print((3 -36 | + - - 4 - - )) -37 + 4) - a) -38 | print(2 * a.__add__(3)) # PLC2801 +35 ~ print((3 +36 + + +37 ~ 4) - a) | note: This is an unsafe fix and may change runtime behavior @@ -557,10 +495,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -39 | )) - - print(2 * a.__add__(3)) # PLC2801 +40 - print(2 * a.__add__(3)) # PLC2801 40 + print(2 * (a + 3)) # PLC2801 -41 | x = 2 * a.__add__(3) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -576,10 +512,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -40 | print(2 * a.__add__(3)) # PLC2801 - - x = 2 * a.__add__(3) # PLC2801 +41 - x = 2 * a.__add__(3) # PLC2801 41 + x = 2 * (a + 3) # PLC2801 -42 | x = 2 * -a.__add__(3) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -595,10 +529,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -41 | x = 2 * a.__add__(3) # PLC2801 - - x = 2 * -a.__add__(3) # PLC2801 +42 - x = 2 * -a.__add__(3) # PLC2801 42 + x = 2 * -(a + 3) # PLC2801 -43 | x = a.__add__(3) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -614,10 +546,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -42 | x = 2 * -a.__add__(3) # PLC2801 - - x = a.__add__(3) # PLC2801 +43 - x = a.__add__(3) # PLC2801 43 + x = a + 3 # PLC2801 -44 | x = -a.__add__(3) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -633,10 +563,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -43 | x = a.__add__(3) # PLC2801 - - x = -a.__add__(3) # PLC2801 +44 - x = -a.__add__(3) # PLC2801 44 + x = -(a + 3) # PLC2801 -45 | x = (-a).__add__(3) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -651,10 +579,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -44 | x = -a.__add__(3) # PLC2801 - - x = (-a).__add__(3) # PLC2801 +45 - x = (-a).__add__(3) # PLC2801 45 + x = -a + 3 # PLC2801 -46 | x = -(-a).__add__(3) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -670,10 +596,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -45 | x = (-a).__add__(3) # PLC2801 - - x = -(-a).__add__(3) # PLC2801 +46 - x = -(-a).__add__(3) # PLC2801 46 + x = -(-a + 3) # PLC2801 -47 | | note: This is an unsafe fix and may change runtime behavior @@ -695,10 +619,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | ^^^^^^^^^^^^^^ help: Use `+` operator | -62 | foo = Foo(1) - - foo.__add__(2).get_v() # PLC2801 +63 - foo.__add__(2).get_v() # PLC2801 63 + (foo + 2).get_v() # PLC2801 -64 | | note: This is an unsafe fix and may change runtime behavior @@ -713,10 +635,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -66 | # Lambda expressions - - blah = lambda: a.__add__(1) # PLC2801 +67 - blah = lambda: a.__add__(1) # PLC2801 67 + blah = lambda: a + 1 # PLC2801 -68 | | note: This is an unsafe fix and may change runtime behavior @@ -731,10 +651,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -69 | # If expressions - - print(a.__add__(1) if a > 0 else a.__sub__(1)) # PLC2801 +70 - print(a.__add__(1) if a > 0 else a.__sub__(1)) # PLC2801 70 + print(a + 1 if a > 0 else a.__sub__(1)) # PLC2801 -71 | | note: This is an unsafe fix and may change runtime behavior @@ -749,10 +667,8 @@ PLC2801 [*] Unnecessary dunder call to `__sub__`. Use `-` operator. | help: Use `-` operator | -69 | # If expressions - - print(a.__add__(1) if a > 0 else a.__sub__(1)) # PLC2801 +70 - print(a.__add__(1) if a > 0 else a.__sub__(1)) # PLC2801 70 + print(a.__add__(1) if a > 0 else a - 1) # PLC2801 -71 | | note: This is an unsafe fix and may change runtime behavior @@ -767,10 +683,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -72 | # Dict/Set/List/Tuple - - print({"a": a.__add__(1)}) # PLC2801 +73 - print({"a": a.__add__(1)}) # PLC2801 73 + print({"a": (a + 1)}) # PLC2801 -74 | print({a.__add__(1)}) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -786,10 +700,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -73 | print({"a": a.__add__(1)}) # PLC2801 - - print({a.__add__(1)}) # PLC2801 +74 - print({a.__add__(1)}) # PLC2801 74 + print({(a + 1)}) # PLC2801 -75 | print([a.__add__(1)]) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -804,10 +716,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -74 | print({a.__add__(1)}) # PLC2801 - - print([a.__add__(1)]) # PLC2801 +75 - print([a.__add__(1)]) # PLC2801 75 + print([(a + 1)]) # PLC2801 -76 | print((a.__add__(1),)) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -823,10 +733,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -75 | print([a.__add__(1)]) # PLC2801 - - print((a.__add__(1),)) # PLC2801 +76 - print((a.__add__(1),)) # PLC2801 76 + print(((a + 1),)) # PLC2801 -77 | | note: This is an unsafe fix and may change runtime behavior @@ -841,10 +749,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -78 | # Comprehension variants - - print({i: i.__add__(1) for i in range(5)}) # PLC2801 +79 - print({i: i.__add__(1) for i in range(5)}) # PLC2801 79 + print({i: (i + 1) for i in range(5)}) # PLC2801 -80 | print({i.__add__(1) for i in range(5)}) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -860,10 +766,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -79 | print({i: i.__add__(1) for i in range(5)}) # PLC2801 - - print({i.__add__(1) for i in range(5)}) # PLC2801 +80 - print({i.__add__(1) for i in range(5)}) # PLC2801 80 + print({(i + 1) for i in range(5)}) # PLC2801 -81 | print([i.__add__(1) for i in range(5)]) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -878,10 +782,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -80 | print({i.__add__(1) for i in range(5)}) # PLC2801 - - print([i.__add__(1) for i in range(5)]) # PLC2801 +81 - print([i.__add__(1) for i in range(5)]) # PLC2801 81 + print([(i + 1) for i in range(5)]) # PLC2801 -82 | print((i.__add__(1) for i in range(5))) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -897,10 +799,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -81 | print([i.__add__(1) for i in range(5)]) # PLC2801 - - print((i.__add__(1) for i in range(5))) # PLC2801 +82 - print((i.__add__(1) for i in range(5))) # PLC2801 82 + print(((i + 1) for i in range(5))) # PLC2801 -83 | | note: This is an unsafe fix and may change runtime behavior @@ -914,10 +814,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -84 | # Generators - - gen = (i.__add__(1) for i in range(5)) # PLC2801 +85 - gen = (i.__add__(1) for i in range(5)) # PLC2801 85 + gen = ((i + 1) for i in range(5)) # PLC2801 -86 | print(next(gen)) | note: This is an unsafe fix and may change runtime behavior @@ -932,10 +830,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -88 | # Subscripts - - print({"a": a.__add__(1)}["a"]) # PLC2801 +89 - print({"a": a.__add__(1)}["a"]) # PLC2801 89 + print({"a": (a + 1)}["a"]) # PLC2801 -90 | # https://github.com/astral-sh/ruff/issues/15745 | note: This is an unsafe fix and may change runtime behavior @@ -951,10 +847,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -90 | # https://github.com/astral-sh/ruff/issues/15745 - - print("x".__add__("y")[0]) # PLC2801 +91 - print("x".__add__("y")[0]) # PLC2801 91 + print(("x" + "y")[0]) # PLC2801 -92 | | note: This is an unsafe fix and may change runtime behavior @@ -969,10 +863,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -93 | # Starred - - print(*[a.__add__(1)]) # PLC2801 +94 - print(*[a.__add__(1)]) # PLC2801 94 + print(*[(a + 1)]) # PLC2801 -95 | | note: This is an unsafe fix and may change runtime behavior @@ -988,10 +880,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -97 | list2 = [4, 5, 6] - - print([*list1.__add__(list2)]) # PLC2801 +98 - print([*list1.__add__(list2)]) # PLC2801 98 + print([*list1 + list2]) # PLC2801 -99 | | note: This is an unsafe fix and may change runtime behavior @@ -1006,10 +896,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -100 | # Slices - - print([a.__add__(1), a.__sub__(1)][0:1]) # PLC2801 +101 - print([a.__add__(1), a.__sub__(1)][0:1]) # PLC2801 101 + print([(a + 1), a.__sub__(1)][0:1]) # PLC2801 -102 | | note: This is an unsafe fix and may change runtime behavior @@ -1024,10 +912,8 @@ PLC2801 [*] Unnecessary dunder call to `__sub__`. Use `-` operator. | help: Use `-` operator | -100 | # Slices - - print([a.__add__(1), a.__sub__(1)][0:1]) # PLC2801 +101 - print([a.__add__(1), a.__sub__(1)][0:1]) # PLC2801 101 + print([a.__add__(1), (a - 1)][0:1]) # PLC2801 -102 | | note: This is an unsafe fix and may change runtime behavior @@ -1043,10 +929,8 @@ PLC2801 [*] Unnecessary dunder call to `__add__`. Use `+` operator. | help: Use `+` operator | -104 | # https://github.com/astral-sh/ruff/issues/15745 - - print(1j.__add__(1.0).real) # PLC2801 +105 - print(1j.__add__(1.0).real) # PLC2801 105 + print((1j + 1.0).real) # PLC2801 -106 | | note: This is an unsafe fix and may change runtime behavior @@ -1073,10 +957,8 @@ PLC2801 [*] Unnecessary dunder call to `__contains__`. Use `in` operator. | help: Use `in` operator | -127 | - - "abc".__contains__("a") +128 - "abc".__contains__("a") 128 + "a" in "abc" -129 | | note: This is an unsafe fix and may change runtime behavior @@ -1091,10 +973,8 @@ PLC2801 [*] Unnecessary dunder call to `__str__`. Use `str()` builtin. | help: Use `str()` builtin | -130 | # https://github.com/astral-sh/ruff/issues/14597 - - assert "abc".__str__() == "abc" +131 - assert "abc".__str__() == "abc" 131 + assert str("abc") == "abc" -132 | | note: This is an unsafe fix and may change runtime behavior @@ -1109,10 +989,8 @@ PLC2801 [*] Unnecessary dunder call to `__str__`. Use `str()` builtin. | help: Use `str()` builtin | -133 | # https://github.com/astral-sh/ruff/issues/18813 - - three = 1 if 1 else(3.0).__str__() +134 - three = 1 if 1 else(3.0).__str__() 134 + three = 1 if 1 else str(3.0) -135 | | note: This is an unsafe fix and may change runtime behavior @@ -1175,10 +1053,8 @@ PLC2801 [*] Unnecessary dunder call to `__matmul__`. Use `@` operator. | help: Use `@` operator | -140 | Foo().__length_hint__() # PLC2801 - - Foo().__matmul__(Foo()) # PLC2801 +141 - Foo().__matmul__(Foo()) # PLC2801 141 + Foo() @ Foo() # PLC2801 -142 | foo.__rmatmul__(a) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -1193,10 +1069,8 @@ PLC2801 [*] Unnecessary dunder call to `__rmatmul__`. Use `@` operator. | help: Use `@` operator | -141 | Foo().__matmul__(Foo()) # PLC2801 - - foo.__rmatmul__(a) # PLC2801 +142 - foo.__rmatmul__(a) # PLC2801 142 + a @ foo # PLC2801 -143 | foo.__imatmul__(foo) # PLC2801 | note: This is an unsafe fix and may change runtime behavior @@ -1209,8 +1083,7 @@ PLC2801 [*] Unnecessary dunder call to `__imatmul__`. Use `@=` operator. | ^^^^^^^^^^^^^^^^^^^^ help: Use `@=` operator | -142 | foo.__rmatmul__(a) # PLC2801 - - foo.__imatmul__(foo) # PLC2801 +143 - foo.__imatmul__(foo) # PLC2801 143 + foo @= foo # PLC2801 | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE0241_duplicate_bases.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE0241_duplicate_bases.py.snap index beaf8d509a51c..81064d5221e82 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE0241_duplicate_bases.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE0241_duplicate_bases.py.snap @@ -11,10 +11,8 @@ PLE0241 [*] Duplicate base `A` for class `F1` | help: Remove duplicate base | -12 | # Duplicate base class is last. - - class F1(A, A): +13 - class F1(A, A): 13 + class F1(A): -14 | ... | PLE0241 [*] Duplicate base `A` for class `F2` @@ -26,10 +24,8 @@ PLE0241 [*] Duplicate base `A` for class `F2` | help: Remove duplicate base | -16 | - - class F2(A, A,): +17 - class F2(A, A,): 17 + class F2(A,): -18 | ... | PLE0241 [*] Duplicate base `A` for class `F3` @@ -44,9 +40,7 @@ PLE0241 [*] Duplicate base `A` for class `F3` | help: Remove duplicate base | -21 | class F3( - - A, -22 | A +22 - A, | PLE0241 [*] Duplicate base `A` for class `F4` @@ -61,9 +55,7 @@ PLE0241 [*] Duplicate base `A` for class `F4` | help: Remove duplicate base | -29 | A, - - A, -30 | ): +29 - A, | PLE0241 [*] Duplicate base `A` for class `G1` @@ -76,10 +68,8 @@ PLE0241 [*] Duplicate base `A` for class `G1` | help: Remove duplicate base | -35 | # Duplicate base class is not last. - - class G1(A, A, B): +36 - class G1(A, A, B): 36 + class G1(A, B): -37 | ... | PLE0241 [*] Duplicate base `A` for class `G2` @@ -91,10 +81,8 @@ PLE0241 [*] Duplicate base `A` for class `G2` | help: Remove duplicate base | -39 | - - class G2(A, A, B,): +40 - class G2(A, A, B,): 40 + class G2(A, B,): -41 | ... | PLE0241 [*] Duplicate base `A` for class `G3` @@ -109,9 +97,7 @@ PLE0241 [*] Duplicate base `A` for class `G3` | help: Remove duplicate base | -45 | A, - - A, -46 | B +46 - A, | PLE0241 [*] Duplicate base `A` for class `G4` @@ -126,9 +112,7 @@ PLE0241 [*] Duplicate base `A` for class `G4` | help: Remove duplicate base | -53 | A, - - A, -54 | B, +54 - A, | PLE0241 [*] Duplicate base `Foo` for class `Bar` @@ -143,10 +127,8 @@ PLE0241 [*] Duplicate base `Foo` for class `Bar` | help: Remove duplicate base | -74 | # https://github.com/astral-sh/ruff/issues/18814 - - class Bar(Foo, # 1 - - Foo # 2 +75 - class Bar(Foo, # 1 +76 - Foo # 2 75 + class Bar(Foo # 2 -76 | ): | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE1141_dict_iter_missing_items.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE1141_dict_iter_missing_items.py.snap index 983df0f6d23f4..083f8ef0afc2b 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE1141_dict_iter_missing_items.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE1141_dict_iter_missing_items.py.snap @@ -11,11 +11,8 @@ PLE1141 [*] Unpacking a dictionary in iteration without calling `.items()` | help: Add a call to `.items()` | -12 | # Errors - - for k, v in d: -13 + for k, v in d.items(): -14 | pass - | +13 | for k, v in d.items(): + | ++++++++ note: This is an unsafe fix and may change runtime behavior PLE1141 [*] Unpacking a dictionary in iteration without calling `.items()` @@ -29,11 +26,8 @@ PLE1141 [*] Unpacking a dictionary in iteration without calling `.items()` | help: Add a call to `.items()` | -15 | - - for k, v in d_tuple_incorrect_tuple: -16 + for k, v in d_tuple_incorrect_tuple.items(): -17 | pass - | +16 | for k, v in d_tuple_incorrect_tuple.items(): + | ++++++++ note: This is an unsafe fix and may change runtime behavior PLE1141 [*] Unpacking a dictionary in iteration without calling `.items()` @@ -47,11 +41,8 @@ PLE1141 [*] Unpacking a dictionary in iteration without calling `.items()` | help: Add a call to `.items()` | -36 | empty_dict["x"] = 1 - - for k, v in empty_dict: -37 + for k, v in empty_dict.items(): -38 | pass - | +37 | for k, v in empty_dict.items(): + | ++++++++ note: This is an unsafe fix and may change runtime behavior PLE1141 [*] Unpacking a dictionary in iteration without calling `.items()` @@ -65,11 +56,8 @@ PLE1141 [*] Unpacking a dictionary in iteration without calling `.items()` | help: Add a call to `.items()` | -45 | empty_dict_unannotated[("x", "y")] = True - - for k, v in empty_dict_unannotated: -46 + for k, v in empty_dict_unannotated.items(): -47 | pass - | +46 | for k, v in empty_dict_unannotated.items(): + | ++++++++ note: This is an unsafe fix and may change runtime behavior PLE1141 [*] Unpacking a dictionary in iteration without calling `.items()` @@ -83,9 +71,6 @@ PLE1141 [*] Unpacking a dictionary in iteration without calling `.items()` | help: Add a call to `.items()` | -50 | empty_dict_annotated_str_keys["x"] = 1 - - for k, v in empty_dict_annotated_str_keys: -51 + for k, v in empty_dict_annotated_str_keys.items(): -52 | pass - | +51 | for k, v in empty_dict_annotated_str_keys.items(): + | ++++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE1519_singledispatch_method.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE1519_singledispatch_method.py.snap index b00cda9f9f3ce..722ae44a47dc6 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE1519_singledispatch_method.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE1519_singledispatch_method.py.snap @@ -12,10 +12,11 @@ PLE1519 [*] `@singledispatch` decorator should not be used on methods | help: Replace with `@singledispatchmethod` | -9 | class Board: - - @singledispatch # [singledispatch-method] -10 + @singledispatchmethod # [singledispatch-method] -11 | @classmethod + 1 ~ from functools import singledispatch, singledispatchmethod + 2 | + … + 9 | class Board: +10 ~ @singledispatchmethod # [singledispatch-method] | note: This is an unsafe fix and may change runtime behavior @@ -31,10 +32,11 @@ PLE1519 [*] `@singledispatch` decorator should not be used on methods | help: Replace with `@singledispatchmethod` | + 1 ~ from functools import singledispatch, singledispatchmethod + 2 | + … 14 | - - @singledispatch # [singledispatch-method] -15 + @singledispatchmethod # [singledispatch-method] -16 | def move(self, position): +15 ~ @singledispatchmethod # [singledispatch-method] | note: This is an unsafe fix and may change runtime behavior @@ -50,9 +52,10 @@ PLE1519 [*] `@singledispatch` decorator should not be used on methods | help: Replace with `@singledispatchmethod` | + 1 ~ from functools import singledispatch, singledispatchmethod + 2 | + … 22 | - - @singledispatch # [singledispatch-method] -23 + @singledispatchmethod # [singledispatch-method] -24 | @staticmethod +23 ~ @singledispatchmethod # [singledispatch-method] | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE1520_singledispatchmethod_function.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE1520_singledispatchmethod_function.py.snap index 88d6718d3be38..2d52dac713f92 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE1520_singledispatchmethod_function.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE1520_singledispatchmethod_function.py.snap @@ -11,12 +11,9 @@ PLE1520 [*] `@singledispatchmethod` decorator should not be used on non-method f | help: Replace with `@singledispatch` | - - from functools import singledispatchmethod -1 + from functools import singledispatchmethod, singledispatch +1 ~ from functools import singledispatchmethod, singledispatch 2 | 3 | - - @singledispatchmethod # [singledispatchmethod-function] -4 + @singledispatch # [singledispatchmethod-function] -5 | def convert_position(position): +4 ~ @singledispatch # [singledispatchmethod-function] | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE2510_invalid_characters.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE2510_invalid_characters.py.snap index 221dae3339ac7..942da51c81b8f 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE2510_invalid_characters.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE2510_invalid_characters.py.snap @@ -12,10 +12,8 @@ PLE2510 [*] Invalid unescaped character backspace, use "\b" instead | help: Replace with escape sequence | -14 | #foo = 'hi' - - b = '␈' +15 - b = '␈' 15 + b = '\b' -16 | b = f'␈' | PLE2510 [*] Invalid unescaped character backspace, use "\b" instead @@ -30,10 +28,8 @@ PLE2510 [*] Invalid unescaped character backspace, use "\b" instead | help: Replace with escape sequence | -15 | b = '␈' - - b = f'␈' +16 - b = f'␈' 16 + b = f'\b' -17 | | PLE2510 [*] Invalid unescaped character backspace, use "\b" instead @@ -48,10 +44,8 @@ PLE2510 [*] Invalid unescaped character backspace, use "\b" instead | help: Replace with escape sequence | -54 | - - nested_fstrings = f'␈{f'{f'␛'}'}' -55 + nested_fstrings = f'\b{f'{f'␛'}'}' -56 | +55 - nested_fstrings = f'␈{f'␚{f'␛'}'}' +55 + nested_fstrings = f'\b{f'␚{f'␛'}'}' | PLE2510 Invalid unescaped character backspace, use "\b" instead @@ -110,10 +104,8 @@ PLE2510 [*] Invalid unescaped character backspace, use "\b" instead | help: Replace with escape sequence | -79 | esc = t'esc esc ␛' - - nested_tstrings = t'␈{t'{t'␛'}'}' -80 + nested_tstrings = t'\b{t'{t'␛'}'}' -81 | nested_ftstrings = t'␈{f'{t'␛'}'}' +80 - nested_tstrings = t'␈{t'␚{t'␛'}'}' +80 + nested_tstrings = t'\b{t'␚{t'␛'}'}' | PLE2510 [*] Invalid unescaped character backspace, use "\b" instead @@ -125,8 +117,6 @@ PLE2510 [*] Invalid unescaped character backspace, use "\b" instead | ^ help: Replace with escape sequence | -80 | nested_tstrings = t'␈{t'{t'␛'}'}' - - nested_ftstrings = t'␈{f'{t'␛'}'}' -81 + nested_ftstrings = t'\b{f'{t'␛'}'}' -82 | +81 - nested_ftstrings = t'␈{f'␚{t'␛'}'}' +81 + nested_ftstrings = t'\b{f'␚{t'␛'}'}' | diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE2512_invalid_characters.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE2512_invalid_characters.py.snap index a6244be8a55ab..6340e87476c8d 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE2512_invalid_characters.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE2512_invalid_characters.py.snap @@ -12,10 +12,8 @@ PLE2512 [*] Invalid unescaped character SUB, use "\x1a" instead | help: Replace with escape sequence | -23 | - - sub = 'sub ' +24 - sub = 'sub ␚' 24 + sub = 'sub \x1a' -25 | sub = f'sub ' | PLE2512 [*] Invalid unescaped character SUB, use "\x1a" instead @@ -29,10 +27,8 @@ PLE2512 [*] Invalid unescaped character SUB, use "\x1a" instead | help: Replace with escape sequence | -24 | sub = 'sub ' - - sub = f'sub ' +25 - sub = f'sub ␚' 25 + sub = f'sub \x1a' -26 | | PLE2512 [*] Invalid unescaped character SUB, use "\x1a" instead @@ -47,10 +43,8 @@ PLE2512 [*] Invalid unescaped character SUB, use "\x1a" instead | help: Replace with escape sequence | -54 | - - nested_fstrings = f'␈{f'{f'␛'}'}' +55 - nested_fstrings = f'␈{f'␚{f'␛'}'}' 55 + nested_fstrings = f'␈{f'\x1a{f'␛'}'}' -56 | | PLE2512 [*] Invalid unescaped character SUB, use "\x1a" instead @@ -64,10 +58,8 @@ PLE2512 [*] Invalid unescaped character SUB, use "\x1a" instead | help: Replace with escape sequence | -57 | # https://github.com/astral-sh/ruff/issues/7455#issuecomment-1741998106 - - x = f"""}}ab""" +58 - x = f"""}}a␚b""" 58 + x = f"""}}a\x1ab""" -59 | # https://github.com/astral-sh/ruff/issues/7455#issuecomment-1741998256 | PLE2512 Invalid unescaped character SUB, use "\x1a" instead @@ -127,10 +119,8 @@ PLE2512 [*] Invalid unescaped character SUB, use "\x1a" instead | help: Replace with escape sequence | -79 | esc = t'esc esc ␛' - - nested_tstrings = t'␈{t'{t'␛'}'}' +80 - nested_tstrings = t'␈{t'␚{t'␛'}'}' 80 + nested_tstrings = t'␈{t'\x1a{t'␛'}'}' -81 | nested_ftstrings = t'␈{f'{t'␛'}'}' | PLE2512 [*] Invalid unescaped character SUB, use "\x1a" instead @@ -142,8 +132,6 @@ PLE2512 [*] Invalid unescaped character SUB, use "\x1a" instead | ^ help: Replace with escape sequence | -80 | nested_tstrings = t'␈{t'{t'␛'}'}' - - nested_ftstrings = t'␈{f'{t'␛'}'}' +81 - nested_ftstrings = t'␈{f'␚{t'␛'}'}' 81 + nested_ftstrings = t'␈{f'\x1a{t'␛'}'}' -82 | | diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE2513_invalid_characters.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE2513_invalid_characters.py.snap index 9460786bff2df..9b581314283ef 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE2513_invalid_characters.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE2513_invalid_characters.py.snap @@ -12,10 +12,8 @@ PLE2513 [*] Invalid unescaped character ESC, use "\x1b" instead | help: Replace with escape sequence | -29 | - - esc = 'esc esc ␛' +30 - esc = 'esc esc ␛' 30 + esc = 'esc esc \x1b' -31 | esc = f'esc esc ␛' | PLE2513 [*] Invalid unescaped character ESC, use "\x1b" instead @@ -29,10 +27,8 @@ PLE2513 [*] Invalid unescaped character ESC, use "\x1b" instead | help: Replace with escape sequence | -30 | esc = 'esc esc ␛' - - esc = f'esc esc ␛' +31 - esc = f'esc esc ␛' 31 + esc = f'esc esc \x1b' -32 | | PLE2513 [*] Invalid unescaped character ESC, use "\x1b" instead @@ -47,10 +43,8 @@ PLE2513 [*] Invalid unescaped character ESC, use "\x1b" instead | help: Replace with escape sequence | -54 | - - nested_fstrings = f'␈{f'{f'␛'}'}' -55 + nested_fstrings = f'␈{f'{f'\x1b'}'}' -56 | +55 - nested_fstrings = f'␈{f'␚{f'␛'}'}' +55 + nested_fstrings = f'␈{f'␚{f'\x1b'}'}' | PLE2513 [*] Invalid unescaped character ESC, use "\x1b" instead @@ -62,10 +56,8 @@ PLE2513 [*] Invalid unescaped character ESC, use "\x1b" instead | ^ help: Replace with escape sequence | -59 | # https://github.com/astral-sh/ruff/issues/7455#issuecomment-1741998256 - - x = f"""}}a␛b""" +60 - x = f"""}}a␛b""" 60 + x = f"""}}a\x1bb""" -61 | | PLE2513 Invalid unescaped character ESC, use "\x1b" instead @@ -125,10 +117,8 @@ PLE2513 [*] Invalid unescaped character ESC, use "\x1b" instead | help: Replace with escape sequence | -78 | # tstrings - - esc = t'esc esc ␛' +79 - esc = t'esc esc ␛' 79 + esc = t'esc esc \x1b' -80 | nested_tstrings = t'␈{t'{t'␛'}'}' | PLE2513 [*] Invalid unescaped character ESC, use "\x1b" instead @@ -142,10 +132,8 @@ PLE2513 [*] Invalid unescaped character ESC, use "\x1b" instead | help: Replace with escape sequence | -79 | esc = t'esc esc ␛' - - nested_tstrings = t'␈{t'{t'␛'}'}' -80 + nested_tstrings = t'␈{t'{t'\x1b'}'}' -81 | nested_ftstrings = t'␈{f'{t'␛'}'}' +80 - nested_tstrings = t'␈{t'␚{t'␛'}'}' +80 + nested_tstrings = t'␈{t'␚{t'\x1b'}'}' | PLE2513 [*] Invalid unescaped character ESC, use "\x1b" instead @@ -157,8 +145,6 @@ PLE2513 [*] Invalid unescaped character ESC, use "\x1b" instead | ^ help: Replace with escape sequence | -80 | nested_tstrings = t'␈{t'{t'␛'}'}' - - nested_ftstrings = t'␈{f'{t'␛'}'}' -81 + nested_ftstrings = t'␈{f'{t'\x1b'}'}' -82 | +81 - nested_ftstrings = t'␈{f'␚{t'␛'}'}' +81 + nested_ftstrings = t'␈{f'␚{t'\x1b'}'}' | diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE2514_invalid_characters.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE2514_invalid_characters.py.snap index 880cbc8ef3bf7..9e2becf75a623 100644 Binary files a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE2514_invalid_characters.py.snap and b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE2514_invalid_characters.py.snap differ diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE2515_invalid_characters.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE2515_invalid_characters.py.snap index 6d3205f333b41..6bb5169e14fef 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE2515_invalid_characters.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE2515_invalid_characters.py.snap @@ -12,10 +12,8 @@ PLE2515 [*] Invalid unescaped character zero-width-space, use "\u200B" instead | help: Replace with escape sequence | -43 | - - zwsp = 'zero​width' +44 - zwsp = 'zero​width' 44 + zwsp = 'zero\u200bwidth' -45 | zwsp = f'zero​width' | PLE2515 [*] Invalid unescaped character zero-width-space, use "\u200B" instead @@ -29,10 +27,8 @@ PLE2515 [*] Invalid unescaped character zero-width-space, use "\u200B" instead | help: Replace with escape sequence | -44 | zwsp = 'zero​width' - - zwsp = f'zero​width' +45 - zwsp = f'zero​width' 45 + zwsp = f'zero\u200bwidth' -46 | | PLE2515 [*] Invalid unescaped character zero-width-space, use "\u200B" instead @@ -47,10 +43,8 @@ PLE2515 [*] Invalid unescaped character zero-width-space, use "\u200B" instead | help: Replace with escape sequence | -49 | - - zwsp_after_multibyte_character = "ಫ​" +50 - zwsp_after_multibyte_character = "ಫ​" 50 + zwsp_after_multibyte_character = "ಫ\u200b" -51 | zwsp_after_multibyte_character = f"ಫ​" | PLE2515 [*] Invalid unescaped character zero-width-space, use "\u200B" instead @@ -64,10 +58,8 @@ PLE2515 [*] Invalid unescaped character zero-width-space, use "\u200B" instead | help: Replace with escape sequence | -50 | zwsp_after_multibyte_character = "ಫ​" - - zwsp_after_multibyte_character = f"ಫ​" +51 - zwsp_after_multibyte_character = f"ಫ​" 51 + zwsp_after_multibyte_character = f"ಫ\u200b" -52 | zwsp_after_multicharacter_grapheme_cluster = "ಫ್ರಾನ್ಸಿಸ್ಕೊ ​​" | PLE2515 [*] Invalid unescaped character zero-width-space, use "\u200B" instead @@ -81,10 +73,8 @@ PLE2515 [*] Invalid unescaped character zero-width-space, use "\u200B" instead | help: Replace with escape sequence | -51 | zwsp_after_multibyte_character = f"ಫ​" - - zwsp_after_multicharacter_grapheme_cluster = "ಫ್ರಾನ್ಸಿಸ್ಕೊ ​​" +52 - zwsp_after_multicharacter_grapheme_cluster = "ಫ್ರಾನ್ಸಿಸ್ಕೊ ​​" 52 + zwsp_after_multicharacter_grapheme_cluster = "ಫ್ರಾನ್ಸಿಸ್ಕೊ \u200b​" -53 | zwsp_after_multicharacter_grapheme_cluster = f"ಫ್ರಾನ್ಸಿಸ್ಕೊ ​​" | PLE2515 [*] Invalid unescaped character zero-width-space, use "\u200B" instead @@ -98,10 +88,8 @@ PLE2515 [*] Invalid unescaped character zero-width-space, use "\u200B" instead | help: Replace with escape sequence | -51 | zwsp_after_multibyte_character = f"ಫ​" - - zwsp_after_multicharacter_grapheme_cluster = "ಫ್ರಾನ್ಸಿಸ್ಕೊ ​​" +52 - zwsp_after_multicharacter_grapheme_cluster = "ಫ್ರಾನ್ಸಿಸ್ಕೊ ​​" 52 + zwsp_after_multicharacter_grapheme_cluster = "ಫ್ರಾನ್ಸಿಸ್ಕೊ ​\u200b" -53 | zwsp_after_multicharacter_grapheme_cluster = f"ಫ್ರಾನ್ಸಿಸ್ಕೊ ​​" | PLE2515 [*] Invalid unescaped character zero-width-space, use "\u200B" instead @@ -116,10 +104,8 @@ PLE2515 [*] Invalid unescaped character zero-width-space, use "\u200B" instead | help: Replace with escape sequence | -52 | zwsp_after_multicharacter_grapheme_cluster = "ಫ್ರಾನ್ಸಿಸ್ಕೊ ​​" - - zwsp_after_multicharacter_grapheme_cluster = f"ಫ್ರಾನ್ಸಿಸ್ಕೊ ​​" +53 - zwsp_after_multicharacter_grapheme_cluster = f"ಫ್ರಾನ್ಸಿಸ್ಕೊ ​​" 53 + zwsp_after_multicharacter_grapheme_cluster = f"ಫ್ರಾನ್ಸಿಸ್ಕೊ \u200b​" -54 | | PLE2515 [*] Invalid unescaped character zero-width-space, use "\u200B" instead @@ -134,10 +120,8 @@ PLE2515 [*] Invalid unescaped character zero-width-space, use "\u200B" instead | help: Replace with escape sequence | -52 | zwsp_after_multicharacter_grapheme_cluster = "ಫ್ರಾನ್ಸಿಸ್ಕೊ ​​" - - zwsp_after_multicharacter_grapheme_cluster = f"ಫ್ರಾನ್ಸಿಸ್ಕೊ ​​" +53 - zwsp_after_multicharacter_grapheme_cluster = f"ಫ್ರಾನ್ಸಿಸ್ಕೊ ​​" 53 + zwsp_after_multicharacter_grapheme_cluster = f"ಫ್ರಾನ್ಸಿಸ್ಕೊ ​\u200b" -54 | | PLE2515 Invalid unescaped character zero-width-space, use "\u200B" instead diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE4703_modified_iterating_set.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE4703_modified_iterating_set.py.snap index 51fcdebbb89c4..b3e4cf17fc65a 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE4703_modified_iterating_set.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLE4703_modified_iterating_set.py.snap @@ -13,11 +13,8 @@ PLE4703 [*] Iterated set `nums` is modified within the `for` loop | help: Iterate over a copy of `nums` | -3 | nums = {1, 2, 3} - - for num in nums: -4 + for num in nums.copy(): -5 | nums.add(num + 1) - | +4 | for num in nums.copy(): + | +++++++ note: This is an unsafe fix and may change runtime behavior PLE4703 [*] Iterated set `animals` is modified within the `for` loop @@ -32,11 +29,8 @@ PLE4703 [*] Iterated set `animals` is modified within the `for` loop | help: Iterate over a copy of `animals` | -7 | animals = {"dog", "cat", "cow"} - - for animal in animals: -8 + for animal in animals.copy(): -9 | animals.pop("cow") - | +8 | for animal in animals.copy(): + | +++++++ note: This is an unsafe fix and may change runtime behavior PLE4703 [*] Iterated set `fruits` is modified within the `for` loop @@ -51,11 +45,8 @@ PLE4703 [*] Iterated set `fruits` is modified within the `for` loop | help: Iterate over a copy of `fruits` | -11 | fruits = {"apple", "orange", "grape"} - - for fruit in fruits: -12 + for fruit in fruits.copy(): -13 | fruits.clear() - | +12 | for fruit in fruits.copy(): + | +++++++ note: This is an unsafe fix and may change runtime behavior PLE4703 [*] Iterated set `planets` is modified within the `for` loop @@ -70,11 +61,8 @@ PLE4703 [*] Iterated set `planets` is modified within the `for` loop | help: Iterate over a copy of `planets` | -15 | planets = {"mercury", "venus", "earth"} - - for planet in planets: -16 + for planet in planets.copy(): -17 | planets.discard("mercury") - | +16 | for planet in planets.copy(): + | +++++++ note: This is an unsafe fix and may change runtime behavior PLE4703 [*] Iterated set `colors` is modified within the `for` loop @@ -89,11 +77,8 @@ PLE4703 [*] Iterated set `colors` is modified within the `for` loop | help: Iterate over a copy of `colors` | -19 | colors = {"red", "green", "blue"} - - for color in colors: -20 + for color in colors.copy(): -21 | colors.remove("red") - | +20 | for color in colors.copy(): + | +++++++ note: This is an unsafe fix and may change runtime behavior PLE4703 [*] Iterated set `odds` is modified within the `for` loop @@ -109,9 +94,6 @@ PLE4703 [*] Iterated set `odds` is modified within the `for` loop | help: Iterate over a copy of `odds` | -23 | odds = {1, 3, 5} - - for num in odds: -24 + for num in odds.copy(): -25 | if num > 1: - | +24 | for num in odds.copy(): + | +++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR0202_no_method_decorator.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR0202_no_method_decorator.py.snap index d327eea43347d..c7dc244019989 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR0202_no_method_decorator.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR0202_no_method_decorator.py.snap @@ -13,14 +13,8 @@ PLR0202 [*] Class method defined without decorator | help: Add @classmethod decorator | -8 | -9 + @classmethod -10 | def pick_colors(cls, *args): # [no-classmethod-decorator] -11 | """classmethod to pick fruit colors""" -12 | cls.COLORS = args -13 | - - pick_colors = classmethod(pick_colors) -14 | + 9 ~ @classmethod +10 ~ def pick_colors(cls, *args): # [no-classmethod-decorator] | PLR0202 [*] Class method defined without decorator @@ -33,12 +27,9 @@ PLR0202 [*] Class method defined without decorator | help: Add @classmethod decorator | -21 | class Class: -22 + @classmethod -23 | def class_method(cls): +22 ~ @classmethod +23 ~ def class_method(cls): 24 | pass 25 | - - class_method = classmethod(class_method);another_statement -26 + another_statement -27 | +26 ~ another_statement | diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR0203_no_method_decorator.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR0203_no_method_decorator.py.snap index 786fa54486080..1ccc6e68cc4f6 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR0203_no_method_decorator.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR0203_no_method_decorator.py.snap @@ -13,14 +13,8 @@ PLR0203 [*] Static method defined without decorator | help: Add @staticmethod decorator | -14 | -15 + @staticmethod -16 | def pick_one_color(): # [no-staticmethod-decorator] -17 | """staticmethod to pick one fruit color""" -18 | return choice(Fruit.COLORS) -19 | - - pick_one_color = staticmethod(pick_one_color) -20 | +15 ~ @staticmethod +16 ~ def pick_one_color(): # [no-staticmethod-decorator] | PLR0203 [*] Static method defined without decorator @@ -34,11 +28,9 @@ PLR0203 [*] Static method defined without decorator | help: Add @staticmethod decorator | -26 | -27 + @staticmethod -28 | def static_method(): +27 ~ @staticmethod +28 ~ def static_method(): 29 | pass 30 | - - static_method = staticmethod(static_method); -31 + +31 ~ | diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR0402_import_aliasing.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR0402_import_aliasing.py.snap index 706f7e0d443bb..34cb23c46686d 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR0402_import_aliasing.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR0402_import_aliasing.py.snap @@ -12,12 +12,10 @@ PLR0402 [*] Use `from os import path` in lieu of alias 11 | import foo.bar.foobar as foobar # [consider-using-from-import] | help: Replace with `from os import path` - | -8 | from collections import OrderedDict as o_dict - - import os.path as path # [consider-using-from-import] -9 + from os import path # [consider-using-from-import] -10 | import os.path as p - | + | +9 - import os.path as path # [consider-using-from-import] +9 + from os import path # [consider-using-from-import] + | PLR0402 [*] Use `from foo.bar import foobar` in lieu of alias --> import_aliasing.py:11:8 @@ -31,10 +29,8 @@ PLR0402 [*] Use `from foo.bar import foobar` in lieu of alias | help: Replace with `from foo.bar import foobar` | -10 | import os.path as p - - import foo.bar.foobar as foobar # [consider-using-from-import] +11 - import foo.bar.foobar as foobar # [consider-using-from-import] 11 + from foo.bar import foobar # [consider-using-from-import] -12 | import foo.bar.foobar as foobar, sys # [consider-using-from-import] | PLR0402 Use `from foo.bar import foobar` in lieu of alias diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1711_useless_return.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1711_useless_return.py.snap index bb66211d8fc87..ca43339290e7e 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1711_useless_return.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1711_useless_return.py.snap @@ -10,9 +10,7 @@ PLR1711 [*] Useless `return` statement at end of function | ^^^^^^^^^^^ help: Remove useless `return` statement | -5 | print(sys.version) - - return None # [useless-return] -6 | +6 - return None # [useless-return] | PLR1711 [*] Useless `return` statement at end of function @@ -24,9 +22,7 @@ PLR1711 [*] Useless `return` statement at end of function | ^^^^^^^^^^^ help: Remove useless `return` statement | -10 | print(sys.version) - - return None # [useless-return] -11 | +11 - return None # [useless-return] | PLR1711 [*] Useless `return` statement at end of function @@ -38,9 +34,7 @@ PLR1711 [*] Useless `return` statement at end of function | ^^^^^^^^^^^ help: Remove useless `return` statement | -15 | print(sys.version) - - return None # [useless-return] -16 | +16 - return None # [useless-return] | PLR1711 [*] Useless `return` statement at end of function @@ -52,9 +46,7 @@ PLR1711 [*] Useless `return` statement at end of function | ^^^^^^^^^^^ help: Remove useless `return` statement | -21 | print(sys.version) - - return None # [useless-return] -22 | +22 - return None # [useless-return] | PLR1711 [*] Useless `return` statement at end of function @@ -66,9 +58,7 @@ PLR1711 [*] Useless `return` statement at end of function | ^^^^^^^^^^^ help: Remove useless `return` statement | -49 | print(sys.version) - - return None # [useless-return] -50 | +50 - return None # [useless-return] | PLR1711 [*] Useless `return` statement at end of function @@ -80,6 +70,5 @@ PLR1711 [*] Useless `return` statement at end of function | ^^^^^^^^^^^ help: Remove useless `return` statement | -59 | print(f"{key} not found") - - return None +60 - return None | diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1712_swap_with_temporary_variable.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1712_swap_with_temporary_variable.py.snap index 9df056a3ac0c0..15ce0bbfd126f 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1712_swap_with_temporary_variable.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1712_swap_with_temporary_variable.py.snap @@ -12,12 +12,10 @@ PLR1712 [*] Unnecessary temporary variable | |____________^ help: Use `x, y = y, x` instead | -2 | def foo(x: int, y: int): - - temp: int = x - - x = y - - y = temp +3 - temp: int = x +4 - x = y +5 - y = temp 3 + x, y = y, x -4 | | PLR1712 [*] Unnecessary temporary variable @@ -31,12 +29,10 @@ PLR1712 [*] Unnecessary temporary variable | |________________^ help: Use `x, y = y, x` instead | -10 | if x > 5: - - temp: int = x - - x = y - - y = temp +11 - temp: int = x +12 - x = y +13 - y = temp 11 + x, y = y, x -12 | | PLR1712 [*] Unnecessary temporary variable @@ -50,11 +46,9 @@ PLR1712 [*] Unnecessary temporary variable | |____________^ help: Use `x, y = y, x` instead | -17 | def bar(x: int, y: int): - - temp: int = x # comment - - x = y - - y = temp +18 - temp: int = x # comment +19 - x = y +20 - y = temp 18 + x, y = y, x -19 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1714_repeated_equality_comparison.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1714_repeated_equality_comparison.py.snap index e1284b355c192..0deaa2c090c13 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1714_repeated_equality_comparison.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1714_repeated_equality_comparison.py.snap @@ -12,10 +12,8 @@ PLR1714 [*] Consider merging multiple comparisons: `foo in {"a", "b"}`. | help: Merge multiple comparisons | -1 | # Errors. - - foo == "a" or foo == "b" +2 - foo == "a" or foo == "b" 2 + foo in {"a", "b"} -3 | | note: This is an unsafe fix and may change runtime behavior @@ -31,10 +29,8 @@ PLR1714 [*] Consider merging multiple comparisons: `foo not in {"a", "b"}`. | help: Merge multiple comparisons | -3 | - - foo != "a" and foo != "b" +4 - foo != "a" and foo != "b" 4 + foo not in {"a", "b"} -5 | | note: This is an unsafe fix and may change runtime behavior @@ -50,10 +46,8 @@ PLR1714 [*] Consider merging multiple comparisons: `foo in {"a", "b", "c"}`. | help: Merge multiple comparisons | -5 | - - foo == "a" or foo == "b" or foo == "c" +6 - foo == "a" or foo == "b" or foo == "c" 6 + foo in {"a", "b", "c"} -7 | | note: This is an unsafe fix and may change runtime behavior @@ -69,10 +63,8 @@ PLR1714 [*] Consider merging multiple comparisons: `foo not in {"a", "b", "c"}`. | help: Merge multiple comparisons | -7 | - - foo != "a" and foo != "b" and foo != "c" +8 - foo != "a" and foo != "b" and foo != "c" 8 + foo not in {"a", "b", "c"} -9 | | note: This is an unsafe fix and may change runtime behavior @@ -88,10 +80,8 @@ PLR1714 [*] Consider merging multiple comparisons: `foo in (a, "b", 3)`. Use a ` | help: Merge multiple comparisons | -9 | - - foo == a or foo == "b" or foo == 3 # Mixed types. +10 - foo == a or foo == "b" or foo == 3 # Mixed types. 10 + foo in (a, "b", 3) # Mixed types. -11 | | note: This is an unsafe fix and may change runtime behavior @@ -107,10 +97,8 @@ PLR1714 [*] Consider merging multiple comparisons: `foo in {"a", "b", "c"}`. | help: Merge multiple comparisons | -11 | - - "a" == foo or "b" == foo or "c" == foo +12 - "a" == foo or "b" == foo or "c" == foo 12 + foo in {"a", "b", "c"} -13 | | note: This is an unsafe fix and may change runtime behavior @@ -126,10 +114,8 @@ PLR1714 [*] Consider merging multiple comparisons: `foo not in {"a", "b", "c"}`. | help: Merge multiple comparisons | -13 | - - "a" != foo and "b" != foo and "c" != foo +14 - "a" != foo and "b" != foo and "c" != foo 14 + foo not in {"a", "b", "c"} -15 | | note: This is an unsafe fix and may change runtime behavior @@ -145,10 +131,8 @@ PLR1714 [*] Consider merging multiple comparisons: `foo in {"a", "b", "c"}`. | help: Merge multiple comparisons | -15 | - - "a" == foo or foo == "b" or "c" == foo +16 - "a" == foo or foo == "b" or "c" == foo 16 + foo in {"a", "b", "c"} -17 | | note: This is an unsafe fix and may change runtime behavior @@ -164,10 +148,8 @@ PLR1714 [*] Consider merging multiple comparisons: `foo in (bar, baz, qux)`. Use | help: Merge multiple comparisons | -17 | - - foo == bar or baz == foo or qux == foo +18 - foo == bar or baz == foo or qux == foo 18 + foo in (bar, baz, qux) -19 | | note: This is an unsafe fix and may change runtime behavior @@ -183,10 +165,8 @@ PLR1714 [*] Consider merging multiple comparisons: `foo in {"a", "b", "c"}`. | help: Merge multiple comparisons | -19 | - - foo == "a" or "b" == foo or foo == "c" +20 - foo == "a" or "b" == foo or foo == "c" 20 + foo in {"a", "b", "c"} -21 | | note: This is an unsafe fix and may change runtime behavior @@ -202,10 +182,8 @@ PLR1714 [*] Consider merging multiple comparisons: `foo not in {"a", "b", "c"}`. | help: Merge multiple comparisons | -21 | - - foo != "a" and "b" != foo and foo != "c" +22 - foo != "a" and "b" != foo and foo != "c" 22 + foo not in {"a", "b", "c"} -23 | | note: This is an unsafe fix and may change runtime behavior @@ -221,10 +199,8 @@ PLR1714 [*] Consider merging multiple comparisons: `foo in {"a", "b"}`. | help: Merge multiple comparisons | -23 | - - foo == "a" or foo == "b" or "c" == bar or "d" == bar # Multiple targets +24 - foo == "a" or foo == "b" or "c" == bar or "d" == bar # Multiple targets 24 + foo in {"a", "b"} or "c" == bar or "d" == bar # Multiple targets -25 | | note: This is an unsafe fix and may change runtime behavior @@ -240,10 +216,8 @@ PLR1714 [*] Consider merging multiple comparisons: `bar in {"c", "d"}`. | help: Merge multiple comparisons | -23 | - - foo == "a" or foo == "b" or "c" == bar or "d" == bar # Multiple targets +24 - foo == "a" or foo == "b" or "c" == bar or "d" == bar # Multiple targets 24 + foo == "a" or foo == "b" or bar in {"c", "d"} # Multiple targets -25 | | note: This is an unsafe fix and may change runtime behavior @@ -259,10 +233,8 @@ PLR1714 [*] Consider merging multiple comparisons: `foo.bar in {"a", "b"}`. | help: Merge multiple comparisons | -25 | - - foo.bar == "a" or foo.bar == "b" # Attributes. +26 - foo.bar == "a" or foo.bar == "b" # Attributes. 26 + foo.bar in {"a", "b"} # Attributes. -27 | | note: This is an unsafe fix and may change runtime behavior @@ -278,10 +250,8 @@ PLR1714 [*] Consider merging multiple comparisons: `bar in {"c", "d"}`. | help: Merge multiple comparisons | -60 | - - foo == "a" or ("c" == bar or "d" == bar) or foo == "b" # Multiple targets +61 - foo == "a" or ("c" == bar or "d" == bar) or foo == "b" # Multiple targets 61 + foo == "a" or (bar in {"c", "d"}) or foo == "b" # Multiple targets -62 | | note: This is an unsafe fix and may change runtime behavior @@ -297,10 +267,8 @@ PLR1714 [*] Consider merging multiple comparisons: `foo in {"a", "b"}`. | help: Merge multiple comparisons | -62 | - - foo == "a" or foo == "b" or "c" != bar and "d" != bar # Multiple targets +63 - foo == "a" or foo == "b" or "c" != bar and "d" != bar # Multiple targets 63 + foo in {"a", "b"} or "c" != bar and "d" != bar # Multiple targets -64 | | note: This is an unsafe fix and may change runtime behavior @@ -316,10 +284,8 @@ PLR1714 [*] Consider merging multiple comparisons: `bar not in {"c", "d"}`. | help: Merge multiple comparisons | -62 | - - foo == "a" or foo == "b" or "c" != bar and "d" != bar # Multiple targets +63 - foo == "a" or foo == "b" or "c" != bar and "d" != bar # Multiple targets 63 + foo == "a" or foo == "b" or bar not in {"c", "d"} # Multiple targets -64 | | note: This is an unsafe fix and may change runtime behavior @@ -335,10 +301,8 @@ PLR1714 [*] Consider merging multiple comparisons: `bar not in {"c", "d"}`. | help: Merge multiple comparisons | -64 | - - foo == "a" or ("c" != bar and "d" != bar) or foo == "b" # Multiple targets +65 - foo == "a" or ("c" != bar and "d" != bar) or foo == "b" # Multiple targets 65 + foo == "a" or (bar not in {"c", "d"}) or foo == "b" # Multiple targets -66 | | note: This is an unsafe fix and may change runtime behavior @@ -354,10 +318,8 @@ PLR1714 [*] Consider merging multiple comparisons: `foo in {1, True}`. | help: Merge multiple comparisons | -68 | - - foo == 1 or foo == True # Different types, same hashed value +69 - foo == 1 or foo == True # Different types, same hashed value 69 + foo in {1, True} # Different types, same hashed value -70 | | note: This is an unsafe fix and may change runtime behavior @@ -373,10 +335,8 @@ PLR1714 [*] Consider merging multiple comparisons: `foo in {1, 1.0}`. | help: Merge multiple comparisons | -70 | - - foo == 1 or foo == 1.0 # Different types, same hashed value +71 - foo == 1 or foo == 1.0 # Different types, same hashed value 71 + foo in {1, 1.0} # Different types, same hashed value -72 | | note: This is an unsafe fix and may change runtime behavior @@ -392,10 +352,8 @@ PLR1714 [*] Consider merging multiple comparisons: `foo in {False, 0}`. | help: Merge multiple comparisons | -72 | - - foo == False or foo == 0 # Different types, same hashed value +73 - foo == False or foo == 0 # Different types, same hashed value 73 + foo in {False, 0} # Different types, same hashed value -74 | | note: This is an unsafe fix and may change runtime behavior @@ -411,10 +369,8 @@ PLR1714 [*] Consider merging multiple comparisons: `foo in {0.0, 0j}`. | help: Merge multiple comparisons | -74 | - - foo == 0.0 or foo == 0j # Different types, same hashed value +75 - foo == 0.0 or foo == 0j # Different types, same hashed value 75 + foo in {0.0, 0j} # Different types, same hashed value -76 | | note: This is an unsafe fix and may change runtime behavior @@ -427,8 +383,7 @@ PLR1714 [*] Consider merging multiple comparisons: `foo in {"bar", "bar", "buzz" | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Merge multiple comparisons | -78 | - - foo == "bar" or foo == "bar" or foo == "buzz" # All but one members identical +79 - foo == "bar" or foo == "bar" or foo == "buzz" # All but one members identical 79 + foo in {"bar", "bar", "buzz"} # All but one members identical | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1716_boolean_chained_comparison.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1716_boolean_chained_comparison.py.snap index 3e6d4093a7393..f03bb1f71bd32 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1716_boolean_chained_comparison.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1716_boolean_chained_comparison.py.snap @@ -12,10 +12,8 @@ PLR1716 [*] Contains chained boolean comparison that can be simplified | help: Use a single compare expression | -7 | c = int(input()) - - if a < b and b < c: # [boolean-chained-comparison] +8 - if a < b and b < c: # [boolean-chained-comparison] 8 + if a < b < c: # [boolean-chained-comparison] -9 | pass | PLR1716 [*] Contains chained boolean comparison that can be simplified @@ -29,10 +27,8 @@ PLR1716 [*] Contains chained boolean comparison that can be simplified | help: Use a single compare expression | -13 | c = int(input()) - - if a < b and b <= c: # [boolean-chained-comparison] +14 - if a < b and b <= c: # [boolean-chained-comparison] 14 + if a < b <= c: # [boolean-chained-comparison] -15 | pass | PLR1716 [*] Contains chained boolean comparison that can be simplified @@ -46,10 +42,8 @@ PLR1716 [*] Contains chained boolean comparison that can be simplified | help: Use a single compare expression | -19 | c = int(input()) - - if a <= b and b < c: # [boolean-chained-comparison] +20 - if a <= b and b < c: # [boolean-chained-comparison] 20 + if a <= b < c: # [boolean-chained-comparison] -21 | pass | PLR1716 [*] Contains chained boolean comparison that can be simplified @@ -63,10 +57,8 @@ PLR1716 [*] Contains chained boolean comparison that can be simplified | help: Use a single compare expression | -25 | c = int(input()) - - if a <= b and b <= c: # [boolean-chained-comparison] +26 - if a <= b and b <= c: # [boolean-chained-comparison] 26 + if a <= b <= c: # [boolean-chained-comparison] -27 | pass | PLR1716 [*] Contains chained boolean comparison that can be simplified @@ -80,10 +72,8 @@ PLR1716 [*] Contains chained boolean comparison that can be simplified | help: Use a single compare expression | -35 | c = int(input()) - - if a > b and b > c: # [boolean-chained-comparison] +36 - if a > b and b > c: # [boolean-chained-comparison] 36 + if a > b > c: # [boolean-chained-comparison] -37 | pass | PLR1716 [*] Contains chained boolean comparison that can be simplified @@ -97,10 +87,8 @@ PLR1716 [*] Contains chained boolean comparison that can be simplified | help: Use a single compare expression | -41 | c = int(input()) - - if a >= b and b > c: # [boolean-chained-comparison] +42 - if a >= b and b > c: # [boolean-chained-comparison] 42 + if a >= b > c: # [boolean-chained-comparison] -43 | pass | PLR1716 [*] Contains chained boolean comparison that can be simplified @@ -114,10 +102,8 @@ PLR1716 [*] Contains chained boolean comparison that can be simplified | help: Use a single compare expression | -47 | c = int(input()) - - if a > b and b >= c: # [boolean-chained-comparison] +48 - if a > b and b >= c: # [boolean-chained-comparison] 48 + if a > b >= c: # [boolean-chained-comparison] -49 | pass | PLR1716 [*] Contains chained boolean comparison that can be simplified @@ -131,10 +117,8 @@ PLR1716 [*] Contains chained boolean comparison that can be simplified | help: Use a single compare expression | -53 | c = int(input()) - - if a >= b and b >= c: # [boolean-chained-comparison] +54 - if a >= b and b >= c: # [boolean-chained-comparison] 54 + if a >= b >= c: # [boolean-chained-comparison] -55 | pass | PLR1716 [*] Contains chained boolean comparison that can be simplified @@ -148,10 +132,8 @@ PLR1716 [*] Contains chained boolean comparison that can be simplified | help: Use a single compare expression | -64 | d = int(input()) - - if a < b and b < c and c < d: # [boolean-chained-comparison] +65 - if a < b and b < c and c < d: # [boolean-chained-comparison] 65 + if a < b < c and c < d: # [boolean-chained-comparison] -66 | pass | PLR1716 [*] Contains chained boolean comparison that can be simplified @@ -165,10 +147,8 @@ PLR1716 [*] Contains chained boolean comparison that can be simplified | help: Use a single compare expression | -64 | d = int(input()) - - if a < b and b < c and c < d: # [boolean-chained-comparison] +65 - if a < b and b < c and c < d: # [boolean-chained-comparison] 65 + if a < b and b < c < d: # [boolean-chained-comparison] -66 | pass | PLR1716 [*] Contains chained boolean comparison that can be simplified @@ -182,10 +162,8 @@ PLR1716 [*] Contains chained boolean comparison that can be simplified | help: Use a single compare expression | -72 | e = int(input()) - - if a < b and b < c and c < d and d < e: # [boolean-chained-comparison] +73 - if a < b and b < c and c < d and d < e: # [boolean-chained-comparison] 73 + if a < b < c and c < d and d < e: # [boolean-chained-comparison] -74 | pass | PLR1716 [*] Contains chained boolean comparison that can be simplified @@ -199,10 +177,8 @@ PLR1716 [*] Contains chained boolean comparison that can be simplified | help: Use a single compare expression | -72 | e = int(input()) - - if a < b and b < c and c < d and d < e: # [boolean-chained-comparison] +73 - if a < b and b < c and c < d and d < e: # [boolean-chained-comparison] 73 + if a < b and b < c < d and d < e: # [boolean-chained-comparison] -74 | pass | PLR1716 [*] Contains chained boolean comparison that can be simplified @@ -216,10 +192,8 @@ PLR1716 [*] Contains chained boolean comparison that can be simplified | help: Use a single compare expression | -72 | e = int(input()) - - if a < b and b < c and c < d and d < e: # [boolean-chained-comparison] +73 - if a < b and b < c and c < d and d < e: # [boolean-chained-comparison] 73 + if a < b and b < c and c < d < e: # [boolean-chained-comparison] -74 | pass | PLR1716 [*] Contains chained boolean comparison that can be simplified @@ -233,10 +207,8 @@ PLR1716 [*] Contains chained boolean comparison that can be simplified | help: Use a single compare expression | -122 | # fixes will balance parentheses - - (a < b) and b < c +123 - (a < b) and b < c 123 + (a < b < c) -124 | a < b and (b < c) | PLR1716 [*] Contains chained boolean comparison that can be simplified @@ -251,10 +223,8 @@ PLR1716 [*] Contains chained boolean comparison that can be simplified | help: Use a single compare expression | -123 | (a < b) and b < c - - a < b and (b < c) +124 - a < b and (b < c) 124 + (a < b < c) -125 | ((a < b) and b < c) | PLR1716 [*] Contains chained boolean comparison that can be simplified @@ -269,10 +239,8 @@ PLR1716 [*] Contains chained boolean comparison that can be simplified | help: Use a single compare expression | -124 | a < b and (b < c) - - ((a < b) and b < c) +125 - ((a < b) and b < c) 125 + ((a < b < c)) -126 | (a < b) and (b < c) | PLR1716 [*] Contains chained boolean comparison that can be simplified @@ -286,10 +254,8 @@ PLR1716 [*] Contains chained boolean comparison that can be simplified | help: Use a single compare expression | -125 | ((a < b) and b < c) - - (a < b) and (b < c) +126 - (a < b) and (b < c) 126 + (a < b < c) -127 | (((a < b))) and (b < c) | PLR1716 [*] Contains chained boolean comparison that can be simplified @@ -304,10 +270,8 @@ PLR1716 [*] Contains chained boolean comparison that can be simplified | help: Use a single compare expression | -126 | (a < b) and (b < c) - - (((a < b))) and (b < c) +127 - (((a < b))) and (b < c) 127 + (((a < b < c))) -128 | | PLR1716 [*] Contains chained boolean comparison that can be simplified @@ -322,10 +286,8 @@ PLR1716 [*] Contains chained boolean comparison that can be simplified | help: Use a single compare expression | -128 | - - (a= b: - - a = b +21 - if a >= b: +22 - a = b 21 + a = min(b, a) -22 | | PLR1730 [*] Replace `if` statement with `a = max(b, a)` @@ -32,11 +30,9 @@ PLR1730 [*] Replace `if` statement with `a = max(b, a)` | help: Replace with `a = max(b, a)` | -24 | # case 2: a = max(b, a) - - if a <= b: - - a = b +25 - if a <= b: +26 - a = b 25 + a = max(b, a) -26 | | PLR1730 [*] Replace `if` statement with `b = min(a, b)` @@ -51,11 +47,9 @@ PLR1730 [*] Replace `if` statement with `b = min(a, b)` | help: Replace with `b = min(a, b)` | -28 | # case 3: b = min(a, b) - - if a <= b: - - b = a +29 - if a <= b: +30 - b = a 29 + b = min(a, b) -30 | | PLR1730 [*] Replace `if` statement with `b = max(a, b)` @@ -70,11 +64,9 @@ PLR1730 [*] Replace `if` statement with `b = max(a, b)` | help: Replace with `b = max(a, b)` | -32 | # case 4: b = max(a, b) - - if a >= b: - - b = a +33 - if a >= b: +34 - b = a 33 + b = max(a, b) -34 | | PLR1730 [*] Replace `if` statement with `a = min(a, b)` @@ -89,11 +81,9 @@ PLR1730 [*] Replace `if` statement with `a = min(a, b)` | help: Replace with `a = min(a, b)` | -36 | # case 5: a = min(a, b) - - if a > b: - - a = b +37 - if a > b: +38 - a = b 37 + a = min(a, b) -38 | | PLR1730 [*] Replace `if` statement with `a = max(a, b)` @@ -108,11 +98,9 @@ PLR1730 [*] Replace `if` statement with `a = max(a, b)` | help: Replace with `a = max(a, b)` | -40 | # case 6: a = max(a, b) - - if a < b: - - a = b +41 - if a < b: +42 - a = b 41 + a = max(a, b) -42 | | PLR1730 [*] Replace `if` statement with `b = min(b, a)` @@ -127,11 +115,9 @@ PLR1730 [*] Replace `if` statement with `b = min(b, a)` | help: Replace with `b = min(b, a)` | -44 | # case 7: b = min(b, a) - - if a < b: - - b = a +45 - if a < b: +46 - b = a 45 + b = min(b, a) -46 | | PLR1730 [*] Replace `if` statement with `b = max(b, a)` @@ -143,11 +129,9 @@ PLR1730 [*] Replace `if` statement with `b = max(b, a)` | |_________^ help: Replace with `b = max(b, a)` | -48 | # case 8: b = max(b, a) - - if a > b: - - b = a +49 - if a > b: +50 - b = a 49 + b = max(b, a) -50 | | PLR1730 [*] Replace `if` statement with `value = max(value, 10)` @@ -162,11 +146,9 @@ PLR1730 [*] Replace `if` statement with `value = max(value, 10)` | help: Replace with `value = max(value, 10)` | -58 | # base case 6: value = max(value, 10) - - if value < 10: - - value = 10 +59 - if value < 10: +60 - value = 10 59 + value = max(value, 10) -60 | | PLR1730 [*] Replace `if` statement with `value = max(10, value)` @@ -181,11 +163,9 @@ PLR1730 [*] Replace `if` statement with `value = max(10, value)` | help: Replace with `value = max(10, value)` | -62 | # base case 2: value = max(10, value) - - if value <= 10: - - value = 10 +63 - if value <= 10: +64 - value = 10 63 + value = max(10, value) -64 | | PLR1730 [*] Replace `if` statement with `value = max(value, value2)` @@ -200,11 +180,9 @@ PLR1730 [*] Replace `if` statement with `value = max(value, value2)` | help: Replace with `value = max(value, value2)` | -66 | # base case 6: value = max(value, value2) - - if value < value2: - - value = value2 +67 - if value < value2: +68 - value = value2 67 + value = max(value, value2) -68 | | PLR1730 [*] Replace `if` statement with `value = min(value, 10)` @@ -219,11 +197,9 @@ PLR1730 [*] Replace `if` statement with `value = min(value, 10)` | help: Replace with `value = min(value, 10)` | -70 | # base case 5: value = min(value, 10) - - if value > 10: - - value = 10 +71 - if value > 10: +72 - value = 10 71 + value = min(value, 10) -72 | | PLR1730 [*] Replace `if` statement with `value = min(10, value)` @@ -238,11 +214,9 @@ PLR1730 [*] Replace `if` statement with `value = min(10, value)` | help: Replace with `value = min(10, value)` | -74 | # base case 1: value = min(10, value) - - if value >= 10: - - value = 10 +75 - if value >= 10: +76 - value = 10 75 + value = min(10, value) -76 | | PLR1730 [*] Replace `if` statement with `value = min(value, value2)` @@ -254,11 +228,9 @@ PLR1730 [*] Replace `if` statement with `value = min(value, value2)` | |__________________^ help: Replace with `value = min(value, value2)` | -78 | # base case 5: value = min(value, value2) - - if value > value2: - - value = value2 +79 - if value > value2: +80 - value = value2 79 + value = min(value, value2) -80 | | PLR1730 [*] Replace `if` statement with `A1.value = max(A1.value, 10)` @@ -272,11 +244,9 @@ PLR1730 [*] Replace `if` statement with `A1.value = max(A1.value, 10)` | help: Replace with `A1.value = max(A1.value, 10)` | -91 | - - if A1.value < 10: - - A1.value = 10 +92 - if A1.value < 10: +93 - A1.value = 10 92 + A1.value = max(A1.value, 10) -93 | | PLR1730 [*] Replace `if` statement with `A1.value = min(A1.value, 10)` @@ -289,11 +259,9 @@ PLR1730 [*] Replace `if` statement with `A1.value = min(A1.value, 10)` | |_________________^ help: Replace with `A1.value = min(A1.value, 10)` | -94 | - - if A1.value > 10: - - A1.value = 10 +95 - if A1.value > 10: +96 - A1.value = 10 95 + A1.value = min(A1.value, 10) -96 | | PLR1730 [*] Replace `if` statement with `A2 = max(A2, A1)` @@ -309,11 +277,9 @@ PLR1730 [*] Replace `if` statement with `A2 = max(A2, A1)` | help: Replace with `A2 = max(A2, A1)` | -118 | - - if A2 < A1: # [max-instead-of-if] - - A2 = A1 +119 - if A2 < A1: # [max-instead-of-if] +120 - A2 = A1 119 + A2 = max(A2, A1) -120 | | note: This is an unsafe fix and may change runtime behavior @@ -330,11 +296,9 @@ PLR1730 [*] Replace `if` statement with `A2 = max(A1, A2)` | help: Replace with `A2 = max(A1, A2)` | -121 | - - if A2 <= A1: # [max-instead-of-if] - - A2 = A1 +122 - if A2 <= A1: # [max-instead-of-if] +123 - A2 = A1 122 + A2 = max(A1, A2) -123 | | note: This is an unsafe fix and may change runtime behavior @@ -351,11 +315,9 @@ PLR1730 [*] Replace `if` statement with `A2 = min(A2, A1)` | help: Replace with `A2 = min(A2, A1)` | -124 | - - if A2 > A1: # [min-instead-of-if] - - A2 = A1 +125 - if A2 > A1: # [min-instead-of-if] +126 - A2 = A1 125 + A2 = min(A2, A1) -126 | | note: This is an unsafe fix and may change runtime behavior @@ -372,11 +334,9 @@ PLR1730 [*] Replace `if` statement with `A2 = min(A1, A2)` | help: Replace with `A2 = min(A1, A2)` | -127 | - - if A2 >= A1: # [min-instead-of-if] - - A2 = A1 +128 - if A2 >= A1: # [min-instead-of-if] +129 - A2 = A1 128 + A2 = min(A1, A2) -129 | | note: This is an unsafe fix and may change runtime behavior @@ -395,15 +355,10 @@ PLR1730 [*] Replace `if` statement with `min` call | help: Replace with `min` call | -190 | # Parenthesized expressions - - if value.attr > 3: - - ( 191 + ( -192 | value. -193 | attr - - ) = 3 +192 + value. +193 + attr 194 + ) = min(value.attr, 3) -195 | | PLR1730 [*] Replace `if` statement with `self._min = min(self._min, value)` @@ -418,11 +373,9 @@ PLR1730 [*] Replace `if` statement with `self._min = min(self._min, value)` | help: Replace with `self._min = min(self._min, value)` | -201 | def foo(self, value) -> None: - - if value < self._min: - - self._min = value +202 - if value < self._min: +203 - self._min = value 202 + self._min = min(self._min, value) -203 | if value > self._max: | PLR1730 [*] Replace `if` statement with `self._max = max(self._max, value)` @@ -438,11 +391,9 @@ PLR1730 [*] Replace `if` statement with `self._max = max(self._max, value)` | help: Replace with `self._max = max(self._max, value)` | -203 | self._min = value - - if value > self._max: - - self._max = value +204 - if value > self._max: +205 - self._max = value 204 + self._max = max(self._max, value) -205 | | PLR1730 [*] Replace `if` statement with `self._min = max(self._min, value)` @@ -458,11 +409,9 @@ PLR1730 [*] Replace `if` statement with `self._min = max(self._min, value)` | help: Replace with `self._min = max(self._min, value)` | -206 | - - if self._min < value: - - self._min = value +207 - if self._min < value: +208 - self._min = value 207 + self._min = max(self._min, value) -208 | if self._max > value: | PLR1730 [*] Replace `if` statement with `self._max = min(self._max, value)` @@ -478,11 +427,9 @@ PLR1730 [*] Replace `if` statement with `self._max = min(self._max, value)` | help: Replace with `self._max = min(self._max, value)` | -208 | self._min = value - - if self._max > value: - - self._max = value +209 - if self._max > value: +210 - self._max = value 209 + self._max = min(self._max, value) -210 | | PLR1730 [*] Replace `if` statement with `self._min = min(value, self._min)` @@ -498,11 +445,9 @@ PLR1730 [*] Replace `if` statement with `self._min = min(value, self._min)` | help: Replace with `self._min = min(value, self._min)` | -211 | - - if value <= self._min: - - self._min = value +212 - if value <= self._min: +213 - self._min = value 212 + self._min = min(value, self._min) -213 | if value >= self._max: | PLR1730 [*] Replace `if` statement with `self._max = max(value, self._max)` @@ -518,11 +463,9 @@ PLR1730 [*] Replace `if` statement with `self._max = max(value, self._max)` | help: Replace with `self._max = max(value, self._max)` | -213 | self._min = value - - if value >= self._max: - - self._max = value +214 - if value >= self._max: +215 - self._max = value 214 + self._max = max(value, self._max) -215 | | PLR1730 [*] Replace `if` statement with `self._min = max(value, self._min)` @@ -538,11 +481,9 @@ PLR1730 [*] Replace `if` statement with `self._min = max(value, self._min)` | help: Replace with `self._min = max(value, self._min)` | -216 | - - if self._min <= value: - - self._min = value +217 - if self._min <= value: +218 - self._min = value 217 + self._min = max(value, self._min) -218 | if self._max >= value: | PLR1730 [*] Replace `if` statement with `self._max = min(value, self._max)` @@ -555,11 +496,9 @@ PLR1730 [*] Replace `if` statement with `self._max = min(value, self._max)` | |_____________________________^ help: Replace with `self._max = min(value, self._max)` | -218 | self._min = value - - if self._max >= value: - - self._max = value +219 - if self._max >= value: +220 - self._max = value 219 + self._max = min(value, self._max) -220 | | PLR1730 [*] Replace `if` statement with `counter["a"] = max(counter["b"], counter["a"])` @@ -574,11 +513,9 @@ PLR1730 [*] Replace `if` statement with `counter["a"] = max(counter["b"], counte | help: Replace with `counter["a"] = max(counter["b"], counter["a"])` | -225 | # base case 2: counter["a"] = max(counter["b"], counter["a"]) - - if counter["a"] <= counter["b"]: - - counter["a"] = counter["b"] +226 - if counter["a"] <= counter["b"]: +227 - counter["a"] = counter["b"] 226 + counter["a"] = max(counter["b"], counter["a"]) -227 | | PLR1730 [*] Replace `if` statement with `counter["b"] = min(counter["a"], counter["b"])` @@ -593,11 +530,9 @@ PLR1730 [*] Replace `if` statement with `counter["b"] = min(counter["a"], counte | help: Replace with `counter["b"] = min(counter["a"], counter["b"])` | -229 | # case 3: counter["b"] = min(counter["a"], counter["b"]) - - if counter["a"] <= counter["b"]: - - counter["b"] = counter["a"] +230 - if counter["a"] <= counter["b"]: +231 - counter["b"] = counter["a"] 230 + counter["b"] = min(counter["a"], counter["b"]) -231 | | PLR1730 [*] Replace `if` statement with `counter["b"] = max(counter["b"], counter["a"])` @@ -612,11 +547,9 @@ PLR1730 [*] Replace `if` statement with `counter["b"] = max(counter["b"], counte | help: Replace with `counter["b"] = max(counter["b"], counter["a"])` | -233 | # case 5: counter["a"] = min(counter["a"], counter["b"]) - - if counter["a"] > counter["b"]: - - counter["b"] = counter["a"] +234 - if counter["a"] > counter["b"]: +235 - counter["b"] = counter["a"] 234 + counter["b"] = max(counter["b"], counter["a"]) -235 | | PLR1730 [*] Replace `if` statement with `counter["b"] = max(counter["b"], counter["a"])` @@ -631,11 +564,9 @@ PLR1730 [*] Replace `if` statement with `counter["b"] = max(counter["b"], counte | help: Replace with `counter["b"] = max(counter["b"], counter["a"])` | -237 | # case 8: counter["a"] = max(counter["b"], counter["a"]) - - if counter["a"] > counter["b"]: - - counter["b"] = counter["a"] +238 - if counter["a"] > counter["b"]: +239 - counter["b"] = counter["a"] 238 + counter["b"] = max(counter["b"], counter["a"]) -239 | | PLR1730 [*] Replace `if` statement with `a = min(b, a)` @@ -652,12 +583,10 @@ PLR1730 [*] Replace `if` statement with `a = min(b, a)` | help: Replace with `a = min(b, a)` | -244 | a, b = [], [] - - if a >= b: - - # very important comment - - a = b +245 - if a >= b: +246 - # very important comment +247 - a = b 245 + a = min(b, a) -246 | | note: This is an unsafe fix and may change runtime behavior @@ -670,8 +599,7 @@ PLR1730 [*] Replace `if` statement with `a = min(b, a)` | |_________^ help: Replace with `a = min(b, a)` | -249 | # fix marked safe as preserve comments - - if a >= b: - - a = b # very important comment +250 - if a >= b: +251 - a = b # very important comment 250 + a = min(b, a) # very important comment | diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1733_unnecessary_dict_index_lookup.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1733_unnecessary_dict_index_lookup.py.snap index 987539e90e848..417f378f5ee01 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1733_unnecessary_dict_index_lookup.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1733_unnecessary_dict_index_lookup.py.snap @@ -12,10 +12,8 @@ PLR1733 [*] Unnecessary lookup of dictionary value by key | help: Use existing variable | -3 | def fix_these(): - - [FRUITS[fruit_name] for fruit_name, fruit_count in FRUITS.items()] # PLR1733 +4 - [FRUITS[fruit_name] for fruit_name, fruit_count in FRUITS.items()] # PLR1733 4 + [fruit_count for fruit_name, fruit_count in FRUITS.items()] # PLR1733 -5 | {FRUITS[fruit_name] for fruit_name, fruit_count in FRUITS.items()} # PLR1733 | PLR1733 [*] Unnecessary lookup of dictionary value by key @@ -29,10 +27,8 @@ PLR1733 [*] Unnecessary lookup of dictionary value by key | help: Use existing variable | -4 | [FRUITS[fruit_name] for fruit_name, fruit_count in FRUITS.items()] # PLR1733 - - {FRUITS[fruit_name] for fruit_name, fruit_count in FRUITS.items()} # PLR1733 +5 - {FRUITS[fruit_name] for fruit_name, fruit_count in FRUITS.items()} # PLR1733 5 + {fruit_count for fruit_name, fruit_count in FRUITS.items()} # PLR1733 -6 | {fruit_name: FRUITS[fruit_name] for fruit_name, fruit_count in FRUITS.items()} # PLR1733 | PLR1733 [*] Unnecessary lookup of dictionary value by key @@ -47,10 +43,8 @@ PLR1733 [*] Unnecessary lookup of dictionary value by key | help: Use existing variable | -5 | {FRUITS[fruit_name] for fruit_name, fruit_count in FRUITS.items()} # PLR1733 - - {fruit_name: FRUITS[fruit_name] for fruit_name, fruit_count in FRUITS.items()} # PLR1733 +6 - {fruit_name: FRUITS[fruit_name] for fruit_name, fruit_count in FRUITS.items()} # PLR1733 6 + {fruit_name: fruit_count for fruit_name, fruit_count in FRUITS.items()} # PLR1733 -7 | | PLR1733 [*] Unnecessary lookup of dictionary value by key @@ -63,12 +57,10 @@ PLR1733 [*] Unnecessary lookup of dictionary value by key 11 | assert FRUITS[fruit_name] == "pear" # PLR1733 | help: Use existing variable - | -8 | for fruit_name, fruit_count in FRUITS.items(): - - print(FRUITS[fruit_name]) # PLR1733 -9 + print(fruit_count) # PLR1733 -10 | blah = FRUITS[fruit_name] # PLR1733 - | + | +8 ~ for fruit_name, fruit_count in FRUITS.items(): +9 ~ print(fruit_count) # PLR1733 + | PLR1733 [*] Unnecessary lookup of dictionary value by key --> unnecessary_dict_index_lookup.py:10:16 @@ -81,10 +73,9 @@ PLR1733 [*] Unnecessary lookup of dictionary value by key | help: Use existing variable | -9 | print(FRUITS[fruit_name]) # PLR1733 - - blah = FRUITS[fruit_name] # PLR1733 -10 + blah = fruit_count # PLR1733 -11 | assert FRUITS[fruit_name] == "pear" # PLR1733 + 8 ~ for fruit_name, fruit_count in FRUITS.items(): + 9 | print(FRUITS[fruit_name]) # PLR1733 +10 ~ blah = fruit_count # PLR1733 | PLR1733 [*] Unnecessary lookup of dictionary value by key @@ -96,10 +87,10 @@ PLR1733 [*] Unnecessary lookup of dictionary value by key | ^^^^^^^^^^^^^^^^^^ help: Use existing variable | + 8 ~ for fruit_name, fruit_count in FRUITS.items(): + 9 | print(FRUITS[fruit_name]) # PLR1733 10 | blah = FRUITS[fruit_name] # PLR1733 - - assert FRUITS[fruit_name] == "pear" # PLR1733 -11 + assert fruit_count == "pear" # PLR1733 -12 | +11 ~ assert fruit_count == "pear" # PLR1733 | PLR1733 [*] Unnecessary lookup of dictionary value by key @@ -114,10 +105,11 @@ PLR1733 [*] Unnecessary lookup of dictionary value by key | help: Use existing variable | +46 ~ for label, array in value_arrays.items(): +47 | mapped_label = client_label_map(label) +48 | if mapped_label in mapped_arrays: 49 | for i in range(len(array)): - - mapped_arrays[mapped_label][i] += value_arrays[label][i] # PLR1733 -50 + mapped_arrays[mapped_label][i] += array[i] # PLR1733 -51 | else: +50 ~ mapped_arrays[mapped_label][i] += array[i] # PLR1733 | PLR1733 [*] Unnecessary lookup of dictionary value by key @@ -131,8 +123,9 @@ PLR1733 [*] Unnecessary lookup of dictionary value by key | help: Use existing variable | +46 ~ for label, array in value_arrays.items(): +47 | mapped_label = client_label_map(label) + … 51 | else: - - mapped_arrays[mapped_label] = [value_arrays[label][i] for i in range(len(array))] # PLR1733 -52 + mapped_arrays[mapped_label] = [array[i] for i in range(len(array))] # PLR1733 -53 | return mapped_arrays +52 ~ mapped_arrays[mapped_label] = [array[i] for i in range(len(array))] # PLR1733 | diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1736_unnecessary_list_index_lookup.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1736_unnecessary_list_index_lookup.py.snap index 837f1e65d4d5d..e785bb535c761 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1736_unnecessary_list_index_lookup.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR1736_unnecessary_list_index_lookup.py.snap @@ -12,10 +12,8 @@ PLR1736 [*] List index lookup in `enumerate()` loop | help: Use the loop variable directly | -6 | def fix_these(): - - [letters[index] for index, letter in enumerate(letters)] # PLR1736 +7 - [letters[index] for index, letter in enumerate(letters)] # PLR1736 7 + [letter for index, letter in enumerate(letters)] # PLR1736 -8 | {letters[index] for index, letter in enumerate(letters)} # PLR1736 | PLR1736 [*] List index lookup in `enumerate()` loop @@ -29,10 +27,8 @@ PLR1736 [*] List index lookup in `enumerate()` loop | help: Use the loop variable directly | -7 | [letters[index] for index, letter in enumerate(letters)] # PLR1736 - - {letters[index] for index, letter in enumerate(letters)} # PLR1736 +8 - {letters[index] for index, letter in enumerate(letters)} # PLR1736 8 + {letter for index, letter in enumerate(letters)} # PLR1736 -9 | {letter: letters[index] for index, letter in enumerate(letters)} # PLR1736 | PLR1736 [*] List index lookup in `enumerate()` loop @@ -46,12 +42,10 @@ PLR1736 [*] List index lookup in `enumerate()` loop 11 | for index, letter in enumerate(letters): | help: Use the loop variable directly - | -8 | {letters[index] for index, letter in enumerate(letters)} # PLR1736 - - {letter: letters[index] for index, letter in enumerate(letters)} # PLR1736 -9 + {letter: letter for index, letter in enumerate(letters)} # PLR1736 -10 | - | + | +9 - {letter: letters[index] for index, letter in enumerate(letters)} # PLR1736 +9 + {letter: letter for index, letter in enumerate(letters)} # PLR1736 + | PLR1736 [*] List index lookup in `enumerate()` loop --> unnecessary_list_index_lookup.py:12:15 @@ -64,10 +58,8 @@ PLR1736 [*] List index lookup in `enumerate()` loop | help: Use the loop variable directly | -11 | for index, letter in enumerate(letters): - - print(letters[index]) # PLR1736 -12 + print(letter) # PLR1736 -13 | blah = letters[index] # PLR1736 +11 ~ for index, letter in enumerate(letters): +12 ~ print(letter) # PLR1736 | PLR1736 [*] List index lookup in `enumerate()` loop @@ -81,10 +73,9 @@ PLR1736 [*] List index lookup in `enumerate()` loop | help: Use the loop variable directly | +11 ~ for index, letter in enumerate(letters): 12 | print(letters[index]) # PLR1736 - - blah = letters[index] # PLR1736 -13 + blah = letter # PLR1736 -14 | assert letters[index] == "d" # PLR1736 +13 ~ blah = letter # PLR1736 | PLR1736 [*] List index lookup in `enumerate()` loop @@ -99,10 +90,10 @@ PLR1736 [*] List index lookup in `enumerate()` loop | help: Use the loop variable directly | +11 ~ for index, letter in enumerate(letters): +12 | print(letters[index]) # PLR1736 13 | blah = letters[index] # PLR1736 - - assert letters[index] == "d" # PLR1736 -14 + assert letter == "d" # PLR1736 -15 | +14 ~ assert letter == "d" # PLR1736 | PLR1736 [*] List index lookup in `enumerate()` loop @@ -116,10 +107,8 @@ PLR1736 [*] List index lookup in `enumerate()` loop | help: Use the loop variable directly | -16 | for index, letter in builtins.enumerate(letters): - - print(letters[index]) # PLR1736 -17 + print(letter) # PLR1736 -18 | blah = letters[index] # PLR1736 +16 ~ for index, letter in builtins.enumerate(letters): +17 ~ print(letter) # PLR1736 | PLR1736 [*] List index lookup in `enumerate()` loop @@ -133,10 +122,9 @@ PLR1736 [*] List index lookup in `enumerate()` loop | help: Use the loop variable directly | +16 ~ for index, letter in builtins.enumerate(letters): 17 | print(letters[index]) # PLR1736 - - blah = letters[index] # PLR1736 -18 + blah = letter # PLR1736 -19 | assert letters[index] == "d" # PLR1736 +18 ~ blah = letter # PLR1736 | PLR1736 [*] List index lookup in `enumerate()` loop @@ -148,10 +136,10 @@ PLR1736 [*] List index lookup in `enumerate()` loop | ^^^^^^^^^^^^^^ help: Use the loop variable directly | +16 ~ for index, letter in builtins.enumerate(letters): +17 | print(letters[index]) # PLR1736 18 | blah = letters[index] # PLR1736 - - assert letters[index] == "d" # PLR1736 -19 + assert letter == "d" # PLR1736 -20 | +19 ~ assert letter == "d" # PLR1736 | PLR1736 [*] List index lookup in `enumerate()` loop @@ -166,10 +154,8 @@ PLR1736 [*] List index lookup in `enumerate()` loop | help: Use the loop variable directly | -73 | for index, list_item in enumerate(some_list, start=0): - - print(some_list[index]) -74 + print(list_item) -75 | +73 ~ for index, list_item in enumerate(some_list, start=0): +74 ~ print(list_item) | PLR1736 [*] List index lookup in `enumerate()` loop @@ -181,10 +167,8 @@ PLR1736 [*] List index lookup in `enumerate()` loop | ^^^^^^^^^^^^^^^^ help: Use the loop variable directly | -77 | for index, list_item in enumerate(some_list): - - print(some_list[index]) -78 + print(list_item) -79 | +77 ~ for index, list_item in enumerate(some_list): +78 ~ print(list_item) | PLR1736 [*] List index lookup in `enumerate()` loop @@ -196,7 +180,6 @@ PLR1736 [*] List index lookup in `enumerate()` loop | ^^^^^^^^^^^^^^^^^^^ help: Use the loop variable directly | -84 | for index, column_name in enumerate(column_names): - - _ = data[column_names[index]] # PLR1736 -85 + _ = data[column_name] # PLR1736 +84 ~ for index, column_name in enumerate(column_names): +85 ~ _ = data[column_name] # PLR1736 | diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR2044_empty_comment.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR2044_empty_comment.py.snap index da0769a521903..769f2c9d511b7 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR2044_empty_comment.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR2044_empty_comment.py.snap @@ -13,9 +13,7 @@ PLR2044 [*] Line with empty comment | help: Delete the empty comment | -2 | # this line is also OK, but the three following lines are not - - # -3 | # +3 - # | PLR2044 [*] Line with empty comment @@ -29,9 +27,7 @@ PLR2044 [*] Line with empty comment | help: Delete the empty comment | -3 | # - - # -4 | # +4 - # | PLR2044 [*] Line with empty comment @@ -46,9 +42,7 @@ PLR2044 [*] Line with empty comment | help: Delete the empty comment | -4 | # - - # -5 | +5 - # | PLR2044 [*] Line with empty comment @@ -59,10 +53,8 @@ PLR2044 [*] Line with empty comment | ^ help: Delete the empty comment | -17 | def foo(): # this comment is OK, the one below is not - - pass # +18 - pass # 18 + pass -19 | | PLR2044 [*] Line with empty comment @@ -76,9 +68,7 @@ PLR2044 [*] Line with empty comment | help: Delete the empty comment | -44 | # - - # -45 | +44 - # | PLR2044 [*] Line with empty comment @@ -92,9 +82,7 @@ PLR2044 [*] Line with empty comment | help: Delete the empty comment | -44 | # - - # -45 | +45 - # | PLR2044 [*] Line with empty comment @@ -105,7 +93,6 @@ PLR2044 [*] Line with empty comment | ^ help: Delete the empty comment | -57 | α = 1 - - α# +58 - α# 58 + α | diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR2044_empty_comment_line_continuation.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR2044_empty_comment_line_continuation.py.snap index 15bcc33b096d3..3ea5261bf3882 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR2044_empty_comment_line_continuation.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR2044_empty_comment_line_continuation.py.snap @@ -11,8 +11,7 @@ PLR2044 [*] Line with empty comment | help: Delete the empty comment | - - # -1 | x = 0 \ +1 - # | PLR2044 [*] Line with empty comment @@ -27,8 +26,5 @@ PLR2044 [*] Line with empty comment | help: Delete the empty comment | -2 | x = 0 \ - - # -3 + -4 | +1 +3 - # | diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR5501_collapsible_else_if.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR5501_collapsible_else_if.py.snap index 7d26d79e5e5c3..19208d1e37fef 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR5501_collapsible_else_if.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR5501_collapsible_else_if.py.snap @@ -13,13 +13,8 @@ PLR5501 [*] Use `elif` instead of `else` then `if`, to reduce indentation | help: Convert to `elif` | -36 | pass - - else: - - if 2: - - pass 37 + elif 2: 38 + pass -39 | | PLR5501 [*] Use `elif` instead of `else` then `if`, to reduce indentation @@ -35,16 +30,10 @@ PLR5501 [*] Use `elif` instead of `else` then `if`, to reduce indentation | help: Convert to `elif` | -44 | pass 45 + elif 2: 46 + pass -47 | else: - - if 2: - - pass - - else: - - pass +47 + else: 48 + pass -49 | | PLR5501 [*] Use `elif` instead of `else` then `if`, to reduce indentation @@ -61,18 +50,11 @@ PLR5501 [*] Use `elif` instead of `else` then `if`, to reduce indentation | help: Convert to `elif` | -54 | pass 55 + # inner comment -56 + elif 2: +56 ~ elif 2: 57 + pass -58 | else: - - # inner comment - - if 2: - - pass - - else: - - pass # final pass comment +58 + else: 59 + pass # final pass comment -60 | | PLR5501 [*] Use `elif` instead of `else` then `if`, to reduce indentation @@ -88,16 +70,10 @@ PLR5501 [*] Use `elif` instead of `else` then `if`, to reduce indentation | help: Convert to `elif` | -68 | print(2) 69 + elif True: 70 + print(3) -71 | else: - - if True: - - print(3) - - else: - - print(4) +71 + else: 72 + print(4) -73 | | PLR5501 [*] Use `elif` instead of `else` then `if`, to reduce indentation @@ -112,13 +88,8 @@ PLR5501 [*] Use `elif` instead of `else` then `if`, to reduce indentation | help: Convert to `elif` | -78 | pass - - else: - - if 2: pass - - else: pass 79 + elif 2: pass 80 + else: pass -81 | | PLR5501 [*] Use `elif` instead of `else` then `if`, to reduce indentation @@ -134,14 +105,9 @@ PLR5501 [*] Use `elif` instead of `else` then `if`, to reduce indentation | help: Convert to `elif` | -86 | pass 87 + elif 2: pass -88 | else: - - if 2: pass - - else: - - pass +88 + else: 89 + pass -90 | | PLR5501 [*] Use `elif` instead of `else` then `if`, to reduce indentation @@ -157,15 +123,9 @@ PLR5501 [*] Use `elif` instead of `else` then `if`, to reduce indentation | help: Convert to `elif` | -95 | pass - - else: - - if 2: - - pass - - else: pass 96 + elif 2: 97 + pass 98 + else: pass -99 | | PLR5501 [*] Use `elif` instead of `else` then `if`, to reduce indentation @@ -183,20 +143,12 @@ PLR5501 [*] Use `elif` instead of `else` then `if`, to reduce indentation | help: Convert to `elif` | -104 | pass 105 + # inner comment which happens 106 + # to be longer than one line -107 + elif 2: +107 ~ elif 2: 108 + pass -109 | else: - - # inner comment which happens - - # to be longer than one line - - if 2: - - pass - - else: - - pass # final pass comment +109 + else: 110 + pass # final pass comment -111 | | PLR5501 [*] Use `elif` instead of `else` then `if`, to reduce indentation @@ -213,18 +165,11 @@ PLR5501 [*] Use `elif` instead of `else` then `if`, to reduce indentation | help: Convert to `elif` | -116 | pass 117 + # inner comment which happens to be overly indented -118 + elif 2: +118 ~ elif 2: 119 + pass -120 | else: - - # inner comment which happens to be overly indented - - if 2: - - pass - - else: - - pass # final pass comment +120 + else: 121 + pass # final pass comment -122 | | PLR5501 [*] Use `elif` instead of `else` then `if`, to reduce indentation @@ -241,18 +186,11 @@ PLR5501 [*] Use `elif` instead of `else` then `if`, to reduce indentation | help: Convert to `elif` | -127 | pass - - else: -128 | # inner comment which happens to be under indented - - if 2: - - pass - - else: - - pass # final pass comment -129 + elif 2: +128 + # inner comment which happens to be under indented +129 ~ elif 2: 130 + pass 131 + else: 132 + pass # final pass comment -133 | | PLR5501 [*] Use `elif` instead of `else` then `if`, to reduce indentation @@ -271,19 +209,11 @@ PLR5501 [*] Use `elif` instead of `else` then `if`, to reduce indentation | help: Convert to `elif` | -138 | pass 139 + # inner comment which has mixed 140 + # indentation levels 141 + # which is pretty weird -142 + elif 2: +142 ~ elif 2: 143 + pass -144 | else: - - # inner comment which has mixed - - # indentation levels - - # which is pretty weird - - if 2: - - pass - - else: - - pass # final pass comment +144 + else: 145 + pass # final pass comment | diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR6104_non_augmented_assignment.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR6104_non_augmented_assignment.py.snap index f690326bdca9b..829d4c6420962 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR6104_non_augmented_assignment.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR6104_non_augmented_assignment.py.snap @@ -13,10 +13,8 @@ PLR6104 [*] Use `+=` to perform an augmented assignment directly | help: Replace with augmented assignment | -15 | - - some_string = some_string + "a very long end of string" +16 - some_string = some_string + "a very long end of string" 16 + some_string += "a very long end of string" -17 | index = index - 1 | note: This is an unsafe fix and may change runtime behavior @@ -31,10 +29,8 @@ PLR6104 [*] Use `-=` to perform an augmented assignment directly | help: Replace with augmented assignment | -16 | some_string = some_string + "a very long end of string" - - index = index - 1 +17 - index = index - 1 17 + index -= 1 -18 | a_list = a_list + ["to concat"] | note: This is an unsafe fix and may change runtime behavior @@ -50,10 +46,8 @@ PLR6104 [*] Use `+=` to perform an augmented assignment directly | help: Replace with augmented assignment | -17 | index = index - 1 - - a_list = a_list + ["to concat"] +18 - a_list = a_list + ["to concat"] 18 + a_list += ["to concat"] -19 | some_set = some_set | {"to concat"} | note: This is an unsafe fix and may change runtime behavior @@ -69,10 +63,8 @@ PLR6104 [*] Use `|=` to perform an augmented assignment directly | help: Replace with augmented assignment | -18 | a_list = a_list + ["to concat"] - - some_set = some_set | {"to concat"} +19 - some_set = some_set | {"to concat"} 19 + some_set |= {"to concat"} -20 | to_multiply = to_multiply * 5 | note: This is an unsafe fix and may change runtime behavior @@ -88,10 +80,8 @@ PLR6104 [*] Use `*=` to perform an augmented assignment directly | help: Replace with augmented assignment | -19 | some_set = some_set | {"to concat"} - - to_multiply = to_multiply * 5 +20 - to_multiply = to_multiply * 5 20 + to_multiply *= 5 -21 | to_multiply = 5 * to_multiply | note: This is an unsafe fix and may change runtime behavior @@ -107,10 +97,8 @@ PLR6104 [*] Use `*=` to perform an augmented assignment directly | help: Replace with augmented assignment | -20 | to_multiply = to_multiply * 5 - - to_multiply = 5 * to_multiply +21 - to_multiply = 5 * to_multiply 21 + to_multiply *= 5 -22 | to_multiply = to_multiply * to_multiply | note: This is an unsafe fix and may change runtime behavior @@ -126,10 +114,8 @@ PLR6104 [*] Use `*=` to perform an augmented assignment directly | help: Replace with augmented assignment | -21 | to_multiply = 5 * to_multiply - - to_multiply = to_multiply * to_multiply +22 - to_multiply = to_multiply * to_multiply 22 + to_multiply *= to_multiply -23 | to_divide = to_divide / 5 | note: This is an unsafe fix and may change runtime behavior @@ -145,10 +131,8 @@ PLR6104 [*] Use `/=` to perform an augmented assignment directly | help: Replace with augmented assignment | -22 | to_multiply = to_multiply * to_multiply - - to_divide = to_divide / 5 +23 - to_divide = to_divide / 5 23 + to_divide /= 5 -24 | to_divide = to_divide // 5 | note: This is an unsafe fix and may change runtime behavior @@ -164,10 +148,8 @@ PLR6104 [*] Use `//=` to perform an augmented assignment directly | help: Replace with augmented assignment | -23 | to_divide = to_divide / 5 - - to_divide = to_divide // 5 +24 - to_divide = to_divide // 5 24 + to_divide //= 5 -25 | to_cube = to_cube**3 | note: This is an unsafe fix and may change runtime behavior @@ -183,10 +165,8 @@ PLR6104 [*] Use `**=` to perform an augmented assignment directly | help: Replace with augmented assignment | -24 | to_divide = to_divide // 5 - - to_cube = to_cube**3 +25 - to_cube = to_cube**3 25 + to_cube **= 3 -26 | to_cube = 3**to_cube | note: This is an unsafe fix and may change runtime behavior @@ -202,10 +182,8 @@ PLR6104 [*] Use `**=` to perform an augmented assignment directly | help: Replace with augmented assignment | -26 | to_cube = 3**to_cube - - to_cube = to_cube**to_cube +27 - to_cube = to_cube**to_cube 27 + to_cube **= to_cube -28 | timeDiffSeconds = timeDiffSeconds % 60 | note: This is an unsafe fix and may change runtime behavior @@ -221,10 +199,8 @@ PLR6104 [*] Use `%=` to perform an augmented assignment directly | help: Replace with augmented assignment | -27 | to_cube = to_cube**to_cube - - timeDiffSeconds = timeDiffSeconds % 60 +28 - timeDiffSeconds = timeDiffSeconds % 60 28 + timeDiffSeconds %= 60 -29 | flags = flags & 0x1 | note: This is an unsafe fix and may change runtime behavior @@ -240,10 +216,8 @@ PLR6104 [*] Use `&=` to perform an augmented assignment directly | help: Replace with augmented assignment | -28 | timeDiffSeconds = timeDiffSeconds % 60 - - flags = flags & 0x1 +29 - flags = flags & 0x1 29 + flags &= 0x1 -30 | flags = flags | 0x1 | note: This is an unsafe fix and may change runtime behavior @@ -259,10 +233,8 @@ PLR6104 [*] Use `|=` to perform an augmented assignment directly | help: Replace with augmented assignment | -29 | flags = flags & 0x1 - - flags = flags | 0x1 +30 - flags = flags | 0x1 30 + flags |= 0x1 -31 | flags = flags ^ 0x1 | note: This is an unsafe fix and may change runtime behavior @@ -278,10 +250,8 @@ PLR6104 [*] Use `^=` to perform an augmented assignment directly | help: Replace with augmented assignment | -30 | flags = flags | 0x1 - - flags = flags ^ 0x1 +31 - flags = flags ^ 0x1 31 + flags ^= 0x1 -32 | flags = flags << 1 | note: This is an unsafe fix and may change runtime behavior @@ -297,10 +267,8 @@ PLR6104 [*] Use `<<=` to perform an augmented assignment directly | help: Replace with augmented assignment | -31 | flags = flags ^ 0x1 - - flags = flags << 1 +32 - flags = flags << 1 32 + flags <<= 1 -33 | flags = flags >> 1 | note: This is an unsafe fix and may change runtime behavior @@ -316,10 +284,8 @@ PLR6104 [*] Use `>>=` to perform an augmented assignment directly | help: Replace with augmented assignment | -32 | flags = flags << 1 - - flags = flags >> 1 +33 - flags = flags >> 1 33 + flags >>= 1 -34 | mat1 = mat1 @ mat2 | note: This is an unsafe fix and may change runtime behavior @@ -334,10 +300,8 @@ PLR6104 [*] Use `@=` to perform an augmented assignment directly | help: Replace with augmented assignment | -33 | flags = flags >> 1 - - mat1 = mat1 @ mat2 +34 - mat1 = mat1 @ mat2 34 + mat1 @= mat2 -35 | a_list[1] = a_list[1] + 1 | note: This is an unsafe fix and may change runtime behavior @@ -353,10 +317,8 @@ PLR6104 [*] Use `+=` to perform an augmented assignment directly | help: Replace with augmented assignment | -34 | mat1 = mat1 @ mat2 - - a_list[1] = a_list[1] + 1 +35 - a_list[1] = a_list[1] + 1 35 + a_list[1] += 1 -36 | | note: This is an unsafe fix and may change runtime behavior @@ -372,10 +334,8 @@ PLR6104 [*] Use `*=` to perform an augmented assignment directly | help: Replace with augmented assignment | -36 | - - a_list[0:2] = a_list[0:2] * 3 +37 - a_list[0:2] = a_list[0:2] * 3 37 + a_list[0:2] *= 3 -38 | a_list[:2] = a_list[:2] * 3 | note: This is an unsafe fix and may change runtime behavior @@ -390,10 +350,8 @@ PLR6104 [*] Use `*=` to perform an augmented assignment directly | help: Replace with augmented assignment | -37 | a_list[0:2] = a_list[0:2] * 3 - - a_list[:2] = a_list[:2] * 3 +38 - a_list[:2] = a_list[:2] * 3 38 + a_list[:2] *= 3 -39 | a_list[1:] = a_list[1:] * 3 | note: This is an unsafe fix and may change runtime behavior @@ -408,10 +366,8 @@ PLR6104 [*] Use `*=` to perform an augmented assignment directly | help: Replace with augmented assignment | -38 | a_list[:2] = a_list[:2] * 3 - - a_list[1:] = a_list[1:] * 3 +39 - a_list[1:] = a_list[1:] * 3 39 + a_list[1:] *= 3 -40 | a_list[:] = a_list[:] * 3 | note: This is an unsafe fix and may change runtime behavior @@ -427,10 +383,8 @@ PLR6104 [*] Use `*=` to perform an augmented assignment directly | help: Replace with augmented assignment | -39 | a_list[1:] = a_list[1:] * 3 - - a_list[:] = a_list[:] * 3 +40 - a_list[:] = a_list[:] * 3 40 + a_list[:] *= 3 -41 | | note: This is an unsafe fix and may change runtime behavior @@ -443,10 +397,8 @@ PLR6104 [*] Use `*=` to perform an augmented assignment directly | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with augmented assignment | -41 | - - index = index * (index + 10) +42 - index = index * (index + 10) 42 + index *= (index + 10) -43 | | note: This is an unsafe fix and may change runtime behavior @@ -459,10 +411,8 @@ PLR6104 [*] Use `+=` to perform an augmented assignment directly | ^^^^^^^^^^^^^^^^^^^ help: Replace with augmented assignment | -46 | def t(self): - - self.a = self.a + 1 +47 - self.a = self.a + 1 47 + self.a += 1 -48 | | note: This is an unsafe fix and may change runtime behavior @@ -474,10 +424,8 @@ PLR6104 [*] Use `+=` to perform an augmented assignment directly | ^^^^^^^^^^^^^^^^^ help: Replace with augmented assignment | -50 | obj = T() - - obj.a = obj.a + 1 +51 - obj.a = obj.a + 1 51 + obj.a += 1 -52 | | note: This is an unsafe fix and may change runtime behavior @@ -491,10 +439,8 @@ PLR6104 [*] Use `+=` to perform an augmented assignment directly | help: Replace with augmented assignment | -53 | - - a = a+-1 +54 - a = a+-1 54 + a += -1 -55 | | note: This is an unsafe fix and may change runtime behavior @@ -510,10 +456,8 @@ PLR6104 [*] Use `+=` to perform an augmented assignment directly | help: Replace with augmented assignment | -57 | test = 0x5 - - test = test + 0xBA +58 - test = test + 0xBA 58 + test += 0xBA -59 | | note: This is an unsafe fix and may change runtime behavior @@ -528,10 +472,8 @@ PLR6104 [*] Use `+=` to perform an augmented assignment directly | help: Replace with augmented assignment | -60 | test2 = b"" - - test2 = test2 + b"\000" +61 - test2 = test2 + b"\000" 61 + test2 += b"\000" -62 | | note: This is an unsafe fix and may change runtime behavior @@ -547,10 +489,8 @@ PLR6104 [*] Use `+=` to perform an augmented assignment directly | help: Replace with augmented assignment | -63 | test3 = "" - - test3 = test3 + ( a := R"" 64 + test3 += ( a := R"" -65 | f"oo" ) +65 + f"oo" ) | note: This is an unsafe fix and may change runtime behavior @@ -568,10 +508,10 @@ PLR6104 [*] Use `+=` to perform an augmented assignment directly | help: Replace with augmented assignment | -67 | test4 = [] - - test4 = test4 + ( e 68 + test4 += ( e -69 | for e in +69 + for e in +70 + range(10) +71 + ) | note: This is an unsafe fix and may change runtime behavior @@ -591,10 +531,11 @@ PLR6104 [*] Use `+=` to perform an augmented assignment directly | help: Replace with augmented assignment | -72 | - - test5 = test5 + ( 73 + test5 += ( -74 | 4 +74 + 4 +75 + * +76 + 10 +77 + ) | note: This is an unsafe fix and may change runtime behavior @@ -615,11 +556,11 @@ PLR6104 [*] Use `+=` to perform an augmented assignment directly | help: Replace with augmented assignment | -78 | - - test6 = test6 + \ - - ( 79 + test6 += ( -80 | 4 +80 + 4 +81 + * +82 + 10 +83 + ) | note: This is an unsafe fix and may change runtime behavior @@ -637,12 +578,10 @@ PLR6104 [*] Use `+=` to perform an augmented assignment directly | help: Replace with augmented assignment | -85 | - - test7 = \ - - 100 \ - - + test7 +86 - test7 = \ +87 - 100 \ +88 - + test7 86 + test7 += 100 -87 | | note: This is an unsafe fix and may change runtime behavior @@ -659,13 +598,11 @@ PLR6104 [*] Use `+=` to perform an augmented assignment directly | |_________^ help: Replace with augmented assignment | -89 | - - test8 = \ - - 886 \ - - + \ - - \ - - test8 +90 - test8 = \ +91 - 886 \ +92 - + \ +93 - \ +94 - test8 90 + test8 += 886 -91 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR6201_literal_membership.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR6201_literal_membership.py.snap index e696344281e07..e3bf351855bc6 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR6201_literal_membership.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR6201_literal_membership.py.snap @@ -12,10 +12,8 @@ PLR6201 [*] Use a set literal when testing for membership | help: Convert to `set` | -1 | # Errors - - 1 in [1, 2, 3] +2 - 1 in [1, 2, 3] 2 + 1 in {1, 2, 3} -3 | 1 in (1, 2, 3) | note: This is an unsafe fix and may change runtime behavior @@ -31,10 +29,8 @@ PLR6201 [*] Use a set literal when testing for membership | help: Convert to `set` | -2 | 1 in [1, 2, 3] - - 1 in (1, 2, 3) +3 - 1 in (1, 2, 3) 3 + 1 in {1, 2, 3} -4 | 1 in ( | note: This is an unsafe fix and may change runtime behavior @@ -53,13 +49,9 @@ PLR6201 [*] Use a set literal when testing for membership | help: Convert to `set` | -3 | 1 in (1, 2, 3) - - 1 in ( -4 + 1 in { -5 | 1, 2, 3 - - ) +4 ~ 1 in { +5 + 1, 2, 3 6 + } -7 | fruits = ["cherry", "grapes"] | note: This is an unsafe fix and may change runtime behavior @@ -74,10 +66,8 @@ PLR6201 [*] Use a set literal when testing for membership 11 | # OK | help: Convert to `set` - | -8 | "cherry" in fruits - - _ = {key: value for key, value in {"a": 1, "b": 2}.items() if key in ("a", "b")} -9 + _ = {key: value for key, value in {"a": 1, "b": 2}.items() if key in {"a", "b"}} -10 | - | + | +9 - _ = {key: value for key, value in {"a": 1, "b": 2}.items() if key in ("a", "b")} +9 + _ = {key: value for key, value in {"a": 1, "b": 2}.items() if key in {"a", "b"}} + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW0108_unnecessary_lambda.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW0108_unnecessary_lambda.py.snap index 5fbe8caa9b756..762058ab613ac 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW0108_unnecessary_lambda.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW0108_unnecessary_lambda.py.snap @@ -10,9 +10,8 @@ PLW0108 [*] Lambda may be unnecessary; consider inlining inner function | help: Inline function call | - - _ = lambda: print() # [unnecessary-lambda] +1 - _ = lambda: print() # [unnecessary-lambda] 1 + _ = print # [unnecessary-lambda] -2 | _ = lambda x, y: min(x, y) # [unnecessary-lambda] | note: This is an unsafe fix and may change runtime behavior @@ -27,10 +26,8 @@ PLW0108 [*] Lambda may be unnecessary; consider inlining inner function | help: Inline function call | -1 | _ = lambda: print() # [unnecessary-lambda] - - _ = lambda x, y: min(x, y) # [unnecessary-lambda] +2 - _ = lambda x, y: min(x, y) # [unnecessary-lambda] 2 + _ = min # [unnecessary-lambda] -3 | | note: This is an unsafe fix and may change runtime behavior @@ -46,10 +43,8 @@ PLW0108 [*] Lambda may be unnecessary; consider inlining inner function | help: Inline function call | -3 | - - _ = lambda *args: f(*args) # [unnecessary-lambda] +4 - _ = lambda *args: f(*args) # [unnecessary-lambda] 4 + _ = f # [unnecessary-lambda] -5 | _ = lambda **kwargs: f(**kwargs) # [unnecessary-lambda] | note: This is an unsafe fix and may change runtime behavior @@ -64,10 +59,8 @@ PLW0108 [*] Lambda may be unnecessary; consider inlining inner function | help: Inline function call | -4 | _ = lambda *args: f(*args) # [unnecessary-lambda] - - _ = lambda **kwargs: f(**kwargs) # [unnecessary-lambda] +5 - _ = lambda **kwargs: f(**kwargs) # [unnecessary-lambda] 5 + _ = f # [unnecessary-lambda] -6 | _ = lambda *args, **kwargs: f(*args, **kwargs) # [unnecessary-lambda] | note: This is an unsafe fix and may change runtime behavior @@ -82,10 +75,8 @@ PLW0108 [*] Lambda may be unnecessary; consider inlining inner function | help: Inline function call | -5 | _ = lambda **kwargs: f(**kwargs) # [unnecessary-lambda] - - _ = lambda *args, **kwargs: f(*args, **kwargs) # [unnecessary-lambda] +6 - _ = lambda *args, **kwargs: f(*args, **kwargs) # [unnecessary-lambda] 6 + _ = f # [unnecessary-lambda] -7 | _ = lambda x, y, z, *args, **kwargs: f(x, y, z, *args, **kwargs) # [unnecessary-lambda] | note: This is an unsafe fix and may change runtime behavior @@ -101,10 +92,8 @@ PLW0108 [*] Lambda may be unnecessary; consider inlining inner function | help: Inline function call | -6 | _ = lambda *args, **kwargs: f(*args, **kwargs) # [unnecessary-lambda] - - _ = lambda x, y, z, *args, **kwargs: f(x, y, z, *args, **kwargs) # [unnecessary-lambda] +7 - _ = lambda x, y, z, *args, **kwargs: f(x, y, z, *args, **kwargs) # [unnecessary-lambda] 7 + _ = f # [unnecessary-lambda] -8 | | note: This is an unsafe fix and may change runtime behavior @@ -118,12 +107,10 @@ PLW0108 [*] Lambda may be unnecessary; consider inlining inner function 10 | _ = lambda x, y: f(lambda x, y: x + y)(x, y) # [unnecessary-lambda] | help: Inline function call - | -8 | - - _ = lambda x: f(lambda x: x)(x) # [unnecessary-lambda] -9 + _ = f(lambda x: x) # [unnecessary-lambda] -10 | _ = lambda x, y: f(lambda x, y: x + y)(x, y) # [unnecessary-lambda] - | + | +9 - _ = lambda x: f(lambda x: x)(x) # [unnecessary-lambda] +9 + _ = f(lambda x: x) # [unnecessary-lambda] + | note: This is an unsafe fix and may change runtime behavior PLW0108 [*] Lambda may be unnecessary; consider inlining inner function @@ -137,10 +124,8 @@ PLW0108 [*] Lambda may be unnecessary; consider inlining inner function | help: Inline function call | -9 | _ = lambda x: f(lambda x: x)(x) # [unnecessary-lambda] - - _ = lambda x, y: f(lambda x, y: x + y)(x, y) # [unnecessary-lambda] +10 - _ = lambda x, y: f(lambda x, y: x + y)(x, y) # [unnecessary-lambda] 10 + _ = f(lambda x, y: x + y) # [unnecessary-lambda] -11 | | note: This is an unsafe fix and may change runtime behavior @@ -154,10 +139,8 @@ PLW0108 [*] Lambda may be unnecessary; consider inlining inner function | help: Inline function call | -61 | # https://github.com/astral-sh/ruff/issues/18675 - - _ = lambda x: (string := str)(x) +62 - _ = lambda x: (string := str)(x) 62 + _ = (string := str) -63 | _ = lambda x: ((x := 1) and str)(x) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW0120_useless_else_on_loop.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW0120_useless_else_on_loop.py.snap index 0e77dd5f43fe9..71a614d9c330b 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW0120_useless_else_on_loop.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW0120_useless_else_on_loop.py.snap @@ -13,11 +13,10 @@ PLW0120 [*] `else` clause on loop without a `break` statement; remove the `else` | help: Remove `else` | -8 | return i - - else: # [useless-else-on-loop] - - print("math is broken") -9 + print("math is broken") -10 | return None + 9 - else: # [useless-else-on-loop] +10 - print("math is broken") +11 - return None + 9 + print("math is broken") | PLW0120 [*] `else` clause on loop without a `break` statement; remove the `else` and dedent its contents @@ -32,11 +31,10 @@ PLW0120 [*] `else` clause on loop without a `break` statement; remove the `else` | help: Remove `else` | -17 | return 1 - - else: # [useless-else-on-loop] - - print("math is broken") +18 - else: # [useless-else-on-loop] +19 - print("math is broken") +20 - return None 18 + print("math is broken") -19 | return None | PLW0120 [*] `else` clause on loop without a `break` statement; remove the `else` and dedent its contents @@ -50,11 +48,10 @@ PLW0120 [*] `else` clause on loop without a `break` statement; remove the `else` | help: Remove `else` | -29 | - - else: # [useless-else-on-loop] - - print("or else!") +30 - else: # [useless-else-on-loop] +31 - print("or else!") +32 - 30 + print("or else!") -31 | | PLW0120 [*] `else` clause on loop without a `break` statement; remove the `else` and dedent its contents @@ -68,11 +65,10 @@ PLW0120 [*] `else` clause on loop without a `break` statement; remove the `else` | help: Remove `else` | -36 | break - - else: # [useless-else-on-loop] - - print("or else!") +37 - else: # [useless-else-on-loop] +38 - print("or else!") +39 - 37 + print("or else!") -38 | | PLW0120 [*] `else` clause on loop without a `break` statement; remove the `else` and dedent its contents @@ -87,15 +83,9 @@ PLW0120 [*] `else` clause on loop without a `break` statement; remove the `else` | help: Remove `else` | -41 | pass - - else: # [useless-else-on-loop] - - print("fat chance") - - for j in range(10): - - break 42 + print("fat chance") 43 + for j in range(10): 44 + break -45 | | PLW0120 [*] `else` clause on loop without a `break` statement; remove the `else` and dedent its contents @@ -110,11 +100,10 @@ PLW0120 [*] `else` clause on loop without a `break` statement; remove the `else` | help: Remove `else` | -87 | print("all right") - - else: # [useless-else-on-loop] - - return True +88 - else: # [useless-else-on-loop] +89 - return True +90 - return False 88 + return True -89 | return False | PLW0120 [*] `else` clause on loop without a `break` statement; remove the `else` and dedent its contents @@ -128,15 +117,10 @@ PLW0120 [*] `else` clause on loop without a `break` statement; remove the `else` 100 | break | help: Remove `else` - | -97 | pass - - else: - - if 1 < 2: # pylint: disable=comparison-of-constants - - break -98 + if 1 < 2: # pylint: disable=comparison-of-constants -99 + break -100 | else: - | + | +98 + if 1 < 2: # pylint: disable=comparison-of-constants +99 + break + | PLW0120 [*] `else` clause on loop without a `break` statement; remove the `else` and dedent its contents --> useless_else_on_loop.py:144:5 @@ -150,12 +134,6 @@ PLW0120 [*] `else` clause on loop without a `break` statement; remove the `else` | help: Remove `else` | -143 | pass - - else: - - # [useless-else-on-loop] - - print("fat chance") - - for j in range(10): - - break 144 + # [useless-else-on-loop] 145 + print("fat chance") 146 + for j in range(10): diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW0133_useless_exception_statement.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW0133_useless_exception_statement.py.snap index 225546bef3029..8fc04aed47b02 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW0133_useless_exception_statement.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW0133_useless_exception_statement.py.snap @@ -13,11 +13,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -25 | def func(): - - AssertionError("This is an assertion error") # PLW0133 -26 + raise AssertionError("This is an assertion error") # PLW0133 -27 | MyError("This is a custom error") # PLW0133 - | +26 | raise AssertionError("This is an assertion error") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior PLW0133 [*] Missing `raise` statement on exception @@ -32,11 +29,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -34 | try: - - Exception("This is an exception") # PLW0133 -35 + raise Exception("This is an exception") # PLW0133 -36 | MyError("This is an exception") # PLW0133 - | +35 | raise Exception("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior PLW0133 [*] Missing `raise` statement on exception @@ -51,11 +45,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -45 | if True: - - RuntimeError("This is an exception") # PLW0133 -46 + raise RuntimeError("This is an exception") # PLW0133 -47 | MyError("This is an exception") # PLW0133 - | +46 | raise RuntimeError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior PLW0133 [*] Missing `raise` statement on exception @@ -70,11 +61,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -55 | def __init__(self): - - TypeError("This is an exception") # PLW0133 -56 + raise TypeError("This is an exception") # PLW0133 -57 | MyError("This is an exception") # PLW0133 - | +56 | raise TypeError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior PLW0133 [*] Missing `raise` statement on exception @@ -89,11 +77,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -64 | def inner(): - - IndexError("This is an exception") # PLW0133 -65 + raise IndexError("This is an exception") # PLW0133 -66 | MyError("This is an exception") # PLW0133 - | +65 | raise IndexError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior PLW0133 [*] Missing `raise` statement on exception @@ -108,11 +93,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -75 | while True: - - KeyError("This is an exception") # PLW0133 -76 + raise KeyError("This is an exception") # PLW0133 -77 | MyError("This is an exception") # PLW0133 - | +76 | raise KeyError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior PLW0133 [*] Missing `raise` statement on exception @@ -127,11 +109,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -86 | def method(self): - - NotImplementedError("This is an exception") # PLW0133 -87 + raise NotImplementedError("This is an exception") # PLW0133 -88 | MyError("This is an exception") # PLW0133 - | +87 | raise NotImplementedError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior PLW0133 [*] Missing `raise` statement on exception @@ -146,11 +125,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -95 | with suppress(Exception): - - AttributeError("This is an exception") # PLW0133 -96 + raise AttributeError("This is an exception") # PLW0133 -97 | MyError("This is an exception") # PLW0133 - | +96 | raise AttributeError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior PLW0133 [*] Missing `raise` statement on exception @@ -165,11 +141,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -103 | def func(): - - (RuntimeError("This is an exception")) # PLW0133 -104 + raise (RuntimeError("This is an exception")) # PLW0133 -105 | (MyError("This is an exception")) # PLW0133 - | +104 | raise (RuntimeError("This is an exception")) # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior PLW0133 [*] Missing `raise` statement on exception @@ -184,11 +157,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -111 | def func(): - - x = 1; (RuntimeError("This is an exception")); y = 2 # PLW0133 -112 + x = 1; raise (RuntimeError("This is an exception")); y = 2 # PLW0133 -113 | x = 1; (MyError("This is an exception")); y = 2 # PLW0133 - | +112 | x = 1; raise (RuntimeError("This is an exception")); y = 2 # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior PLW0133 [*] Missing `raise` statement on exception @@ -202,11 +172,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -119 | def func(): - - UserWarning("This is a user warning") # PLW0133 -120 + raise UserWarning("This is a user warning") # PLW0133 -121 | MyUserWarning("This is a custom user warning") # PLW0133 - | +120 | raise UserWarning("This is a user warning") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior PLW0133 [*] Missing `raise` statement on exception @@ -221,11 +188,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -126 | - - builtins.TypeError("still an exception even though it's an Attribute") # PLW0133 -127 + raise builtins.TypeError("still an exception even though it's an Attribute") # PLW0133 -128 | - | +127 | raise builtins.TypeError("still an exception even though it's an Attribute") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior PLW0133 [*] Missing `raise` statement on exception @@ -240,11 +204,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -128 | - - PythonFinalizationError("Added in Python 3.13") # PLW0133 -129 + raise PythonFinalizationError("Added in Python 3.13") # PLW0133 -130 | - | +129 | raise PythonFinalizationError("Added in Python 3.13") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior PLW0133 [*] Missing `raise` statement on exception @@ -259,9 +220,6 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -136 | - - UserWarning("This is a user warning") # PLW0133 -137 + raise UserWarning("This is a user warning") # PLW0133 -138 | - | +137 | raise UserWarning("This is a user warning") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW0245_super_without_brackets.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW0245_super_without_brackets.py.snap index cd598656b349e..1fcbffcf9ef05 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW0245_super_without_brackets.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW0245_super_without_brackets.py.snap @@ -12,8 +12,5 @@ PLW0245 [*] `super` call is missing parentheses | help: Add parentheses to `super` call | -9 | def speak(): - - original_speak = super.speak() # PLW0245 -10 + original_speak = super().speak() # PLW0245 -11 | return f"{original_speak} But as a dog, it barks!" - | +10 | original_speak = super().speak() # PLW0245 + | ++ diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW1507_shallow_copy_environ.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW1507_shallow_copy_environ.py.snap index c616da9775577..4b1b5bcb3a9c4 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW1507_shallow_copy_environ.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW1507_shallow_copy_environ.py.snap @@ -10,10 +10,8 @@ PLW1507 [*] Shallow copy of `os.environ` via `copy.copy(os.environ)` | ^^^^^^^^^^^^^^^^^^^^^ help: Replace with `os.environ.copy()` | -3 | - - copied_env = copy.copy(os.environ) # [shallow-copy-environ] +4 - copied_env = copy.copy(os.environ) # [shallow-copy-environ] 4 + copied_env = os.environ.copy() # [shallow-copy-environ] -5 | | note: This is an unsafe fix and may change runtime behavior @@ -27,9 +25,7 @@ PLW1507 [*] Shallow copy of `os.environ` via `copy.copy(os.environ)` | help: Replace with `os.environ.copy()` | -10 | os.environ["X"] = "0" - - env = copy.copy(os.environ) +11 - env = copy.copy(os.environ) 11 + env = os.environ.copy() -12 | os.environ["X"] = "1" | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW1510_subprocess_run_without_check.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW1510_subprocess_run_without_check.py.snap index 20579ab9de2d3..149e228f41cf9 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW1510_subprocess_run_without_check.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW1510_subprocess_run_without_check.py.snap @@ -12,11 +12,8 @@ PLW1510 [*] `subprocess.run` without explicit `check` argument | help: Add explicit `check=False` | -3 | # Errors. - - subprocess.run("ls") -4 + subprocess.run("ls", check=False) -5 | subprocess.run("ls", shell=True) - | +4 | subprocess.run("ls", check=False) + | +++++++++++++ note: This is a display-only fix and is likely to be incorrect PLW1510 [*] `subprocess.run` without explicit `check` argument @@ -31,11 +28,8 @@ PLW1510 [*] `subprocess.run` without explicit `check` argument | help: Add explicit `check=False` | -4 | subprocess.run("ls") - - subprocess.run("ls", shell=True) -5 + subprocess.run("ls", check=False, shell=True) -6 | subprocess.run( - | +5 | subprocess.run("ls", check=False, shell=True) + | ++++++++++++ note: This is a display-only fix and is likely to be incorrect PLW1510 [*] `subprocess.run` without explicit `check` argument @@ -50,11 +44,8 @@ PLW1510 [*] `subprocess.run` without explicit `check` argument | help: Add explicit `check=False` | -7 | ["ls"], - - shell=False, -8 + check=False, shell=False, -9 | ) - | +8 | check=False, shell=False, + | ++++++++++++ note: This is a display-only fix and is likely to be incorrect PLW1510 [*] `subprocess.run` without explicit `check` argument @@ -69,9 +60,6 @@ PLW1510 [*] `subprocess.run` without explicit `check` argument | help: Add explicit `check=False` | -9 | ) - - subprocess.run(["ls"], **kwargs) -10 + subprocess.run(["ls"], check=False, **kwargs) -11 | - | +10 | subprocess.run(["ls"], check=False, **kwargs) + | ++++++++++++ note: This is a display-only fix and is likely to be incorrect diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW1514_unspecified_encoding.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW1514_unspecified_encoding.py.snap index 71f3bede10a3d..6927bc6e9ad6c 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW1514_unspecified_encoding.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW1514_unspecified_encoding.py.snap @@ -12,11 +12,8 @@ PLW1514 [*] `open` in text mode without explicit `encoding` argument | help: Add explicit `encoding` argument | -7 | # Errors. - - open("test.txt") -8 + open("test.txt", encoding="utf-8") -9 | io.TextIOWrapper(io.FileIO("test.txt")) - | +8 | open("test.txt", encoding="utf-8") + | ++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `io.TextIOWrapper` without explicit `encoding` argument @@ -30,12 +27,9 @@ PLW1514 [*] `io.TextIOWrapper` without explicit `encoding` argument 11 | tempfile.NamedTemporaryFile("w") | help: Add explicit `encoding` argument - | -8 | open("test.txt") - - io.TextIOWrapper(io.FileIO("test.txt")) -9 + io.TextIOWrapper(io.FileIO("test.txt"), encoding="utf-8") -10 | hugo.TextIOWrapper(hugo.FileIO("test.txt")) - | + | +9 | io.TextIOWrapper(io.FileIO("test.txt"), encoding="utf-8") + | ++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `io.TextIOWrapper` without explicit `encoding` argument @@ -50,11 +44,8 @@ PLW1514 [*] `io.TextIOWrapper` without explicit `encoding` argument | help: Add explicit `encoding` argument | -9 | io.TextIOWrapper(io.FileIO("test.txt")) - - hugo.TextIOWrapper(hugo.FileIO("test.txt")) -10 + hugo.TextIOWrapper(hugo.FileIO("test.txt"), encoding="utf-8") -11 | tempfile.NamedTemporaryFile("w") - | +10 | hugo.TextIOWrapper(hugo.FileIO("test.txt"), encoding="utf-8") + | ++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `tempfile.NamedTemporaryFile` in text mode without explicit `encoding` argument @@ -69,11 +60,8 @@ PLW1514 [*] `tempfile.NamedTemporaryFile` in text mode without explicit `encodin | help: Add explicit `encoding` argument | -10 | hugo.TextIOWrapper(hugo.FileIO("test.txt")) - - tempfile.NamedTemporaryFile("w") -11 + tempfile.NamedTemporaryFile("w", encoding="utf-8") -12 | tempfile.TemporaryFile("w") - | +11 | tempfile.NamedTemporaryFile("w", encoding="utf-8") + | ++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `tempfile.TemporaryFile` in text mode without explicit `encoding` argument @@ -88,11 +76,8 @@ PLW1514 [*] `tempfile.TemporaryFile` in text mode without explicit `encoding` ar | help: Add explicit `encoding` argument | -11 | tempfile.NamedTemporaryFile("w") - - tempfile.TemporaryFile("w") -12 + tempfile.TemporaryFile("w", encoding="utf-8") -13 | codecs.open("test.txt") - | +12 | tempfile.TemporaryFile("w", encoding="utf-8") + | ++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `codecs.open` in text mode without explicit `encoding` argument @@ -106,11 +91,8 @@ PLW1514 [*] `codecs.open` in text mode without explicit `encoding` argument | help: Add explicit `encoding` argument | -12 | tempfile.TemporaryFile("w") - - codecs.open("test.txt") -13 + codecs.open("test.txt", encoding="utf-8") -14 | tempfile.SpooledTemporaryFile(0, "w") - | +13 | codecs.open("test.txt", encoding="utf-8") + | ++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `tempfile.SpooledTemporaryFile` in text mode without explicit `encoding` argument @@ -125,11 +107,8 @@ PLW1514 [*] `tempfile.SpooledTemporaryFile` in text mode without explicit `encod | help: Add explicit `encoding` argument | -13 | codecs.open("test.txt") - - tempfile.SpooledTemporaryFile(0, "w") -14 + tempfile.SpooledTemporaryFile(0, "w", encoding="utf-8") -15 | - | +14 | tempfile.SpooledTemporaryFile(0, "w", encoding="utf-8") + | ++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `open` in text mode without explicit `encoding` argument @@ -144,11 +123,8 @@ PLW1514 [*] `open` in text mode without explicit `encoding` argument | help: Add explicit `encoding` argument | -45 | - - open("test.txt",) -46 + open("test.txt", encoding="utf-8",) -47 | open() - | +46 | open("test.txt", encoding="utf-8",) + | ++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `open` in text mode without explicit `encoding` argument @@ -162,11 +138,8 @@ PLW1514 [*] `open` in text mode without explicit `encoding` argument | help: Add explicit `encoding` argument | -46 | open("test.txt",) - - open() -47 + open(encoding="utf-8") -48 | open( - | +47 | open(encoding="utf-8") + | ++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `open` in text mode without explicit `encoding` argument @@ -181,11 +154,8 @@ PLW1514 [*] `open` in text mode without explicit `encoding` argument | help: Add explicit `encoding` argument | -48 | open( - - "test.txt", # comment -49 + "test.txt", encoding="utf-8", # comment -50 | ) - | +49 | "test.txt", encoding="utf-8", # comment + | ++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `open` in text mode without explicit `encoding` argument @@ -200,11 +170,8 @@ PLW1514 [*] `open` in text mode without explicit `encoding` argument | help: Add explicit `encoding` argument | -51 | open( - - "test.txt", -52 + "test.txt", encoding="utf-8", -53 | # comment - | +52 | "test.txt", encoding="utf-8", + | ++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `open` in text mode without explicit `encoding` argument @@ -219,11 +186,8 @@ PLW1514 [*] `open` in text mode without explicit `encoding` argument | help: Add explicit `encoding` argument | -54 | ) - - open(("test.txt"),) -55 + open(("test.txt"), encoding="utf-8",) -56 | open( - | +55 | open(("test.txt"), encoding="utf-8",) + | ++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `open` in text mode without explicit `encoding` argument @@ -238,11 +202,8 @@ PLW1514 [*] `open` in text mode without explicit `encoding` argument | help: Add explicit `encoding` argument | -56 | open( - - ("test.txt"), # comment -57 + ("test.txt"), encoding="utf-8", # comment -58 | ) - | +57 | ("test.txt"), encoding="utf-8", # comment + | ++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `open` in text mode without explicit `encoding` argument @@ -257,11 +218,8 @@ PLW1514 [*] `open` in text mode without explicit `encoding` argument | help: Add explicit `encoding` argument | -59 | open( - - ("test.txt"), -60 + ("test.txt"), encoding="utf-8", -61 | # comment - | +60 | ("test.txt"), encoding="utf-8", + | ++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `open` in text mode without explicit `encoding` argument @@ -276,11 +234,8 @@ PLW1514 [*] `open` in text mode without explicit `encoding` argument | help: Add explicit `encoding` argument | -63 | - - open((("test.txt")),) -64 + open((("test.txt")), encoding="utf-8",) -65 | open( - | +64 | open((("test.txt")), encoding="utf-8",) + | ++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `open` in text mode without explicit `encoding` argument @@ -294,11 +249,8 @@ PLW1514 [*] `open` in text mode without explicit `encoding` argument | help: Add explicit `encoding` argument | -65 | open( - - (("test.txt")), # comment -66 + (("test.txt")), encoding="utf-8", # comment -67 | ) - | +66 | (("test.txt")), encoding="utf-8", # comment + | ++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `open` in text mode without explicit `encoding` argument @@ -313,11 +265,8 @@ PLW1514 [*] `open` in text mode without explicit `encoding` argument | help: Add explicit `encoding` argument | -68 | open( - - (("test.txt")), -69 + (("test.txt")), encoding="utf-8", -70 | # comment - | +69 | (("test.txt")), encoding="utf-8", + | ++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `pathlib.Path(...).open` in text mode without explicit `encoding` argument @@ -331,11 +280,8 @@ PLW1514 [*] `pathlib.Path(...).open` in text mode without explicit `encoding` ar | help: Add explicit `encoding` argument | -76 | # Errors. - - Path("foo.txt").open() -77 + Path("foo.txt").open(encoding="utf-8") -78 | Path("foo.txt").open("w") - | +77 | Path("foo.txt").open(encoding="utf-8") + | ++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `pathlib.Path(...).open` in text mode without explicit `encoding` argument @@ -350,11 +296,8 @@ PLW1514 [*] `pathlib.Path(...).open` in text mode without explicit `encoding` ar | help: Add explicit `encoding` argument | -77 | Path("foo.txt").open() - - Path("foo.txt").open("w") -78 + Path("foo.txt").open("w", encoding="utf-8") -79 | text = Path("foo.txt").read_text() - | +78 | Path("foo.txt").open("w", encoding="utf-8") + | ++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `pathlib.Path(...).read_text` without explicit `encoding` argument @@ -368,11 +311,8 @@ PLW1514 [*] `pathlib.Path(...).read_text` without explicit `encoding` argument | help: Add explicit `encoding` argument | -78 | Path("foo.txt").open("w") - - text = Path("foo.txt").read_text() -79 + text = Path("foo.txt").read_text(encoding="utf-8") -80 | Path("foo.txt").write_text(text) - | +79 | text = Path("foo.txt").read_text(encoding="utf-8") + | ++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `pathlib.Path(...).write_text` without explicit `encoding` argument @@ -387,11 +327,8 @@ PLW1514 [*] `pathlib.Path(...).write_text` without explicit `encoding` argument | help: Add explicit `encoding` argument | -79 | text = Path("foo.txt").read_text() - - Path("foo.txt").write_text(text) -80 + Path("foo.txt").write_text(text, encoding="utf-8") -81 | - | +80 | Path("foo.txt").write_text(text, encoding="utf-8") + | ++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `pathlib.Path(...).open` in text mode without explicit `encoding` argument @@ -406,11 +343,8 @@ PLW1514 [*] `pathlib.Path(...).open` in text mode without explicit `encoding` ar | help: Add explicit `encoding` argument | -95 | x = Path("foo.txt") - - x.open() -96 + x.open(encoding="utf-8") -97 | - | +96 | x.open(encoding="utf-8") + | ++++++++++++++++ note: This is an unsafe fix and may change runtime behavior PLW1514 [*] `pathlib.Path(...).open` in text mode without explicit `encoding` argument @@ -423,9 +357,6 @@ PLW1514 [*] `pathlib.Path(...).open` in text mode without explicit `encoding` ar | help: Add explicit `encoding` argument | -104 | def format_file(file: Path): - - with file.open() as f: -105 + with file.open(encoding="utf-8") as f: -106 | contents = f.read() - | +105 | with file.open(encoding="utf-8") as f: + | ++++++++++++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW3301_nested_min_max.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW3301_nested_min_max.py.snap index 564dee97b670e..1da464bef55c3 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW3301_nested_min_max.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW3301_nested_min_max.py.snap @@ -12,10 +12,8 @@ PLW3301 [*] Nested `min` calls can be flattened | help: Flatten nested `min` calls | -1 | min(1, 2, 3) - - min(1, min(2, 3)) +2 - min(1, min(2, 3)) 2 + min(1, 2, 3) -3 | min(1, min(2, min(3, 4))) | note: This is an unsafe fix and may change runtime behavior @@ -31,10 +29,8 @@ PLW3301 [*] Nested `min` calls can be flattened | help: Flatten nested `min` calls | -2 | min(1, min(2, 3)) - - min(1, min(2, min(3, 4))) +3 - min(1, min(2, min(3, 4))) 3 + min(1, 2, 3, 4) -4 | min(1, foo("a", "b"), min(3, 4)) | note: This is an unsafe fix and may change runtime behavior @@ -50,10 +46,8 @@ PLW3301 [*] Nested `min` calls can be flattened | help: Flatten nested `min` calls | -2 | min(1, min(2, 3)) - - min(1, min(2, min(3, 4))) +3 - min(1, min(2, min(3, 4))) 3 + min(1, min(2, 3, 4)) -4 | min(1, foo("a", "b"), min(3, 4)) | note: This is an unsafe fix and may change runtime behavior @@ -69,10 +63,8 @@ PLW3301 [*] Nested `min` calls can be flattened | help: Flatten nested `min` calls | -3 | min(1, min(2, min(3, 4))) - - min(1, foo("a", "b"), min(3, 4)) +4 - min(1, foo("a", "b"), min(3, 4)) 4 + min(1, foo("a", "b"), 3, 4) -5 | min(1, max(2, 3)) | note: This is an unsafe fix and may change runtime behavior @@ -88,10 +80,8 @@ PLW3301 [*] Nested `max` calls can be flattened | help: Flatten nested `max` calls | -6 | max(1, 2, 3) - - max(1, max(2, 3)) +7 - max(1, max(2, 3)) 7 + max(1, 2, 3) -8 | max(1, max(2, max(3, 4))) | note: This is an unsafe fix and may change runtime behavior @@ -106,10 +96,8 @@ PLW3301 [*] Nested `max` calls can be flattened | help: Flatten nested `max` calls | -7 | max(1, max(2, 3)) - - max(1, max(2, max(3, 4))) +8 - max(1, max(2, max(3, 4))) 8 + max(1, 2, 3, 4) -9 | max(1, foo("a", "b"), max(3, 4)) | note: This is an unsafe fix and may change runtime behavior @@ -124,10 +112,8 @@ PLW3301 [*] Nested `max` calls can be flattened | help: Flatten nested `max` calls | -7 | max(1, max(2, 3)) - - max(1, max(2, max(3, 4))) +8 - max(1, max(2, max(3, 4))) 8 + max(1, max(2, 3, 4)) -9 | max(1, foo("a", "b"), max(3, 4)) | note: This is an unsafe fix and may change runtime behavior @@ -142,12 +128,10 @@ PLW3301 [*] Nested `max` calls can be flattened 11 | # These should not trigger; we do not flag cases with keyword args. | help: Flatten nested `max` calls - | -8 | max(1, max(2, max(3, 4))) - - max(1, foo("a", "b"), max(3, 4)) -9 + max(1, foo("a", "b"), 3, 4) -10 | - | + | +9 - max(1, foo("a", "b"), max(3, 4)) +9 + max(1, foo("a", "b"), 3, 4) + | note: This is an unsafe fix and may change runtime behavior PLW3301 [*] Nested `min` calls can be flattened @@ -162,10 +146,8 @@ PLW3301 [*] Nested `min` calls can be flattened | help: Flatten nested `min` calls | -14 | # This will still trigger, to merge the calls without keyword args. - - min(1, min(2, 3, key=test), min(4, 5)) +15 - min(1, min(2, 3, key=test), min(4, 5)) 15 + min(1, min(2, 3, key=test), 4, 5) -16 | | note: This is an unsafe fix and may change runtime behavior @@ -183,13 +165,11 @@ PLW3301 [*] Nested `min` calls can be flattened | help: Flatten nested `min` calls | -17 | # The fix is already unsafe, so deleting comments is okay. - - min( - - 1, # This is a comment. - - min(2, 3), - - ) +18 - min( +19 - 1, # This is a comment. +20 - min(2, 3), +21 - ) 18 + min(1, 2, 3) -19 | | note: This is an unsafe fix and may change runtime behavior @@ -204,10 +184,8 @@ PLW3301 [*] Nested `min` calls can be flattened | help: Flatten nested `min` calls | -23 | # Handle iterable expressions. - - min(1, min(a)) +24 - min(1, min(a)) 24 + min(1, *a) -25 | min(1, min(i for i in range(10))) | note: This is an unsafe fix and may change runtime behavior @@ -223,10 +201,8 @@ PLW3301 [*] Nested `min` calls can be flattened | help: Flatten nested `min` calls | -24 | min(1, min(a)) - - min(1, min(i for i in range(10))) +25 - min(1, min(i for i in range(10))) 25 + min(1, *(i for i in range(10))) -26 | max(1, max(a)) | note: This is an unsafe fix and may change runtime behavior @@ -241,10 +217,8 @@ PLW3301 [*] Nested `max` calls can be flattened | help: Flatten nested `max` calls | -25 | min(1, min(i for i in range(10))) - - max(1, max(a)) +26 - max(1, max(a)) 26 + max(1, *a) -27 | max(1, max(i for i in range(10))) | note: This is an unsafe fix and may change runtime behavior @@ -260,10 +234,8 @@ PLW3301 [*] Nested `max` calls can be flattened | help: Flatten nested `max` calls | -26 | max(1, max(a)) - - max(1, max(i for i in range(10))) +27 - max(1, max(i for i in range(10))) 27 + max(1, *(i for i in range(10))) -28 | | note: This is an unsafe fix and may change runtime behavior @@ -278,10 +250,8 @@ PLW3301 [*] Nested `max` calls can be flattened | help: Flatten nested `max` calls | -40 | # Starred argument should be copied as it is. - - max(1, max(*a)) +41 - max(1, max(*a)) 41 + max(1, *a) -42 | | note: This is an unsafe fix and may change runtime behavior @@ -293,10 +263,8 @@ PLW3301 [*] Nested `min` calls can be flattened | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Flatten nested `min` calls | -43 | import builtins - - builtins.min(1, min(2, 3)) +44 - builtins.min(1, min(2, 3)) 44 + builtins.min(1, 2, 3) -45 | | note: This is an unsafe fix and may change runtime behavior @@ -315,12 +283,10 @@ PLW3301 [*] Nested `max` calls can be flattened | help: Flatten nested `max` calls | -47 | # PLW3301 - - max_word_len = max( - - max(len(word) for word in "blah blah blah".split(" ")), - - len("Done!"), - - ) +48 - max_word_len = max( +49 - max(len(word) for word in "blah blah blah".split(" ")), +50 - len("Done!"), +51 - ) 48 + max_word_len = max(*(len(word) for word in "blah blah blah".split(" ")), len("Done!")) -49 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__conflict_with_definition_rules.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__conflict_with_definition_rules.snap index b02e55bb9e71b..76b2475a29391 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__conflict_with_definition_rules.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__conflict_with_definition_rules.snap @@ -11,10 +11,9 @@ PLR1712 [*] Unnecessary temporary variable | |________^ help: Use `x, y = y, x` instead | -5 | x, y = 1, 2 - - temp = x # PLR1712 - - x = y - - y = temp +6 - temp = x # PLR1712 +7 - x = y +8 - y = temp 6 + x, y = y, x | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__preview__PLW0133_useless_exception_statement.py.snap b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__preview__PLW0133_useless_exception_statement.py.snap index 3bc3b056b2091..b46dabb31a3a3 100644 --- a/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__preview__PLW0133_useless_exception_statement.py.snap +++ b/crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__preview__PLW0133_useless_exception_statement.py.snap @@ -22,11 +22,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -26 | AssertionError("This is an assertion error") # PLW0133 - - MyError("This is a custom error") # PLW0133 -27 + raise MyError("This is a custom error") # PLW0133 -28 | MySubError("This is a custom error") # PLW0133 - | +27 | raise MyError("This is a custom error") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -41,11 +38,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -27 | MyError("This is a custom error") # PLW0133 - - MySubError("This is a custom error") # PLW0133 -28 + raise MySubError("This is a custom error") # PLW0133 -29 | MyValueError("This is a custom value error") # PLW0133 - | +28 | raise MySubError("This is a custom error") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -58,11 +52,8 @@ PLW0133 [*] Missing `raise` statement on exception | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add `raise` keyword | -28 | MySubError("This is a custom error") # PLW0133 - - MyValueError("This is a custom value error") # PLW0133 -29 + raise MyValueError("This is a custom value error") # PLW0133 -30 | - | +29 | raise MyValueError("This is a custom value error") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -78,11 +69,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -35 | Exception("This is an exception") # PLW0133 - - MyError("This is an exception") # PLW0133 -36 + raise MyError("This is an exception") # PLW0133 -37 | MySubError("This is an exception") # PLW0133 - | +36 | raise MyError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -98,11 +86,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -36 | MyError("This is an exception") # PLW0133 - - MySubError("This is an exception") # PLW0133 -37 + raise MySubError("This is an exception") # PLW0133 -38 | MyValueError("This is an exception") # PLW0133 - | +37 | raise MySubError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -118,11 +103,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -37 | MySubError("This is an exception") # PLW0133 - - MyValueError("This is an exception") # PLW0133 -38 + raise MyValueError("This is an exception") # PLW0133 -39 | except Exception as err: - | +38 | raise MyValueError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -138,11 +120,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -46 | RuntimeError("This is an exception") # PLW0133 - - MyError("This is an exception") # PLW0133 -47 + raise MyError("This is an exception") # PLW0133 -48 | MySubError("This is an exception") # PLW0133 - | +47 | raise MyError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -157,11 +136,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -47 | MyError("This is an exception") # PLW0133 - - MySubError("This is an exception") # PLW0133 -48 + raise MySubError("This is an exception") # PLW0133 -49 | MyValueError("This is an exception") # PLW0133 - | +48 | raise MySubError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -174,11 +150,8 @@ PLW0133 [*] Missing `raise` statement on exception | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add `raise` keyword | -48 | MySubError("This is an exception") # PLW0133 - - MyValueError("This is an exception") # PLW0133 -49 + raise MyValueError("This is an exception") # PLW0133 -50 | - | +49 | raise MyValueError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -194,11 +167,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -56 | TypeError("This is an exception") # PLW0133 - - MyError("This is an exception") # PLW0133 -57 + raise MyError("This is an exception") # PLW0133 -58 | MySubError("This is an exception") # PLW0133 - | +57 | raise MyError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -213,11 +183,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -57 | MyError("This is an exception") # PLW0133 - - MySubError("This is an exception") # PLW0133 -58 + raise MySubError("This is an exception") # PLW0133 -59 | MyValueError("This is an exception") # PLW0133 - | +58 | raise MySubError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -230,11 +197,8 @@ PLW0133 [*] Missing `raise` statement on exception | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add `raise` keyword | -58 | MySubError("This is an exception") # PLW0133 - - MyValueError("This is an exception") # PLW0133 -59 + raise MyValueError("This is an exception") # PLW0133 -60 | - | +59 | raise MyValueError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -250,11 +214,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -65 | IndexError("This is an exception") # PLW0133 - - MyError("This is an exception") # PLW0133 -66 + raise MyError("This is an exception") # PLW0133 -67 | MySubError("This is an exception") # PLW0133 - | +66 | raise MyError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -269,11 +230,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -66 | MyError("This is an exception") # PLW0133 - - MySubError("This is an exception") # PLW0133 -67 + raise MySubError("This is an exception") # PLW0133 -68 | MyValueError("This is an exception") # PLW0133 - | +67 | raise MySubError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -289,11 +247,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -67 | MySubError("This is an exception") # PLW0133 - - MyValueError("This is an exception") # PLW0133 -68 + raise MyValueError("This is an exception") # PLW0133 -69 | - | +68 | raise MyValueError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -309,11 +264,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -76 | KeyError("This is an exception") # PLW0133 - - MyError("This is an exception") # PLW0133 -77 + raise MyError("This is an exception") # PLW0133 -78 | MySubError("This is an exception") # PLW0133 - | +77 | raise MyError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -328,11 +280,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -77 | MyError("This is an exception") # PLW0133 - - MySubError("This is an exception") # PLW0133 -78 + raise MySubError("This is an exception") # PLW0133 -79 | MyValueError("This is an exception") # PLW0133 - | +78 | raise MySubError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -345,11 +294,8 @@ PLW0133 [*] Missing `raise` statement on exception | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add `raise` keyword | -78 | MySubError("This is an exception") # PLW0133 - - MyValueError("This is an exception") # PLW0133 -79 + raise MyValueError("This is an exception") # PLW0133 -80 | - | +79 | raise MyValueError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -365,11 +311,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -87 | NotImplementedError("This is an exception") # PLW0133 - - MyError("This is an exception") # PLW0133 -88 + raise MyError("This is an exception") # PLW0133 -89 | MySubError("This is an exception") # PLW0133 - | +88 | raise MyError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -384,11 +327,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -88 | MyError("This is an exception") # PLW0133 - - MySubError("This is an exception") # PLW0133 -89 + raise MySubError("This is an exception") # PLW0133 -90 | MyValueError("This is an exception") # PLW0133 - | +89 | raise MySubError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -401,11 +341,8 @@ PLW0133 [*] Missing `raise` statement on exception | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add `raise` keyword | -89 | MySubError("This is an exception") # PLW0133 - - MyValueError("This is an exception") # PLW0133 -90 + raise MyValueError("This is an exception") # PLW0133 -91 | - | +90 | raise MyValueError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -421,11 +358,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -96 | AttributeError("This is an exception") # PLW0133 - - MyError("This is an exception") # PLW0133 -97 + raise MyError("This is an exception") # PLW0133 -98 | MySubError("This is an exception") # PLW0133 - | +97 | raise MyError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -440,11 +374,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -97 | MyError("This is an exception") # PLW0133 - - MySubError("This is an exception") # PLW0133 -98 + raise MySubError("This is an exception") # PLW0133 -99 | MyValueError("This is an exception") # PLW0133 - | +98 | raise MySubError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -456,12 +387,9 @@ PLW0133 [*] Missing `raise` statement on exception 99 | MyValueError("This is an exception") # PLW0133 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add `raise` keyword - | -98 | MySubError("This is an exception") # PLW0133 - - MyValueError("This is an exception") # PLW0133 -99 + raise MyValueError("This is an exception") # PLW0133 -100 | - | + | +99 | raise MyValueError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -477,11 +405,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -104 | (RuntimeError("This is an exception")) # PLW0133 - - (MyError("This is an exception")) # PLW0133 -105 + raise (MyError("This is an exception")) # PLW0133 -106 | (MySubError("This is an exception")) # PLW0133 - | +105 | raise (MyError("This is an exception")) # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -496,11 +421,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -105 | (MyError("This is an exception")) # PLW0133 - - (MySubError("This is an exception")) # PLW0133 -106 + raise (MySubError("This is an exception")) # PLW0133 -107 | (MyValueError("This is an exception")) # PLW0133 - | +106 | raise (MySubError("This is an exception")) # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -513,11 +435,8 @@ PLW0133 [*] Missing `raise` statement on exception | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add `raise` keyword | -106 | (MySubError("This is an exception")) # PLW0133 - - (MyValueError("This is an exception")) # PLW0133 -107 + raise (MyValueError("This is an exception")) # PLW0133 -108 | - | +107 | raise (MyValueError("This is an exception")) # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -533,11 +452,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -112 | x = 1; (RuntimeError("This is an exception")); y = 2 # PLW0133 - - x = 1; (MyError("This is an exception")); y = 2 # PLW0133 -113 + x = 1; raise (MyError("This is an exception")); y = 2 # PLW0133 -114 | x = 1; (MySubError("This is an exception")); y = 2 # PLW0133 - | +113 | x = 1; raise (MyError("This is an exception")); y = 2 # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -552,11 +468,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -113 | x = 1; (MyError("This is an exception")); y = 2 # PLW0133 - - x = 1; (MySubError("This is an exception")); y = 2 # PLW0133 -114 + x = 1; raise (MySubError("This is an exception")); y = 2 # PLW0133 -115 | x = 1; (MyValueError("This is an exception")); y = 2 # PLW0133 - | +114 | x = 1; raise (MySubError("This is an exception")); y = 2 # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -569,11 +482,8 @@ PLW0133 [*] Missing `raise` statement on exception | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add `raise` keyword | -114 | x = 1; (MySubError("This is an exception")); y = 2 # PLW0133 - - x = 1; (MyValueError("This is an exception")); y = 2 # PLW0133 -115 + x = 1; raise (MyValueError("This is an exception")); y = 2 # PLW0133 -116 | - | +115 | x = 1; raise (MyValueError("This is an exception")); y = 2 # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -586,11 +496,8 @@ PLW0133 [*] Missing `raise` statement on exception | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add `raise` keyword | -120 | UserWarning("This is a user warning") # PLW0133 - - MyUserWarning("This is a custom user warning") # PLW0133 -121 + raise MyUserWarning("This is a custom user warning") # PLW0133 -122 | - | +121 | raise MyUserWarning("This is a custom user warning") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -606,11 +513,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -130 | - - MyError("This is an exception") # PLW0133 -131 + raise MyError("This is an exception") # PLW0133 -132 | - | +131 | raise MyError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -626,11 +530,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -132 | - - MySubError("This is an exception") # PLW0133 -133 + raise MySubError("This is an exception") # PLW0133 -134 | - | +133 | raise MySubError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -646,11 +547,8 @@ PLW0133 [*] Missing `raise` statement on exception | help: Add `raise` keyword | -134 | - - MyValueError("This is an exception") # PLW0133 -135 + raise MyValueError("This is an exception") # PLW0133 -136 | - | +135 | raise MyValueError("This is an exception") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior @@ -663,9 +561,6 @@ PLW0133 [*] Missing `raise` statement on exception | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add `raise` keyword | -138 | - - MyUserWarning("This is a custom user warning") # PLW0133 -139 + raise MyUserWarning("This is a custom user warning") # PLW0133 -140 | - | +139 | raise MyUserWarning("This is a custom user warning") # PLW0133 + | +++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/mod.rs b/crates/ruff_linter/src/rules/pyupgrade/mod.rs index 566280d98aeab..6cc5868d946c8 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/mod.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/mod.rs @@ -459,7 +459,6 @@ mod tests { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Import from `shlex` | - - from pipes import quote, Template 1 + from pipes import Template 2 + from shlex import quote | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP001.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP001.py.snap index aad9e7efda7dc..e921f09a4d18f 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP001.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP001.py.snap @@ -9,10 +9,8 @@ UP001 [*] `__metaclass__ = type` is implied | ^^^^^^^^^^^^^^^^^^^^ help: Remove `__metaclass__ = type` | -1 | class A: - - __metaclass__ = type +2 - __metaclass__ = type 2 + pass -3 | | UP001 [*] `__metaclass__ = type` is implied @@ -26,7 +24,5 @@ UP001 [*] `__metaclass__ = type` is implied | help: Remove `__metaclass__ = type` | -5 | class B: - - __metaclass__ = type -6 | +6 - __metaclass__ = type | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP003.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP003.py.snap index ecd903ccaeb6a..5ab2255bb1fe9 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP003.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP003.py.snap @@ -11,9 +11,8 @@ UP003 [*] Use `str` instead of `type(...)` | help: Replace `type(...)` with `str` | - - type("") +1 - type("") 1 + str -2 | type(b"") | UP003 [*] Use `bytes` instead of `type(...)` @@ -27,10 +26,8 @@ UP003 [*] Use `bytes` instead of `type(...)` | help: Replace `type(...)` with `bytes` | -1 | type("") - - type(b"") +2 - type(b"") 2 + bytes -3 | type(0) | UP003 [*] Use `int` instead of `type(...)` @@ -45,10 +42,8 @@ UP003 [*] Use `int` instead of `type(...)` | help: Replace `type(...)` with `int` | -2 | type(b"") - - type(0) +3 - type(0) 3 + int -4 | type(0.0) | UP003 [*] Use `float` instead of `type(...)` @@ -62,10 +57,8 @@ UP003 [*] Use `float` instead of `type(...)` | help: Replace `type(...)` with `float` | -3 | type(0) - - type(0.0) +4 - type(0.0) 4 + float -5 | type(0j) | UP003 [*] Use `complex` instead of `type(...)` @@ -80,10 +73,8 @@ UP003 [*] Use `complex` instead of `type(...)` | help: Replace `type(...)` with `complex` | -4 | type(0.0) - - type(0j) +5 - type(0j) 5 + complex -6 | | UP003 [*] Use `str` instead of `type(...)` @@ -94,7 +85,6 @@ UP003 [*] Use `str` instead of `type(...)` | ^^^^^^^^ help: Replace `type(...)` with `str` | -13 | # Regression test for: https://github.com/astral-sh/ruff/issues/7455#issuecomment-1722459841 - - assert isinstance(fullname, type("")is not True) +14 - assert isinstance(fullname, type("")is not True) 14 + assert isinstance(fullname, str is not True) | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP004.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP004.py.snap index d7fb242ee9f3e..4f0bb79334b29 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP004.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP004.py.snap @@ -10,10 +10,8 @@ UP004 [*] Class `A` inherits from `object` | help: Remove `object` inheritance | -4 | - - class A(object): +5 - class A(object): 5 + class A: -6 | ... | UP004 [*] Class `A` inherits from `object` @@ -27,12 +25,10 @@ UP004 [*] Class `A` inherits from `object` | help: Remove `object` inheritance | -8 | - - class A( - - object, - - ): -9 + class A: -10 | ... + 9 - class A( +10 - object, +11 - ): + 9 + class A: | UP004 [*] Class `A` inherits from `object` @@ -46,13 +42,11 @@ UP004 [*] Class `A` inherits from `object` | help: Remove `object` inheritance | -14 | - - class A( - - object, - - # - - ): +15 - class A( +16 - object, +17 - # +18 - ): 15 + class A: -16 | ... | note: This is an unsafe fix and may change runtime behavior @@ -68,13 +62,11 @@ UP004 [*] Class `A` inherits from `object` | help: Remove `object` inheritance | -21 | - - class A( - - # - - object, - - ): +22 - class A( +23 - # +24 - object, +25 - ): 22 + class A: -23 | ... | note: This is an unsafe fix and may change runtime behavior @@ -90,13 +82,11 @@ UP004 [*] Class `A` inherits from `object` | help: Remove `object` inheritance | -28 | - - class A( - - # - - object - - ): +29 - class A( +30 - # +31 - object +32 - ): 29 + class A: -30 | ... | note: This is an unsafe fix and may change runtime behavior @@ -111,13 +101,11 @@ UP004 [*] Class `A` inherits from `object` | help: Remove `object` inheritance | -35 | - - class A( - - object - - # - - ): +36 - class A( +37 - object +38 - # +39 - ): 36 + class A: -37 | ... | note: This is an unsafe fix and may change runtime behavior @@ -133,14 +121,12 @@ UP004 [*] Class `A` inherits from `object` | help: Remove `object` inheritance | -42 | - - class A( - - # - - object, - - # - - ): +43 - class A( +44 - # +45 - object, +46 - # +47 - ): 43 + class A: -44 | ... | note: This is an unsafe fix and may change runtime behavior @@ -156,14 +142,12 @@ UP004 [*] Class `A` inherits from `object` | help: Remove `object` inheritance | -50 | - - class A( - - # - - object, - - # - - ): +51 - class A( +52 - # +53 - object, +54 - # +55 - ): 51 + class A: -52 | ... | note: This is an unsafe fix and may change runtime behavior @@ -179,14 +163,12 @@ UP004 [*] Class `A` inherits from `object` | help: Remove `object` inheritance | -58 | - - class A( - - # - - object - - # - - ): +59 - class A( +60 - # +61 - object +62 - # +63 - ): 59 + class A: -60 | ... | note: This is an unsafe fix and may change runtime behavior @@ -202,14 +184,12 @@ UP004 [*] Class `A` inherits from `object` | help: Remove `object` inheritance | -66 | - - class A( - - # - - object - - # - - ): +67 - class A( +68 - # +69 - object +70 - # +71 - ): 67 + class A: -68 | ... | note: This is an unsafe fix and may change runtime behavior @@ -222,10 +202,8 @@ UP004 [*] Class `B` inherits from `object` | help: Remove `object` inheritance | -74 | - - class B(A, object): +75 - class B(A, object): 75 + class B(A): -76 | ... | UP004 [*] Class `B` inherits from `object` @@ -237,10 +215,8 @@ UP004 [*] Class `B` inherits from `object` | help: Remove `object` inheritance | -78 | - - class B(object, A): +79 - class B(object, A): 79 + class B(A): -80 | ... | UP004 [*] Class `B` inherits from `object` @@ -254,9 +230,7 @@ UP004 [*] Class `B` inherits from `object` | help: Remove `object` inheritance | -83 | class B( - - object, -84 | A, +84 - object, | UP004 [*] Class `B` inherits from `object` @@ -271,9 +245,9 @@ UP004 [*] Class `B` inherits from `object` | help: Remove `object` inheritance | -91 | A, - - object, -92 | ): +91 - A, +92 - object, +91 + A, | UP004 [*] Class `B` inherits from `object` @@ -287,9 +261,7 @@ UP004 [*] Class `B` inherits from `object` | help: Remove `object` inheritance | -97 | class B( - - object, -98 | # Comment on A. +98 - object, | note: This is an unsafe fix and may change runtime behavior @@ -305,9 +277,9 @@ UP004 [*] Class `B` inherits from `object` | help: Remove `object` inheritance | -107 | A, - - object, -108 | ): +107 - A, +108 - object, +107 + A, | UP004 [*] Class `A` inherits from `object` @@ -321,12 +293,10 @@ UP004 [*] Class `A` inherits from `object` | help: Remove `object` inheritance | -117 | - - class A( - - object, - - ): +118 - class A( +119 - object, +120 - ): 118 + class A: -119 | ... | UP004 [*] Class `A` inherits from `object` @@ -340,12 +310,10 @@ UP004 [*] Class `A` inherits from `object` | help: Remove `object` inheritance | -123 | - - class A( - - object, # ) - - ): +124 - class A( +125 - object, # ) +126 - ): 124 + class A: -125 | ... | note: This is an unsafe fix and may change runtime behavior @@ -360,13 +328,11 @@ UP004 [*] Class `A` inherits from `object` | help: Remove `object` inheritance | -129 | - - class A( - - object # ) - - , - - ): +130 - class A( +131 - object # ) +132 - , +133 - ): 130 + class A: -131 | ... | note: This is an unsafe fix and may change runtime behavior @@ -379,10 +345,8 @@ UP004 [*] Class `A` inherits from `object` | help: Remove `object` inheritance | -136 | - - class A(object, object): +137 - class A(object, object): 137 + class A(object): -138 | ... | UP004 [*] Class `A` inherits from `object` @@ -394,10 +358,8 @@ UP004 [*] Class `A` inherits from `object` | help: Remove `object` inheritance | -136 | - - class A(object, object): +137 - class A(object, object): 137 + class A(object): -138 | ... | UP004 [*] Class `A` inherits from `object` @@ -410,10 +372,8 @@ UP004 [*] Class `A` inherits from `object` | help: Remove `object` inheritance | -141 | @decorator() - - class A(object): +142 - class A(object): 142 + class A: -143 | ... | UP004 [*] Class `A` inherits from `object` @@ -426,10 +386,8 @@ UP004 [*] Class `A` inherits from `object` | help: Remove `object` inheritance | -145 | @decorator() # class A(object): - - class A(object): +146 - class A(object): 146 + class A: -147 | ... | UP004 [*] Class `Unusual` inherits from `object` @@ -443,8 +401,6 @@ UP004 [*] Class `Unusual` inherits from `object` | help: Remove `object` inheritance | -158 | - - class Unusual(builtins.object): +159 - class Unusual(builtins.object): 159 + class Unusual: -160 | ... | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP005.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP005.py.snap index 14eddffa1e20e..5c58e430ed481 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP005.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP005.py.snap @@ -13,10 +13,8 @@ UP005 [*] `assertEquals` is deprecated, use `assertEqual` | help: Replace `assertEqual` with `assertEquals` | -5 | def test(self) -> None: - - self.assertEquals (1, 2) +6 - self.assertEquals (1, 2) 6 + self.assertEqual (1, 2) -7 | self.assertEquals(1, 2) | UP005 [*] `assertEquals` is deprecated, use `assertEqual` @@ -31,10 +29,8 @@ UP005 [*] `assertEquals` is deprecated, use `assertEqual` | help: Replace `assertEqual` with `assertEquals` | -6 | self.assertEquals (1, 2) - - self.assertEquals(1, 2) +7 - self.assertEquals(1, 2) 7 + self.assertEqual(1, 2) -8 | self.assertEqual(3, 4) | UP005 [*] `failUnlessAlmostEqual` is deprecated, use `assertAlmostEqual` @@ -47,12 +43,10 @@ UP005 [*] `failUnlessAlmostEqual` is deprecated, use `assertAlmostEqual` 10 | self.assertNotRegexpMatches("a", "b") | help: Replace `assertAlmostEqual` with `failUnlessAlmostEqual` - | -8 | self.assertEqual(3, 4) - - self.failUnlessAlmostEqual(1, 1.1) -9 + self.assertAlmostEqual(1, 1.1) -10 | self.assertNotRegexpMatches("a", "b") - | + | +9 - self.failUnlessAlmostEqual(1, 1.1) +9 + self.assertAlmostEqual(1, 1.1) + | UP005 [*] `assertNotRegexpMatches` is deprecated, use `assertNotRegex` --> UP005.py:10:9 @@ -63,7 +57,6 @@ UP005 [*] `assertNotRegexpMatches` is deprecated, use `assertNotRegex` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace `assertNotRegex` with `assertNotRegexpMatches` | -9 | self.failUnlessAlmostEqual(1, 1.1) - - self.assertNotRegexpMatches("a", "b") +10 - self.assertNotRegexpMatches("a", "b") 10 + self.assertNotRegex("a", "b") | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP006_0.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP006_0.py.snap index 16841b162d523..8446095229a2f 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP006_0.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP006_0.py.snap @@ -10,10 +10,8 @@ UP006 [*] Use `list` instead of `typing.List` for type annotation | help: Replace with `list` | -3 | - - def f(x: typing.List[str]) -> None: +4 - def f(x: typing.List[str]) -> None: 4 + def f(x: list[str]) -> None: -5 | ... | UP006 [*] Use `list` instead of `List` for type annotation @@ -25,10 +23,8 @@ UP006 [*] Use `list` instead of `List` for type annotation | help: Replace with `list` | -10 | - - def f(x: List[str]) -> None: +11 - def f(x: List[str]) -> None: 11 + def f(x: list[str]) -> None: -12 | ... | UP006 [*] Use `list` instead of `t.List` for type annotation @@ -40,10 +36,8 @@ UP006 [*] Use `list` instead of `t.List` for type annotation | help: Replace with `list` | -17 | - - def f(x: t.List[str]) -> None: +18 - def f(x: t.List[str]) -> None: 18 + def f(x: list[str]) -> None: -19 | ... | UP006 [*] Use `list` instead of `IList` for type annotation @@ -55,10 +49,8 @@ UP006 [*] Use `list` instead of `IList` for type annotation | help: Replace with `list` | -24 | - - def f(x: IList[str]) -> None: +25 - def f(x: IList[str]) -> None: 25 + def f(x: list[str]) -> None: -26 | ... | UP006 [*] Use `list` instead of `List` for type annotation @@ -70,10 +62,8 @@ UP006 [*] Use `list` instead of `List` for type annotation | help: Replace with `list` | -28 | - - def f(x: "List[str]") -> None: +29 - def f(x: "List[str]") -> None: 29 + def f(x: "list[str]") -> None: -30 | ... | UP006 [*] Use `list` instead of `List` for type annotation @@ -85,10 +75,8 @@ UP006 [*] Use `list` instead of `List` for type annotation | help: Replace with `list` | -32 | - - def f(x: r"List[str]") -> None: +33 - def f(x: r"List[str]") -> None: 33 + def f(x: r"list[str]") -> None: -34 | ... | UP006 [*] Use `list` instead of `List` for type annotation @@ -100,10 +88,8 @@ UP006 [*] Use `list` instead of `List` for type annotation | help: Replace with `list` | -36 | - - def f(x: "List[str]") -> None: +37 - def f(x: "List[str]") -> None: 37 + def f(x: "list[str]") -> None: -38 | ... | UP006 [*] Use `list` instead of `List` for type annotation @@ -115,10 +101,8 @@ UP006 [*] Use `list` instead of `List` for type annotation | help: Replace with `list` | -40 | - - def f(x: """List[str]""") -> None: +41 - def f(x: """List[str]""") -> None: 41 + def f(x: """list[str]""") -> None: -42 | ... | UP006 Use `list` instead of `List` for type annotation @@ -139,10 +123,8 @@ UP006 [*] Use `list` instead of `List` for type annotation | help: Replace with `list` | -48 | - - def f(x: "List['List[str]']") -> None: +49 - def f(x: "List['List[str]']") -> None: 49 + def f(x: "list['List[str]']") -> None: -50 | ... | UP006 [*] Use `list` instead of `List` for type annotation @@ -154,10 +136,8 @@ UP006 [*] Use `list` instead of `List` for type annotation | help: Replace with `list` | -48 | - - def f(x: "List['List[str]']") -> None: +49 - def f(x: "List['List[str]']") -> None: 49 + def f(x: "List['list[str]']") -> None: -50 | ... | UP006 [*] Use `list` instead of `List` for type annotation @@ -169,10 +149,8 @@ UP006 [*] Use `list` instead of `List` for type annotation | help: Replace with `list` | -52 | - - def f(x: "List['Li' 'st[str]']") -> None: +53 - def f(x: "List['Li' 'st[str]']") -> None: 53 + def f(x: "list['Li' 'st[str]']") -> None: -54 | ... | UP006 Use `list` instead of `List` for type annotation @@ -211,14 +189,12 @@ UP006 [*] Use `collections.deque` instead of `typing.Deque` for type annotation | help: Replace with `collections.deque` | -22 | from typing import List as IList 23 + from collections import deque -24 | --------------------------------------------------------------------------------- +24 + +25 | + … 61 | - - def f(x: typing.Deque[str]) -> None: -62 + def f(x: deque[str]) -> None: -63 | ... +62 ~ def f(x: deque[str]) -> None: | UP006 [*] Use `collections.defaultdict` instead of `typing.DefaultDict` for type annotation @@ -230,12 +206,10 @@ UP006 [*] Use `collections.defaultdict` instead of `typing.DefaultDict` for type | help: Replace with `collections.defaultdict` | -22 | from typing import List as IList 23 + from collections import defaultdict -24 | --------------------------------------------------------------------------------- +24 + +25 | + … 65 | - - def f(x: typing.DefaultDict[str, str]) -> None: -66 + def f(x: defaultdict[str, str]) -> None: -67 | ... +66 ~ def f(x: defaultdict[str, str]) -> None: | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP006_1.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP006_1.py.snap index 4c452acb85c4a..fbd3a147b9034 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP006_1.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP006_1.py.snap @@ -9,9 +9,9 @@ UP006 [*] Use `collections.defaultdict` instead of `typing.DefaultDict` for type 10 | ... | help: Replace with `collections.defaultdict` - | -8 | - - def f(x: typing.DefaultDict[str, str]) -> None: -9 + def f(x: defaultdict[str, str]) -> None: -10 | ... - | + | +6 ~ from collections import defaultdict +7 | +8 | +9 ~ def f(x: defaultdict[str, str]) -> None: + | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP006_2.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP006_2.py.snap index 57b5a75d8833e..3b4af9d077500 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP006_2.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP006_2.py.snap @@ -10,8 +10,8 @@ UP006 [*] Use `collections.defaultdict` instead of `typing.DefaultDict` for type | help: Replace with `collections.defaultdict` | +4 ~ from collections import defaultdict +5 | 6 | - - def f(x: typing.DefaultDict[str, str]) -> None: -7 + def f(x: defaultdict[str, str]) -> None: -8 | ... +7 ~ def f(x: defaultdict[str, str]) -> None: | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP006_3.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP006_3.py.snap index 07ce0f092c28c..5bdb7d47ab3b7 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP006_3.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP006_3.py.snap @@ -10,8 +10,8 @@ UP006 [*] Use `collections.defaultdict` instead of `typing.DefaultDict` for type | help: Replace with `collections.defaultdict` | +4 ~ from collections import defaultdict +5 | 6 | - - def f(x: "typing.DefaultDict[str, str]") -> None: -7 + def f(x: "defaultdict[str, str]") -> None: -8 | ... +7 ~ def f(x: "defaultdict[str, str]") -> None: | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP006_4.py_preview_with_fa100_and_future_annotations_py310.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP006_4.py_preview_with_fa100_and_future_annotations_py310.snap index 9520e8ac02c8c..d7dba94876624 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP006_4.py_preview_with_fa100_and_future_annotations_py310.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP006_4.py_preview_with_fa100_and_future_annotations_py310.snap @@ -10,10 +10,8 @@ UP006 [*] Use `list` instead of `typing.List` for type annotation | help: Replace with `list` | -4 | - - def f(x: typing.List[str]) -> None: +5 - def f(x: typing.List[str]) -> None: 5 + def f(x: list[str]) -> None: -6 | ... | UP006 [*] Use `list` instead of `List` for type annotation @@ -24,9 +22,7 @@ UP006 [*] Use `list` instead of `List` for type annotation 10 | ... | help: Replace with `list` - | -8 | - - def g(x: List[str]) -> None: -9 + def g(x: list[str]) -> None: -10 | ... - | + | +9 - def g(x: List[str]) -> None: +9 + def g(x: list[str]) -> None: + | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP007_1.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP007_1.py.snap index de174b1edeccc..33d98581c3c88 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP007_1.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP007_1.py.snap @@ -10,10 +10,8 @@ UP007 [*] Use `X | Y` for type annotations | help: Convert to `X | Y` | -4 | - - def f(x: Union[str, int, Union[float, bytes]]) -> None: +5 - def f(x: Union[str, int, Union[float, bytes]]) -> None: 5 + def f(x: str | int | Union[float, bytes]) -> None: -6 | ... | UP007 [*] Use `X | Y` for type annotations @@ -25,10 +23,8 @@ UP007 [*] Use `X | Y` for type annotations | help: Convert to `X | Y` | -4 | - - def f(x: Union[str, int, Union[float, bytes]]) -> None: +5 - def f(x: Union[str, int, Union[float, bytes]]) -> None: 5 + def f(x: Union[str, int, float | bytes]) -> None: -6 | ... | UP007 [*] Use `X | Y` for type annotations @@ -39,12 +35,10 @@ UP007 [*] Use `X | Y` for type annotations 10 | ... | help: Convert to `X | Y` - | -8 | - - def f(x: typing.Union[str, int]) -> None: -9 + def f(x: str | int) -> None: -10 | ... - | + | +9 - def f(x: typing.Union[str, int]) -> None: +9 + def f(x: str | int) -> None: + | UP007 [*] Use `X | Y` for type annotations --> UP007_1.py:13:10 @@ -55,10 +49,8 @@ UP007 [*] Use `X | Y` for type annotations | help: Convert to `X | Y` | -12 | - - def f(x: typing.Union[(str, int)]) -> None: +13 - def f(x: typing.Union[(str, int)]) -> None: 13 + def f(x: str | int) -> None: -14 | ... | UP007 [*] Use `X | Y` for type annotations @@ -70,10 +62,8 @@ UP007 [*] Use `X | Y` for type annotations | help: Convert to `X | Y` | -16 | - - def f(x: typing.Union[(str, int), float]) -> None: +17 - def f(x: typing.Union[(str, int), float]) -> None: 17 + def f(x: str | int | float) -> None: -18 | ... | UP007 [*] Use `X | Y` for type annotations @@ -85,10 +75,8 @@ UP007 [*] Use `X | Y` for type annotations | help: Convert to `X | Y` | -20 | - - def f(x: typing.Union[(int,)]) -> None: +21 - def f(x: typing.Union[(int,)]) -> None: 21 + def f(x: int) -> None: -22 | ... | UP007 [*] Use `X | Y` for type annotations @@ -100,10 +88,8 @@ UP007 [*] Use `X | Y` for type annotations | help: Convert to `X | Y` | -24 | - - def f(x: typing.Union[()]) -> None: +25 - def f(x: typing.Union[()]) -> None: 25 + def f(x: ()) -> None: -26 | ... | UP007 [*] Use `X | Y` for type annotations @@ -115,10 +101,8 @@ UP007 [*] Use `X | Y` for type annotations | help: Convert to `X | Y` | -28 | - - def f(x: "Union[str, int, Union[float, bytes]]") -> None: +29 - def f(x: "Union[str, int, Union[float, bytes]]") -> None: 29 + def f(x: "str | int | Union[float, bytes]") -> None: -30 | ... | UP007 [*] Use `X | Y` for type annotations @@ -130,10 +114,8 @@ UP007 [*] Use `X | Y` for type annotations | help: Convert to `X | Y` | -28 | - - def f(x: "Union[str, int, Union[float, bytes]]") -> None: +29 - def f(x: "Union[str, int, Union[float, bytes]]") -> None: 29 + def f(x: "Union[str, int, float | bytes]") -> None: -30 | ... | UP007 [*] Use `X | Y` for type annotations @@ -145,10 +127,8 @@ UP007 [*] Use `X | Y` for type annotations | help: Convert to `X | Y` | -32 | - - def f(x: "typing.Union[str, int]") -> None: +33 - def f(x: "typing.Union[str, int]") -> None: 33 + def f(x: "str | int") -> None: -34 | ... | UP007 [*] Use `X | Y` for type annotations @@ -160,10 +140,8 @@ UP007 [*] Use `X | Y` for type annotations | help: Convert to `X | Y` | -36 | - - def f(x: Union["str", int]) -> None: +37 - def f(x: Union["str", int]) -> None: 37 + def f(x: "str" | int) -> None: -38 | ... | UP007 [*] Use `X | Y` for type annotations @@ -175,10 +153,8 @@ UP007 [*] Use `X | Y` for type annotations | help: Convert to `X | Y` | -40 | - - def f(x: Union[("str", "int"), float]) -> None: +41 - def f(x: Union[("str", "int"), float]) -> None: 41 + def f(x: "str" | "int" | float) -> None: -42 | ... | UP007 Use `X | Y` for type annotations @@ -203,10 +179,8 @@ UP007 [*] Use `X | Y` for type annotations | help: Convert to `X | Y` | -47 | x = Union["str", "int"] - - x: Union[str, int] +48 - x: Union[str, int] 48 + x: str | int -49 | x: Union["str", "int"] | UP007 [*] Use `X | Y` for type annotations @@ -218,10 +192,8 @@ UP007 [*] Use `X | Y` for type annotations | ^^^^^^^^^^^^^^^^^^^ help: Convert to `X | Y` | -48 | x: Union[str, int] - - x: Union["str", "int"] +49 - x: Union["str", "int"] 49 + x: "str" | "int" -50 | | UP007 Use `X | Y` for type annotations @@ -288,10 +260,8 @@ UP007 [*] Use `X | Y` for type annotations | help: Convert to `X | Y` | -82 | # Regression test for: https://github.com/astral-sh/ruff/issues/8609 - - def f(x: Union[int, str, bytes]) -> None: +83 - def f(x: Union[int, str, bytes]) -> None: 83 + def f(x: int | str | bytes) -> None: -84 | ... | UP007 [*] Use `X | Y` for type annotations @@ -305,10 +275,8 @@ UP007 [*] Use `X | Y` for type annotations | help: Convert to `X | Y` | -90 | - - def myfunc(param: "tuple[Union[int, 'AClass', None], str]"): +91 - def myfunc(param: "tuple[Union[int, 'AClass', None], str]"): 91 + def myfunc(param: "tuple[int | 'AClass' | None, str]"): -92 | print(param) | UP007 [*] Use `X | Y` for type annotations @@ -325,12 +293,7 @@ UP007 [*] Use `X | Y` for type annotations | |_____^ help: Convert to `X | Y` | -150 | - - LongLiterals: TypeAlias = Union[ - - Literal["LongLiteralNumberOne"] -151 + LongLiterals: TypeAlias = (Literal["LongLiteralNumberOne"] -152 | | Literal["LongLiteralNumberTwo"] - - | Literal["LongLiteralNumberThree"] - - ] +151 ~ LongLiterals: TypeAlias = (Literal["LongLiteralNumberOne"] +152 + | Literal["LongLiteralNumberTwo"] 153 + | Literal["LongLiteralNumberThree"]) | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP007_2.py_preview_with_fa100_and_future_annotations_py310.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP007_2.py_preview_with_fa100_and_future_annotations_py310.snap index fe6c507139bc2..d00eee4fdb0f1 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP007_2.py_preview_with_fa100_and_future_annotations_py310.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP007_2.py_preview_with_fa100_and_future_annotations_py310.snap @@ -10,10 +10,8 @@ UP007 [*] Use `X | Y` for type annotations | help: Convert to `X | Y` | -4 | - - def f(x: Union[str, int, Union[float, bytes]]) -> None: +5 - def f(x: Union[str, int, Union[float, bytes]]) -> None: 5 + def f(x: str | int | Union[float, bytes]) -> None: -6 | ... | UP007 [*] Use `X | Y` for type annotations @@ -25,10 +23,8 @@ UP007 [*] Use `X | Y` for type annotations | help: Convert to `X | Y` | -4 | - - def f(x: Union[str, int, Union[float, bytes]]) -> None: +5 - def f(x: Union[str, int, Union[float, bytes]]) -> None: 5 + def f(x: Union[str, int, float | bytes]) -> None: -6 | ... | UP007 [*] Use `X | Y` for type annotations @@ -39,9 +35,7 @@ UP007 [*] Use `X | Y` for type annotations 10 | ... | help: Convert to `X | Y` - | -8 | - - def f(x: typing.Union[str, int]) -> None: -9 + def f(x: str | int) -> None: -10 | ... - | + | +9 - def f(x: typing.Union[str, int]) -> None: +9 + def f(x: str | int) -> None: + | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP008.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP008.py.snap index ab341e4a98207..0f914e953b2fa 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP008.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP008.py.snap @@ -12,10 +12,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | help: Remove `super()` parameters | -16 | def wrong(self): - - parent = super(Child, self) # wrong +17 - parent = super(Child, self) # wrong 17 + parent = super() # wrong -18 | super(Child, self).method # wrong | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -30,10 +28,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | help: Remove `super()` parameters | -17 | parent = super(Child, self) # wrong - - super(Child, self).method # wrong +18 - super(Child, self).method # wrong 18 + super().method # wrong -19 | super( | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -49,13 +45,11 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | |_________^ help: Remove `super()` parameters | -18 | super(Child, self).method # wrong - - super( - - Child, - - self, - - ).method() # wrong +19 - super( +20 - Child, +21 - self, +22 - ).method() # wrong 19 + super().method() # wrong -20 | | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -69,10 +63,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | help: Remove `super()` parameters | -35 | def normal(self): - - super(MyClass, self).f() # can use super() +36 - super(MyClass, self).f() # can use super() 36 + super().f() # can use super() -37 | super().f() | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -85,10 +77,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | help: Remove `super()` parameters | -70 | def inner_argument(self): - - super(MyClass, self).f() # can use super() +71 - super(MyClass, self).f() # can use super() 71 + super().f() # can use super() -72 | super().f() | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -102,10 +92,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | help: Remove `super()` parameters | -97 | def normal(self): - - super(DataClass, self).f() # Error +98 - super(DataClass, self).f() # Error 98 + super().f() # Error -99 | super().f() # OK | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -117,10 +105,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | ^^^^^^^^^^^^^^^^^ help: Remove `super()` parameters | -115 | def bar(self): - - super(__class__, self).foo() +116 - super(__class__, self).foo() 116 + super().foo() -117 | | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -140,14 +126,12 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | help: Remove `super()` parameters | -136 | def with_comments(self): - - super( - - # super helpful comment - - ClassForCommentEnthusiasts, - - self - - ).f() +137 - super( +138 - # super helpful comment +139 - ClassForCommentEnthusiasts, +140 - self +141 - ).f() 137 + super().f() -138 | super( | note: This is an unsafe fix and may change runtime behavior @@ -168,14 +152,12 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | help: Remove `super()` parameters | -141 | ).f() - - super( - - ClassForCommentEnthusiasts, - - # even more helpful comment - - self - - ).f() +142 - super( +143 - ClassForCommentEnthusiasts, +144 - # even more helpful comment +145 - self +146 - ).f() 142 + super().f() -143 | super( | note: This is an unsafe fix and may change runtime behavior @@ -193,14 +175,12 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | |_________^ help: Remove `super()` parameters | -146 | ).f() - - super( - - ClassForCommentEnthusiasts, - - self - - # also a comment - - ).f() +147 - super( +148 - ClassForCommentEnthusiasts, +149 - self +150 - # also a comment +151 - ).f() 147 + super().f() -148 | | note: This is an unsafe fix and may change runtime behavior @@ -250,10 +230,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | help: Remove `super()` parameters | -166 | def method3(self): - - super(ExampleWithKeywords, self).some_method() # Should be fixed - no keywords +167 - super(ExampleWithKeywords, self).some_method() # Should be fixed - no keywords 167 + super().some_method() # Should be fixed - no keywords -168 | | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -268,10 +246,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | help: Remove `super()` parameters | -177 | if False: __class__ # Python injects __class__ into scope - - builtins.super(ChildD1, self).f() +178 - builtins.super(ChildD1, self).f() 178 + builtins.super().f() -179 | | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -286,10 +262,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | help: Remove `super()` parameters | -182 | if False: super # Python injects __class__ into scope - - builtins.super(ChildD2, self).f() +183 - builtins.super(ChildD2, self).f() 183 + builtins.super().f() -184 | | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -303,10 +277,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | help: Remove `super()` parameters | -186 | def f(self): - - builtins.super(ChildD3, self).f() +187 - builtins.super(ChildD3, self).f() 187 + builtins.super().f() -188 | super # Python injects __class__ into scope | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -320,10 +292,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | help: Remove `super()` parameters | -192 | def f(self): - - builtins_alias.super(ChildD4, self).f() +193 - builtins_alias.super(ChildD4, self).f() 193 + builtins_alias.super().f() -194 | super # Python injects __class__ into scope | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -338,10 +308,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | help: Remove `super()` parameters | -199 | super # Python injects __class__ into scope - - builtins.super(ChildD5, self).f() +200 - builtins.super(ChildD5, self).f() 200 + builtins.super().f() -201 | | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -356,10 +324,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | help: Remove `super()` parameters | -205 | __class__ # Python injects __class__ into scope - - builtins.super(ChildD6, self).f() +206 - builtins.super(ChildD6, self).f() 206 + builtins.super().f() -207 | | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -374,10 +340,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | help: Remove `super()` parameters | -211 | __class__ # Python injects __class__ into scope - - builtins.super(ChildD7, self).f() +212 - builtins.super(ChildD7, self).f() 212 + builtins.super().f() -213 | | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -392,10 +356,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | help: Remove `super()` parameters | -218 | super # Python injects __class__ into scope - - builtins.super(ChildD8, self).f() +219 - builtins.super(ChildD8, self).f() 219 + builtins.super().f() -220 | | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -410,10 +372,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | help: Remove `super()` parameters | -225 | __class__ # Python injects __class__ into scope - - builtins.super(ChildD9, self).f() +226 - builtins.super(ChildD9, self).f() 226 + builtins.super().f() -227 | | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -425,10 +385,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | ^^^^^^^^^^^^^^^^ help: Remove `super()` parameters | -232 | super # Python injects __class__ into scope - - builtins.super(ChildD10, self).f() +233 - builtins.super(ChildD10, self).f() 233 + builtins.super().f() -234 | | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -440,10 +398,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | ^^^^^^^^^^^^^^^^^^^ help: Remove `super()` parameters | -341 | def __init__(self, foo): - - super(Outer.Inner, self).__init__(foo) # UP008: matches enclosing class chain +342 - super(Outer.Inner, self).__init__(foo) # UP008: matches enclosing class chain 342 + super().__init__(foo) # UP008: matches enclosing class chain -343 | | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -458,10 +414,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | help: Remove `super()` parameters | -376 | def __init__(self, foo): - - super(A.B.C, self).__init__(foo) # UP008: matches full chain +377 - super(A.B.C, self).__init__(foo) # UP008: matches full chain 377 + super().__init__(foo) # UP008: matches full chain -378 | | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -473,10 +427,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | ^^^^^^^^^^^^^^^^^^ help: Remove `super()` parameters | -387 | def f(self): - - super (Whitespace, self).f() # can use super() +388 - super (Whitespace, self).f() # can use super() 388 + super ().f() # can use super() -389 | | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -488,10 +440,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove `super()` parameters | -394 | def f(self): - - super(LocalOuter.LocalInner, self).f() # can use super() +395 - super(LocalOuter.LocalInner, self).f() # can use super() 395 + super().f() # can use super() -396 | | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -502,10 +452,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | ^^^^^^^^^^^^^^^^^^^^ help: Remove `super()` parameters | -398 | class LambdaMethod(BaseClass): - - f = lambda self: super(LambdaMethod, self).f() # can use super() +399 - f = lambda self: super(LambdaMethod, self).f() # can use super() 399 + f = lambda self: super().f() # can use super() -400 | | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -517,10 +465,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | ^^^^^^^^^^^^^^^^^^ help: Remove `super()` parameters | -404 | def f(cls): - - super(ClassMethod, cls).f() # can use super() +405 - super(ClassMethod, cls).f() # can use super() 405 + super().f() # can use super() -406 | | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -532,10 +478,8 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | ^^^^^^^^^^^^^^^^^^^ help: Remove `super()` parameters | -409 | async def f(self): - - super(AsyncMethod, self).f() # can use super() +410 - super(AsyncMethod, self).f() # can use super() 410 + super().f() # can use super() -411 | | UP008 [*] Use `super()` instead of `super(__class__, self)` @@ -547,7 +491,6 @@ UP008 [*] Use `super()` instead of `super(__class__, self)` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove `super()` parameters | -415 | def f(self): - - super (OuterWithWhitespace.Inner, self).f() # can use super() +416 - super (OuterWithWhitespace.Inner, self).f() # can use super() 416 + super ().f() # can use super() | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_0.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_0.py.snap index bf709133db2f4..7c7c8896dc8aa 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_0.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_0.py.snap @@ -11,6 +11,5 @@ UP009 [*] UTF-8 encoding declaration is unnecessary | help: Remove unnecessary coding comment | - - # coding=utf8 -1 | +1 - # coding=utf8 | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_1.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_1.py.snap index 062edfe0e4084..90cc7b3bcbdc2 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_1.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_1.py.snap @@ -12,7 +12,5 @@ UP009 [*] UTF-8 encoding declaration is unnecessary | help: Remove unnecessary coding comment | -1 | #!/usr/bin/python - - # -*- coding: utf-8 -*- -2 | +2 - # -*- coding: utf-8 -*- | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_6.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_6.py.snap index b4e4755a45aa5..bcc7c24783384 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_6.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_6.py.snap @@ -10,6 +10,5 @@ UP009 [*] UTF-8 encoding declaration is unnecessary | help: Remove unnecessary coding comment | - - # coding=utf8 -1 | print("Hello world") +1 - # coding=utf8 | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_7.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_7.py.snap index d6b18928e5029..dd64b7cb68bc2 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_7.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_7.py.snap @@ -10,6 +10,5 @@ UP009 [*] UTF-8 encoding declaration is unnecessary | help: Remove unnecessary coding comment | - - # coding=utf8 -1 | print("Hello world") +1 - # coding=utf8 | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_utf8_code_other.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_utf8_code_other.py.snap index 0b7473c13e718..7139cc04fee2e 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_utf8_code_other.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_utf8_code_other.py.snap @@ -11,6 +11,5 @@ UP009 [*] UTF-8 encoding declaration is unnecessary | help: Remove unnecessary coding comment | - - # -*- coding: utf8 -*- -1 | print("the following is not a coding comment") +1 - # -*- coding: utf8 -*- | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_utf8_utf8.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_utf8_utf8.py.snap index cc909b510cd01..724bdbfd52014 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_utf8_utf8.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_utf8_utf8.py.snap @@ -10,6 +10,5 @@ UP009 [*] UTF-8 encoding declaration is unnecessary | help: Remove unnecessary coding comment | -1 | # -*- coding: utf-8 -*- - - # -*- coding: utf-8 -*- +1 - # -*- coding: utf-8 -*- | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_utf8_utf8_other.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_utf8_utf8_other.py.snap index b072ce625ec39..e5541d46286c2 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_utf8_utf8_other.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP009_utf8_utf8_other.py.snap @@ -11,7 +11,5 @@ UP009 [*] UTF-8 encoding declaration is unnecessary | help: Remove unnecessary coding comment | -1 | # -*- coding: utf-8 -*- - - # -*- coding: utf-8 -*- -2 | # -*- coding: ascii -*- +1 - # -*- coding: utf-8 -*- | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP010_0.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP010_0.py.snap index 1eba176457d71..89e7d48e4585a 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP010_0.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP010_0.py.snap @@ -11,8 +11,7 @@ UP010 [*] Unnecessary `__future__` imports `generators`, `nested_scopes` for tar | help: Remove unnecessary `__future__` import | - - from __future__ import nested_scopes, generators -1 | from __future__ import with_statement, unicode_literals +1 - from __future__ import nested_scopes, generators | UP010 [*] Unnecessary `__future__` imports `unicode_literals`, `with_statement` for target Python version @@ -26,9 +25,7 @@ UP010 [*] Unnecessary `__future__` imports `unicode_literals`, `with_statement` | help: Remove unnecessary `__future__` import | -1 | from __future__ import nested_scopes, generators - - from __future__ import with_statement, unicode_literals -2 | from __future__ import absolute_import, division +2 - from __future__ import with_statement, unicode_literals | UP010 [*] Unnecessary `__future__` imports `absolute_import`, `division` for target Python version @@ -43,9 +40,7 @@ UP010 [*] Unnecessary `__future__` imports `absolute_import`, `division` for tar | help: Remove unnecessary `__future__` import | -2 | from __future__ import with_statement, unicode_literals - - from __future__ import absolute_import, division -3 | from __future__ import generator_stop +3 - from __future__ import absolute_import, division | UP010 [*] Unnecessary `__future__` import `generator_stop` for target Python version @@ -60,9 +55,7 @@ UP010 [*] Unnecessary `__future__` import `generator_stop` for target Python ver | help: Remove unnecessary `__future__` import | -3 | from __future__ import absolute_import, division - - from __future__ import generator_stop -4 | from __future__ import print_function, generator_stop +4 - from __future__ import generator_stop | UP010 [*] Unnecessary `__future__` imports `generator_stop`, `print_function` for target Python version @@ -76,9 +69,7 @@ UP010 [*] Unnecessary `__future__` imports `generator_stop`, `print_function` fo | help: Remove unnecessary `__future__` import | -4 | from __future__ import generator_stop - - from __future__ import print_function, generator_stop -5 | from __future__ import invalid_module, generators +5 - from __future__ import print_function, generator_stop | UP010 [*] Unnecessary `__future__` import `generators` for target Python version @@ -93,10 +84,8 @@ UP010 [*] Unnecessary `__future__` import `generators` for target Python version | help: Remove unnecessary `__future__` import | -5 | from __future__ import print_function, generator_stop - - from __future__ import invalid_module, generators +6 - from __future__ import invalid_module, generators 6 + from __future__ import invalid_module -7 | | UP010 [*] Unnecessary `__future__` import `generator_stop` for target Python version @@ -108,11 +97,9 @@ UP010 [*] Unnecessary `__future__` import `generator_stop` for target Python ver 10 | from __future__ import generators | help: Remove unnecessary `__future__` import - | -8 | if True: - - from __future__ import generator_stop -9 | from __future__ import generators - | + | + 9 - from __future__ import generator_stop + | UP010 [*] Unnecessary `__future__` import `generators` for target Python version --> UP010_0.py:10:5 @@ -126,9 +113,7 @@ UP010 [*] Unnecessary `__future__` import `generators` for target Python version | help: Remove unnecessary `__future__` import | -9 | from __future__ import generator_stop - - from __future__ import generators -10 | +10 - from __future__ import generators | UP010 [*] Unnecessary `__future__` import `generator_stop` for target Python version @@ -142,9 +127,7 @@ UP010 [*] Unnecessary `__future__` import `generator_stop` for target Python ver | help: Remove unnecessary `__future__` import | -12 | if True: - - from __future__ import generator_stop -13 | from __future__ import invalid_module, generators +13 - from __future__ import generator_stop | UP010 [*] Unnecessary `__future__` import `generators` for target Python version @@ -158,10 +141,8 @@ UP010 [*] Unnecessary `__future__` import `generators` for target Python version | help: Remove unnecessary `__future__` import | -13 | from __future__ import generator_stop - - from __future__ import invalid_module, generators +14 - from __future__ import invalid_module, generators 14 + from __future__ import invalid_module -15 | from __future__ import generators # comment | UP010 [*] Unnecessary `__future__` import `generators` for target Python version @@ -173,7 +154,6 @@ UP010 [*] Unnecessary `__future__` import `generators` for target Python version | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove unnecessary `__future__` import | -14 | from __future__ import invalid_module, generators - - from __future__ import generators # comment +15 - from __future__ import generators # comment | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP010_1.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP010_1.py.snap index c40894db56420..c1addafcdbf11 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP010_1.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP010_1.py.snap @@ -10,8 +10,7 @@ UP010 [*] Unnecessary `__future__` imports `generators`, `nested_scopes` for tar | help: Remove unnecessary `__future__` import | - - from __future__ import nested_scopes, generators -1 | from __future__ import with_statement, unicode_literals +1 - from __future__ import nested_scopes, generators | UP010 [*] Unnecessary `__future__` import `unicode_literals` for target Python version @@ -25,10 +24,8 @@ UP010 [*] Unnecessary `__future__` import `unicode_literals` for target Python v | help: Remove unnecessary `__future__` import | -1 | from __future__ import nested_scopes, generators - - from __future__ import with_statement, unicode_literals +2 - from __future__ import with_statement, unicode_literals 2 + from __future__ import with_statement -3 | | UP010 [*] Unnecessary `__future__` import `absolute_import` for target Python version @@ -43,10 +40,8 @@ UP010 [*] Unnecessary `__future__` import `absolute_import` for target Python ve | help: Remove unnecessary `__future__` import | -3 | - - from __future__ import absolute_import, division +4 - from __future__ import absolute_import, division 4 + from __future__ import division -5 | from __future__ import generator_stop | UP010 [*] Unnecessary `__future__` import `generator_stop` for target Python version @@ -59,9 +54,7 @@ UP010 [*] Unnecessary `__future__` import `generator_stop` for target Python ver | help: Remove unnecessary `__future__` import | -4 | from __future__ import absolute_import, division - - from __future__ import generator_stop -5 | from __future__ import print_function, nested_scopes, generator_stop +5 - from __future__ import generator_stop | UP010 [*] Unnecessary `__future__` import `nested_scopes` for target Python version @@ -76,8 +69,6 @@ UP010 [*] Unnecessary `__future__` import `nested_scopes` for target Python vers | help: Remove unnecessary `__future__` import | -5 | from __future__ import generator_stop - - from __future__ import print_function, nested_scopes, generator_stop +6 - from __future__ import print_function, nested_scopes, generator_stop 6 + from __future__ import print_function, generator_stop -7 | | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP011.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP011.py.snap index 48cd2149ab066..797067fec82d5 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP011.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP011.py.snap @@ -11,10 +11,8 @@ UP011 [*] Unnecessary parentheses to `functools.lru_cache` | help: Remove unnecessary parentheses | -4 | - - @functools.lru_cache() +5 - @functools.lru_cache() 5 + @functools.lru_cache -6 | def fixme(): | UP011 [*] Unnecessary parentheses to `functools.lru_cache` @@ -27,10 +25,8 @@ UP011 [*] Unnecessary parentheses to `functools.lru_cache` | help: Remove unnecessary parentheses | -9 | - - @lru_cache() +10 - @lru_cache() 10 + @lru_cache -11 | def fixme(): | UP011 [*] Unnecessary parentheses to `functools.lru_cache` @@ -44,10 +40,8 @@ UP011 [*] Unnecessary parentheses to `functools.lru_cache` | help: Remove unnecessary parentheses | -15 | @other_decorator - - @functools.lru_cache() +16 - @functools.lru_cache() 16 + @functools.lru_cache -17 | def fixme(): | UP011 [*] Unnecessary parentheses to `functools.lru_cache` @@ -60,8 +54,6 @@ UP011 [*] Unnecessary parentheses to `functools.lru_cache` | help: Remove unnecessary parentheses | -20 | - - @functools.lru_cache() +21 - @functools.lru_cache() 21 + @functools.lru_cache -22 | @other_decorator | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP012.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP012.py.snap index a0adc52d17031..008c2632e2633 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP012.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP012.py.snap @@ -12,10 +12,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -1 | # ASCII literals should be replaced by a bytes literal - - "foo".encode("utf-8") # b"foo" +2 - "foo".encode("utf-8") # b"foo" 2 + b"foo" # b"foo" -3 | "foo".encode("u8") # b"foo" | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -30,10 +28,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -2 | "foo".encode("utf-8") # b"foo" - - "foo".encode("u8") # b"foo" +3 - "foo".encode("u8") # b"foo" 3 + b"foo" # b"foo" -4 | "foo".encode() # b"foo" | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -48,10 +44,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -3 | "foo".encode("u8") # b"foo" - - "foo".encode() # b"foo" +4 - "foo".encode() # b"foo" 4 + b"foo" # b"foo" -5 | "foo".encode("UTF8") # b"foo" | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -66,10 +60,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -4 | "foo".encode() # b"foo" - - "foo".encode("UTF8") # b"foo" +5 - "foo".encode("UTF8") # b"foo" 5 + b"foo" # b"foo" -6 | U"foo".encode("utf-8") # b"foo" | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -84,10 +76,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -5 | "foo".encode("UTF8") # b"foo" - - U"foo".encode("utf-8") # b"foo" +6 - U"foo".encode("utf-8") # b"foo" 6 + b"foo" # b"foo" -7 | "foo".encode(encoding="utf-8") # b"foo" | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -102,10 +92,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -6 | U"foo".encode("utf-8") # b"foo" - - "foo".encode(encoding="utf-8") # b"foo" +7 - "foo".encode(encoding="utf-8") # b"foo" 7 + b"foo" # b"foo" -8 | """ | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -126,17 +114,11 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -7 | "foo".encode(encoding="utf-8") # b"foo" - - """ -8 + b""" -9 | Lorem -10 | -11 | Ipsum - - """.encode( - - "utf-8" - - ) + 8 + b""" + 9 + Lorem +10 + +11 + Ipsum 12 + """ -13 | ( | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -152,12 +134,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -15 | ( - - "Lorem " - - "Ipsum".encode() -16 + b"Lorem " +16 ~ b"Lorem " 17 + b"Ipsum" -18 | ) | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -173,12 +151,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -19 | ( - - "Lorem " # Comment - - "Ipsum".encode() # Comment -20 + b"Lorem " # Comment -21 + b"Ipsum" # Comment -22 | ) +20 ~ b"Lorem " # Comment +21 ~ b"Ipsum" # Comment | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -192,10 +166,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -23 | ( - - "Lorem " "Ipsum".encode() +24 - "Lorem " "Ipsum".encode() 24 + b"Lorem " b"Ipsum" -25 | ) | UP012 [*] Unnecessary UTF-8 `encoding` argument to `encode` @@ -209,10 +181,8 @@ UP012 [*] Unnecessary UTF-8 `encoding` argument to `encode` | help: Remove unnecessary `encoding` argument | -31 | bar = "bar" - - f"foo{bar}".encode("utf-8") +32 - f"foo{bar}".encode("utf-8") 32 + f"foo{bar}".encode() -33 | encoding = "latin" | UP012 [*] Unnecessary UTF-8 `encoding` argument to `encode` @@ -229,12 +199,10 @@ UP012 [*] Unnecessary UTF-8 `encoding` argument to `encode` | help: Remove unnecessary `encoding` argument | -35 | f"foo{bar}".encode(encoding) - - f"{a=} {b=}".encode( - - "utf-8", - - ) +36 - f"{a=} {b=}".encode( +37 - "utf-8", +38 - ) 36 + f"{a=} {b=}".encode() -37 | | UP012 [*] Unnecessary UTF-8 `encoding` argument to `encode` @@ -248,10 +216,8 @@ UP012 [*] Unnecessary UTF-8 `encoding` argument to `encode` | help: Remove unnecessary `encoding` argument | -52 | # Unicode literals should only be stripped of default encoding. - - "unicode text©".encode("utf-8") # "unicode text©".encode() +53 - "unicode text©".encode("utf-8") # "unicode text©".encode() 53 + "unicode text©".encode() # "unicode text©".encode() -54 | "unicode text©".encode() | UP012 [*] Unnecessary UTF-8 `encoding` argument to `encode` @@ -266,10 +232,8 @@ UP012 [*] Unnecessary UTF-8 `encoding` argument to `encode` | help: Remove unnecessary `encoding` argument | -54 | "unicode text©".encode() - - "unicode text©".encode(encoding="UTF8") # "unicode text©".encode() +55 - "unicode text©".encode(encoding="UTF8") # "unicode text©".encode() 55 + "unicode text©".encode() # "unicode text©".encode() -56 | | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -284,10 +248,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -56 | - - r"foo\o".encode("utf-8") # br"foo\o" +57 - r"foo\o".encode("utf-8") # br"foo\o" 57 + br"foo\o" # br"foo\o" -58 | u"foo".encode("utf-8") # b"foo" | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -301,10 +263,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -57 | r"foo\o".encode("utf-8") # br"foo\o" - - u"foo".encode("utf-8") # b"foo" +58 - u"foo".encode("utf-8") # b"foo" 58 + b"foo" # b"foo" -59 | R"foo\o".encode("utf-8") # br"foo\o" | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -319,10 +279,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -58 | u"foo".encode("utf-8") # b"foo" - - R"foo\o".encode("utf-8") # br"foo\o" +59 - R"foo\o".encode("utf-8") # br"foo\o" 59 + bR"foo\o" # br"foo\o" -60 | U"foo".encode("utf-8") # b"foo" | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -336,10 +294,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -59 | R"foo\o".encode("utf-8") # br"foo\o" - - U"foo".encode("utf-8") # b"foo" +60 - U"foo".encode("utf-8") # b"foo" 60 + b"foo" # b"foo" -61 | print("foo".encode()) # print(b"foo") | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -354,10 +310,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -60 | U"foo".encode("utf-8") # b"foo" - - print("foo".encode()) # print(b"foo") +61 - print("foo".encode()) # print(b"foo") 61 + print(b"foo") # print(b"foo") -62 | | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -374,14 +328,10 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -64 | ( - - "abc" - - "def" - - ).encode() +64 + ( 65 + b"abc" 66 + b"def" 67 + ) -68 | | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -399,14 +349,10 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -69 | (( - - "abc" - - "def" - - )).encode() +69 + (( 70 + b"abc" 71 + b"def" 72 + )) -73 | | UP012 [*] Unnecessary UTF-8 `encoding` argument to `encode` @@ -421,10 +367,8 @@ UP012 [*] Unnecessary UTF-8 `encoding` argument to `encode` | help: Remove unnecessary `encoding` argument | -73 | - - (f"foo{bar}").encode("utf-8") +74 - (f"foo{bar}").encode("utf-8") 74 + (f"foo{bar}").encode() -75 | (f"foo{bar}").encode(encoding="utf-8") | UP012 [*] Unnecessary UTF-8 `encoding` argument to `encode` @@ -438,10 +382,8 @@ UP012 [*] Unnecessary UTF-8 `encoding` argument to `encode` | help: Remove unnecessary `encoding` argument | -74 | (f"foo{bar}").encode("utf-8") - - (f"foo{bar}").encode(encoding="utf-8") +75 - (f"foo{bar}").encode(encoding="utf-8") 75 + (f"foo{bar}").encode() -76 | ("unicode text©").encode("utf-8") | UP012 [*] Unnecessary UTF-8 `encoding` argument to `encode` @@ -455,10 +397,8 @@ UP012 [*] Unnecessary UTF-8 `encoding` argument to `encode` | help: Remove unnecessary `encoding` argument | -75 | (f"foo{bar}").encode(encoding="utf-8") - - ("unicode text©").encode("utf-8") +76 - ("unicode text©").encode("utf-8") 76 + ("unicode text©").encode() -77 | ("unicode text©").encode(encoding="utf-8") | UP012 [*] Unnecessary UTF-8 `encoding` argument to `encode` @@ -470,10 +410,8 @@ UP012 [*] Unnecessary UTF-8 `encoding` argument to `encode` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove unnecessary `encoding` argument | -76 | ("unicode text©").encode("utf-8") - - ("unicode text©").encode(encoding="utf-8") +77 - ("unicode text©").encode(encoding="utf-8") 77 + ("unicode text©").encode() -78 | | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -488,10 +426,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -81 | def _match_ignore(line): - - input=stdin and'\n'.encode()or None -82 + input=stdin and b'\n' or None -83 | +82 - input=stdin and'\n'.encode()or None +82 + input=stdin and b'\n' or None | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -506,10 +442,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -85 | # Refer: https://github.com/astral-sh/ruff/issues/11736 - - x: '"foo".encode("utf-8")' +86 - x: '"foo".encode("utf-8")' 86 + x: 'b"foo"' -87 | | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -523,10 +457,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -95 | ## Errors - - ("a" "b").encode() +96 - ("a" "b").encode() 96 + (b"a" b"b") -97 | | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -541,14 +473,10 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 101 | '\x20\\'.encode() | help: Rewrite as bytes literal - | -97 | - - '''\ - - '''.encode() -98 + b'''\ -99 + ''' -100 | - | + | +98 + b'''\ +99 + ''' + | UP012 [*] Unnecessary call to `encode` as UTF-8 --> UP012.py:101:1 @@ -562,10 +490,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -100 | - - '\x20\\'.encode() +101 - '\x20\\'.encode() 101 + b'\x20\\' -102 | '\0\b0'.encode() | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -579,10 +505,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -101 | '\x20\\'.encode() - - '\0\b0'.encode() +102 - '\0\b0'.encode() 102 + b'\0\b0' -103 | '\01\fc'.encode() | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -596,10 +520,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -102 | '\0\b0'.encode() - - '\01\fc'.encode() +103 - '\01\fc'.encode() 103 + b'\01\fc' -104 | '\143\\'.encode() | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -614,10 +536,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -103 | '\01\fc'.encode() - - '\143\\'.encode() +104 - '\143\\'.encode() 104 + b'\143\\' -105 | | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -632,10 +552,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -105 | - - ("a" "\b").encode() +106 - ("a" "\b").encode() 106 + (b"a" b"\b") -107 | ("\a" "b").encode() | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -649,10 +567,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -106 | ("a" "\b").encode() - - ("\a" "b").encode() +107 - ("\a" "b").encode() 107 + (b"\a" b"b") -108 | ("\a" r"\b").encode() | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -666,10 +582,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -107 | ("\a" "b").encode() - - ("\a" r"\b").encode() +108 - ("\a" r"\b").encode() 108 + (b"\a" br"\b") -109 | (r"\a" "\b").encode() | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -684,10 +598,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -108 | ("\a" r"\b").encode() - - (r"\a" "\b").encode() +109 - (r"\a" "\b").encode() 109 + (br"\a" b"\b") -110 | | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -701,10 +613,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -110 | - - '\"'.encode() +111 - '\"'.encode() 111 + b'\"' -112 | "\'".encode() | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -718,10 +628,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -111 | '\"'.encode() - - "\'".encode() +112 - "\'".encode() 112 + b"\'" -113 | | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -735,10 +643,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -113 | - - '\\\\\\\\ '.encode() # 4 backslashes +114 - '\\\\\\\\ '.encode() # 4 backslashes 114 + b'\\\\\\\\ ' # 4 backslashes -115 | '\\\\\\\ '.encode() # `\ ` is invalid but only causes a SyntaxWarning | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -752,10 +658,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -114 | '\\\\\\\\ '.encode() # 4 backslashes - - '\\\\\\\ '.encode() # `\ ` is invalid but only causes a SyntaxWarning +115 - '\\\\\\\ '.encode() # `\ ` is invalid but only causes a SyntaxWarning 115 + b'\\\\\\\ ' # `\ ` is invalid but only causes a SyntaxWarning -116 | | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -769,10 +673,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -116 | - - '\\a'.encode() +117 - '\\a'.encode() 117 + b'\\a' -118 | 'a\\\b'.encode() | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -786,10 +688,8 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | help: Rewrite as bytes literal | -117 | '\\a'.encode() - - 'a\\\b'.encode() +118 - 'a\\\b'.encode() 118 + b'a\\\b' -119 | | UP012 [*] Unnecessary call to `encode` as UTF-8 @@ -801,8 +701,6 @@ UP012 [*] Unnecessary call to `encode` as UTF-8 | ^^^^^^^^^^^^^^^^^^^^ help: Rewrite as bytes literal | -119 | - - '\\ u0000 '.encode() +120 - '\\ u0000 '.encode() 120 + b'\\ u0000 ' -121 | | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP013.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP013.py.snap index d207369864398..6cc1322616dd9 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP013.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP013.py.snap @@ -12,12 +12,9 @@ UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax | help: Convert `MyType` to class syntax | -4 | # dict literal - - MyType = TypedDict("MyType", {"a": int, "b": str}) 5 + class MyType(TypedDict): 6 + a: int 7 + b: str -8 | | UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax @@ -31,12 +28,9 @@ UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax | help: Convert `MyType` to class syntax | -7 | # dict call - - MyType = TypedDict("MyType", dict(a=int, b=str)) -8 + class MyType(TypedDict): -9 + a: int + 8 + class MyType(TypedDict): + 9 + a: int 10 + b: str -11 | | UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax @@ -50,12 +44,9 @@ UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax | help: Convert `MyType` to class syntax | -10 | # kwargs - - MyType = TypedDict("MyType", a=int, b=str) 11 + class MyType(TypedDict): 12 + a: int 13 + b: str -14 | | UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax @@ -69,11 +60,8 @@ UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax | help: Convert `MyType` to class syntax | -13 | # Empty TypedDict - - MyType = TypedDict("MyType") 14 + class MyType(TypedDict): 15 + pass -16 | | UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax @@ -86,11 +74,8 @@ UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax | help: Convert `MyType` to class syntax | -16 | # Literal values - - MyType = TypedDict("MyType", {"a": "hello"}) 17 + class MyType(TypedDict): 18 + a: "hello" -19 | MyType = TypedDict("MyType", a="hello") | UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax @@ -105,11 +90,8 @@ UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax | help: Convert `MyType` to class syntax | -17 | MyType = TypedDict("MyType", {"a": "hello"}) - - MyType = TypedDict("MyType", a="hello") 18 + class MyType(TypedDict): 19 + a: "hello" -20 | | UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax @@ -123,11 +105,8 @@ UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax | help: Convert `MyType` to class syntax | -20 | # NotRequired - - MyType = TypedDict("MyType", {"a": NotRequired[dict]}) 21 + class MyType(TypedDict): 22 + a: NotRequired[dict] -23 | | UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax @@ -141,12 +120,9 @@ UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax | help: Convert `MyType` to class syntax | -23 | # total - - MyType = TypedDict("MyType", {"x": int, "y": int}, total=False) 24 + class MyType(TypedDict, total=False): 25 + x: int 26 + y: int -27 | | UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax @@ -160,11 +136,8 @@ UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax | help: Convert `MyType` to class syntax | -26 | # using Literal type - - MyType = TypedDict("MyType", {"key": Literal["value"]}) 27 + class MyType(TypedDict): 28 + key: Literal["value"] -29 | | UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax @@ -178,11 +151,8 @@ UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax | help: Convert `MyType` to class syntax | -29 | # using namespace TypedDict - - MyType = typing.TypedDict("MyType", {"key": int}) 30 + class MyType(typing.TypedDict): 31 + key: int -32 | | UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax @@ -196,11 +166,8 @@ UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax | help: Convert `MyType` to class syntax | -39 | # Empty dict literal - - MyType = TypedDict("MyType", {}) 40 + class MyType(TypedDict): 41 + pass -42 | | UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax @@ -214,11 +181,8 @@ UP013 [*] Convert `MyType` from `TypedDict` functional to class syntax | help: Convert `MyType` to class syntax | -42 | # Empty dict call - - MyType = TypedDict("MyType", dict()) 43 + class MyType(TypedDict): 44 + pass -45 | | UP013 [*] Convert `X` from `TypedDict` functional to class syntax @@ -234,12 +198,7 @@ UP013 [*] Convert `X` from `TypedDict` functional to class syntax | help: Convert `X` to class syntax | -45 | # Unsafe fix if comments are present - - X = TypedDict("X", { - - "some_config": int, # important - - }) 46 + class X(TypedDict): 47 + some_config: int -48 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP014.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP014.py.snap index 7bf610bcde8b8..900395ce7c28d 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP014.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP014.py.snap @@ -12,12 +12,9 @@ UP014 [*] Convert `MyType` from `NamedTuple` functional to class syntax | help: Convert `MyType` to class syntax | -4 | # with complex annotations - - MyType = NamedTuple("MyType", [("a", int), ("b", tuple[str, ...])]) 5 + class MyType(NamedTuple): 6 + a: int 7 + b: tuple[str, ...] -8 | | UP014 [*] Convert `MyType` from `NamedTuple` functional to class syntax @@ -31,12 +28,9 @@ UP014 [*] Convert `MyType` from `NamedTuple` functional to class syntax | help: Convert `MyType` to class syntax | -7 | # with namespace - - MyType = typing.NamedTuple("MyType", [("a", int), ("b", str)]) -8 + class MyType(typing.NamedTuple): -9 + a: int + 8 + class MyType(typing.NamedTuple): + 9 + a: int 10 + b: str -11 | | UP014 [*] Convert `MyType` from `NamedTuple` functional to class syntax @@ -50,11 +44,8 @@ UP014 [*] Convert `MyType` from `NamedTuple` functional to class syntax | help: Convert `MyType` to class syntax | -13 | # no fields - - MyType = typing.NamedTuple("MyType") 14 + class MyType(typing.NamedTuple): 15 + pass -16 | | UP014 [*] Convert `MyType` from `NamedTuple` functional to class syntax @@ -68,11 +59,8 @@ UP014 [*] Convert `MyType` from `NamedTuple` functional to class syntax | help: Convert `MyType` to class syntax | -16 | # empty fields - - MyType = typing.NamedTuple("MyType", []) 17 + class MyType(typing.NamedTuple): 18 + pass -19 | | UP014 [*] Convert `MyType` from `NamedTuple` functional to class syntax @@ -86,12 +74,9 @@ UP014 [*] Convert `MyType` from `NamedTuple` functional to class syntax | help: Convert `MyType` to class syntax | -19 | # keywords - - MyType = typing.NamedTuple("MyType", a=int, b=tuple[str, ...]) 20 + class MyType(typing.NamedTuple): 21 + a: int 22 + b: tuple[str, ...] -23 | | UP014 [*] Convert `X` from `NamedTuple` functional to class syntax @@ -104,12 +89,7 @@ UP014 [*] Convert `X` from `NamedTuple` functional to class syntax | |__^ help: Convert `X` to class syntax | -35 | # Unsafe fix if comments are present - - X = NamedTuple("X", [ - - ("some_config", int), # important - - ]) 36 + class X(NamedTuple): 37 + some_config: int -38 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP015.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP015.py.snap index 0d00ef80e62da..2cfe3ae5a14c2 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP015.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP015.py.snap @@ -11,9 +11,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | - - open("foo", "U") +1 - open("foo", "U") 1 + open("foo") -2 | open("foo", "Ur") | UP015 [*] Unnecessary mode argument @@ -27,10 +26,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -1 | open("foo", "U") - - open("foo", "Ur") +2 - open("foo", "Ur") 2 + open("foo") -3 | open("foo", "Ub") | UP015 [*] Unnecessary modes, use `rb` @@ -45,10 +42,8 @@ UP015 [*] Unnecessary modes, use `rb` | help: Replace with `rb` | -2 | open("foo", "Ur") - - open("foo", "Ub") +3 - open("foo", "Ub") 3 + open("foo", "rb") -4 | open("foo", "rUb") | UP015 [*] Unnecessary modes, use `rb` @@ -63,10 +58,8 @@ UP015 [*] Unnecessary modes, use `rb` | help: Replace with `rb` | -3 | open("foo", "Ub") - - open("foo", "rUb") +4 - open("foo", "rUb") 4 + open("foo", "rb") -5 | open("foo", "r") | UP015 [*] Unnecessary mode argument @@ -81,10 +74,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -4 | open("foo", "rUb") - - open("foo", "r") +5 - open("foo", "r") 5 + open("foo") -6 | open("foo", "rt") | UP015 [*] Unnecessary mode argument @@ -99,10 +90,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -5 | open("foo", "r") - - open("foo", "rt") +6 - open("foo", "rt") 6 + open("foo") -7 | open("f", "r", encoding="UTF-8") | UP015 [*] Unnecessary mode argument @@ -117,10 +106,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -6 | open("foo", "rt") - - open("f", "r", encoding="UTF-8") +7 - open("f", "r", encoding="UTF-8") 7 + open("f", encoding="UTF-8") -8 | open("f", "wt") | UP015 [*] Unnecessary modes, use `w` @@ -134,10 +121,8 @@ UP015 [*] Unnecessary modes, use `w` | help: Replace with `w` | -7 | open("f", "r", encoding="UTF-8") - - open("f", "wt") +8 - open("f", "wt") 8 + open("f", "w") -9 | open("f", "tw") | UP015 [*] Unnecessary modes, use `w` @@ -151,12 +136,10 @@ UP015 [*] Unnecessary modes, use `w` 11 | with open("foo", "U") as f: | help: Replace with `w` - | -8 | open("f", "wt") - - open("f", "tw") -9 + open("f", "w") -10 | - | + | +9 - open("f", "tw") +9 + open("f", "w") + | UP015 [*] Unnecessary mode argument --> UP015.py:11:18 @@ -170,10 +153,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -10 | - - with open("foo", "U") as f: +11 - with open("foo", "U") as f: 11 + with open("foo") as f: -12 | pass | UP015 [*] Unnecessary mode argument @@ -188,10 +169,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -12 | pass - - with open("foo", "Ur") as f: +13 - with open("foo", "Ur") as f: 13 + with open("foo") as f: -14 | pass | UP015 [*] Unnecessary modes, use `rb` @@ -206,10 +185,8 @@ UP015 [*] Unnecessary modes, use `rb` | help: Replace with `rb` | -14 | pass - - with open("foo", "Ub") as f: +15 - with open("foo", "Ub") as f: 15 + with open("foo", "rb") as f: -16 | pass | UP015 [*] Unnecessary modes, use `rb` @@ -224,10 +201,8 @@ UP015 [*] Unnecessary modes, use `rb` | help: Replace with `rb` | -16 | pass - - with open("foo", "rUb") as f: +17 - with open("foo", "rUb") as f: 17 + with open("foo", "rb") as f: -18 | pass | UP015 [*] Unnecessary mode argument @@ -242,10 +217,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -18 | pass - - with open("foo", "r") as f: +19 - with open("foo", "r") as f: 19 + with open("foo") as f: -20 | pass | UP015 [*] Unnecessary mode argument @@ -260,10 +233,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -20 | pass - - with open("foo", "rt") as f: +21 - with open("foo", "rt") as f: 21 + with open("foo") as f: -22 | pass | UP015 [*] Unnecessary mode argument @@ -278,10 +249,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -22 | pass - - with open("foo", "r", encoding="UTF-8") as f: +23 - with open("foo", "r", encoding="UTF-8") as f: 23 + with open("foo", encoding="UTF-8") as f: -24 | pass | UP015 [*] Unnecessary modes, use `w` @@ -295,10 +264,8 @@ UP015 [*] Unnecessary modes, use `w` | help: Replace with `w` | -24 | pass - - with open("foo", "wt") as f: +25 - with open("foo", "wt") as f: 25 + with open("foo", "w") as f: -26 | pass | UP015 [*] Unnecessary mode argument @@ -312,10 +279,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -27 | - - open(f("a", "b", "c"), "U") +28 - open(f("a", "b", "c"), "U") 28 + open(f("a", "b", "c")) -29 | open(f("a", "b", "c"), "Ub") | UP015 [*] Unnecessary modes, use `rb` @@ -329,10 +294,8 @@ UP015 [*] Unnecessary modes, use `rb` | help: Replace with `rb` | -28 | open(f("a", "b", "c"), "U") - - open(f("a", "b", "c"), "Ub") +29 - open(f("a", "b", "c"), "Ub") 29 + open(f("a", "b", "c"), "rb") -30 | | UP015 [*] Unnecessary mode argument @@ -347,10 +310,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -30 | - - with open(f("a", "b", "c"), "U") as f: +31 - with open(f("a", "b", "c"), "U") as f: 31 + with open(f("a", "b", "c")) as f: -32 | pass | UP015 [*] Unnecessary modes, use `rb` @@ -364,10 +325,8 @@ UP015 [*] Unnecessary modes, use `rb` | help: Replace with `rb` | -32 | pass - - with open(f("a", "b", "c"), "Ub") as f: +33 - with open(f("a", "b", "c"), "Ub") as f: 33 + with open(f("a", "b", "c"), "rb") as f: -34 | pass | UP015 [*] Unnecessary mode argument @@ -382,10 +341,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -35 | - - with open("foo", "U") as fa, open("bar", "U") as fb: +36 - with open("foo", "U") as fa, open("bar", "U") as fb: 36 + with open("foo") as fa, open("bar", "U") as fb: -37 | pass | UP015 [*] Unnecessary mode argument @@ -400,10 +357,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -35 | - - with open("foo", "U") as fa, open("bar", "U") as fb: +36 - with open("foo", "U") as fa, open("bar", "U") as fb: 36 + with open("foo", "U") as fa, open("bar") as fb: -37 | pass | UP015 [*] Unnecessary modes, use `rb` @@ -417,10 +372,8 @@ UP015 [*] Unnecessary modes, use `rb` | help: Replace with `rb` | -37 | pass - - with open("foo", "Ub") as fa, open("bar", "Ub") as fb: +38 - with open("foo", "Ub") as fa, open("bar", "Ub") as fb: 38 + with open("foo", "rb") as fa, open("bar", "Ub") as fb: -39 | pass | UP015 [*] Unnecessary modes, use `rb` @@ -434,10 +387,8 @@ UP015 [*] Unnecessary modes, use `rb` | help: Replace with `rb` | -37 | pass - - with open("foo", "Ub") as fa, open("bar", "Ub") as fb: +38 - with open("foo", "Ub") as fa, open("bar", "Ub") as fb: 38 + with open("foo", "Ub") as fa, open("bar", "rb") as fb: -39 | pass | UP015 [*] Unnecessary mode argument @@ -452,10 +403,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -40 | - - open("foo", mode="U") +41 - open("foo", mode="U") 41 + open("foo") -42 | open(name="foo", mode="U") | UP015 [*] Unnecessary mode argument @@ -468,10 +417,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -41 | open("foo", mode="U") - - open(name="foo", mode="U") +42 - open(name="foo", mode="U") 42 + open(name="foo") -43 | open(mode="U", name="foo") | UP015 [*] Unnecessary mode argument @@ -486,10 +433,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -42 | open(name="foo", mode="U") - - open(mode="U", name="foo") +43 - open(mode="U", name="foo") 43 + open(name="foo") -44 | | UP015 [*] Unnecessary mode argument @@ -504,10 +449,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -44 | - - with open("foo", mode="U") as f: +45 - with open("foo", mode="U") as f: 45 + with open("foo") as f: -46 | pass | UP015 [*] Unnecessary mode argument @@ -522,10 +465,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -46 | pass - - with open(name="foo", mode="U") as f: +47 - with open(name="foo", mode="U") as f: 47 + with open(name="foo") as f: -48 | pass | UP015 [*] Unnecessary mode argument @@ -539,10 +480,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -48 | pass - - with open(mode="U", name="foo") as f: +49 - with open(mode="U", name="foo") as f: 49 + with open(name="foo") as f: -50 | pass | UP015 [*] Unnecessary modes, use `rb` @@ -557,10 +496,8 @@ UP015 [*] Unnecessary modes, use `rb` | help: Replace with `rb` | -51 | - - open("foo", mode="Ub") +52 - open("foo", mode="Ub") 52 + open("foo", mode="rb") -53 | open(name="foo", mode="Ub") | UP015 [*] Unnecessary modes, use `rb` @@ -573,10 +510,8 @@ UP015 [*] Unnecessary modes, use `rb` | help: Replace with `rb` | -52 | open("foo", mode="Ub") - - open(name="foo", mode="Ub") +53 - open(name="foo", mode="Ub") 53 + open(name="foo", mode="rb") -54 | open(mode="Ub", name="foo") | UP015 [*] Unnecessary modes, use `rb` @@ -591,10 +526,8 @@ UP015 [*] Unnecessary modes, use `rb` | help: Replace with `rb` | -53 | open(name="foo", mode="Ub") - - open(mode="Ub", name="foo") +54 - open(mode="Ub", name="foo") 54 + open(mode="rb", name="foo") -55 | | UP015 [*] Unnecessary modes, use `rb` @@ -609,10 +542,8 @@ UP015 [*] Unnecessary modes, use `rb` | help: Replace with `rb` | -55 | - - with open("foo", mode="Ub") as f: +56 - with open("foo", mode="Ub") as f: 56 + with open("foo", mode="rb") as f: -57 | pass | UP015 [*] Unnecessary modes, use `rb` @@ -627,10 +558,8 @@ UP015 [*] Unnecessary modes, use `rb` | help: Replace with `rb` | -57 | pass - - with open(name="foo", mode="Ub") as f: +58 - with open(name="foo", mode="Ub") as f: 58 + with open(name="foo", mode="rb") as f: -59 | pass | UP015 [*] Unnecessary modes, use `rb` @@ -644,10 +573,8 @@ UP015 [*] Unnecessary modes, use `rb` | help: Replace with `rb` | -59 | pass - - with open(mode="Ub", name="foo") as f: +60 - with open(mode="Ub", name="foo") as f: 60 + with open(mode="rb", name="foo") as f: -61 | pass | UP015 [*] Unnecessary mode argument @@ -662,10 +589,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -62 | - - open(file="foo", mode='U', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) +63 - open(file="foo", mode='U', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) 63 + open(file="foo", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) -64 | open(file="foo", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None, mode='U') | UP015 [*] Unnecessary mode argument @@ -679,10 +604,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -63 | open(file="foo", mode='U', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) - - open(file="foo", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None, mode='U') +64 - open(file="foo", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None, mode='U') 64 + open(file="foo", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) -65 | open(file="foo", buffering=-1, encoding=None, errors=None, mode='U', newline=None, closefd=True, opener=None) | UP015 [*] Unnecessary mode argument @@ -696,10 +619,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -64 | open(file="foo", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None, mode='U') - - open(file="foo", buffering=-1, encoding=None, errors=None, mode='U', newline=None, closefd=True, opener=None) +65 - open(file="foo", buffering=-1, encoding=None, errors=None, mode='U', newline=None, closefd=True, opener=None) 65 + open(file="foo", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) -66 | open(mode='U', file="foo", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) | UP015 [*] Unnecessary mode argument @@ -714,10 +635,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -65 | open(file="foo", buffering=-1, encoding=None, errors=None, mode='U', newline=None, closefd=True, opener=None) - - open(mode='U', file="foo", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) +66 - open(mode='U', file="foo", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) 66 + open(file="foo", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) -67 | | UP015 [*] Unnecessary modes, use `rb` @@ -732,10 +651,8 @@ UP015 [*] Unnecessary modes, use `rb` | help: Replace with `rb` | -67 | - - open(file="foo", mode='Ub', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) +68 - open(file="foo", mode='Ub', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) 68 + open(file="foo", mode="rb", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) -69 | open(file="foo", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None, mode='Ub') | UP015 [*] Unnecessary modes, use `rb` @@ -749,10 +666,8 @@ UP015 [*] Unnecessary modes, use `rb` | help: Replace with `rb` | -68 | open(file="foo", mode='Ub', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) - - open(file="foo", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None, mode='Ub') +69 - open(file="foo", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None, mode='Ub') 69 + open(file="foo", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None, mode="rb") -70 | open(file="foo", buffering=-1, encoding=None, errors=None, mode='Ub', newline=None, closefd=True, opener=None) | UP015 [*] Unnecessary modes, use `rb` @@ -766,10 +681,8 @@ UP015 [*] Unnecessary modes, use `rb` | help: Replace with `rb` | -69 | open(file="foo", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None, mode='Ub') - - open(file="foo", buffering=-1, encoding=None, errors=None, mode='Ub', newline=None, closefd=True, opener=None) +70 - open(file="foo", buffering=-1, encoding=None, errors=None, mode='Ub', newline=None, closefd=True, opener=None) 70 + open(file="foo", buffering=-1, encoding=None, errors=None, mode="rb", newline=None, closefd=True, opener=None) -71 | open(mode='Ub', file="foo", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) | UP015 [*] Unnecessary modes, use `rb` @@ -784,10 +697,8 @@ UP015 [*] Unnecessary modes, use `rb` | help: Replace with `rb` | -70 | open(file="foo", buffering=-1, encoding=None, errors=None, mode='Ub', newline=None, closefd=True, opener=None) - - open(mode='Ub', file="foo", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) +71 - open(mode='Ub', file="foo", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) 71 + open(mode="rb", file="foo", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) -72 | | UP015 [*] Unnecessary mode argument @@ -802,10 +713,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -74 | - - aiofiles.open("foo", "U") +75 - aiofiles.open("foo", "U") 75 + aiofiles.open("foo") -76 | aiofiles.open("foo", "r") | UP015 [*] Unnecessary mode argument @@ -818,10 +727,8 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -75 | aiofiles.open("foo", "U") - - aiofiles.open("foo", "r") +76 - aiofiles.open("foo", "r") 76 + aiofiles.open("foo") -77 | aiofiles.open("foo", mode="r") | UP015 [*] Unnecessary mode argument @@ -836,8 +743,6 @@ UP015 [*] Unnecessary mode argument | help: Remove mode argument | -76 | aiofiles.open("foo", "r") - - aiofiles.open("foo", mode="r") +77 - aiofiles.open("foo", mode="r") 77 + aiofiles.open("foo") -78 | | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP015_1.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP015_1.py.snap index 76b4fe2b95c7a..2194e3e95741f 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP015_1.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP015_1.py.snap @@ -10,8 +10,6 @@ UP015 [*] Unnecessary mode argument | ^^^ help: Remove mode argument | -2 | # Refer: https://github.com/astral-sh/ruff/issues/11736 - - x: 'open("foo", "r")' +3 - x: 'open("foo", "r")' 3 + x: 'open("foo")' -4 | | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP018.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP018.py.snap index a331620e672b7..91f3f60f604a2 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP018.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP018.py.snap @@ -14,10 +14,8 @@ UP018 [*] Unnecessary `str` call (rewrite as a literal) | help: Replace with string literal | -7 | str("foo", encoding="UTF-8") - - str("foo" 8 + ("foo" -9 | "bar") +9 + "bar") | UP018 [*] Unnecessary `bytes` call (rewrite as a literal) @@ -33,10 +31,8 @@ UP018 [*] Unnecessary `bytes` call (rewrite as a literal) | help: Replace with bytes literal | -14 | bytes("foo", **a) - - bytes(b"foo" 15 + (b"foo" -16 | b"bar") +16 + b"bar") | UP018 [*] Unnecessary `int` call (rewrite as a literal) @@ -51,10 +47,8 @@ UP018 [*] Unnecessary `int` call (rewrite as a literal) | help: Replace with integer literal | -33 | bool(1.0) - - int().denominator +34 - int().denominator 34 + (0).denominator -35 | | UP018 [*] Unnecessary `str` call (rewrite as a literal) @@ -68,10 +62,8 @@ UP018 [*] Unnecessary `str` call (rewrite as a literal) | help: Replace with string literal | -36 | # These become literals - - str() +37 - str() 37 + "" -38 | str("foo") | UP018 [*] Unnecessary `str` call (rewrite as a literal) @@ -86,10 +78,8 @@ UP018 [*] Unnecessary `str` call (rewrite as a literal) | help: Replace with string literal | -37 | str() - - str("foo") +38 - str("foo") 38 + "foo" -39 | str(""" | UP018 [*] Unnecessary `str` call (rewrite as a literal) @@ -105,12 +95,8 @@ UP018 [*] Unnecessary `str` call (rewrite as a literal) | help: Replace with string literal | -38 | str("foo") - - str(""" - - foo""") 39 + """ 40 + foo""" -41 | bytes() | UP018 [*] Unnecessary `bytes` call (rewrite as a literal) @@ -125,10 +111,8 @@ UP018 [*] Unnecessary `bytes` call (rewrite as a literal) | help: Replace with bytes literal | -40 | foo""") - - bytes() +41 - bytes() 41 + b"" -42 | bytes(b"foo") | UP018 [*] Unnecessary `bytes` call (rewrite as a literal) @@ -143,10 +127,8 @@ UP018 [*] Unnecessary `bytes` call (rewrite as a literal) | help: Replace with bytes literal | -41 | bytes() - - bytes(b"foo") +42 - bytes(b"foo") 42 + b"foo" -43 | bytes(b""" | UP018 [*] Unnecessary `bytes` call (rewrite as a literal) @@ -162,12 +144,8 @@ UP018 [*] Unnecessary `bytes` call (rewrite as a literal) | help: Replace with bytes literal | -42 | bytes(b"foo") - - bytes(b""" - - foo""") 43 + b""" 44 + foo""" -45 | f"{str()}" | UP018 [*] Unnecessary `str` call (rewrite as a literal) @@ -182,10 +160,8 @@ UP018 [*] Unnecessary `str` call (rewrite as a literal) | help: Replace with string literal | -44 | foo""") - - f"{str()}" +45 - f"{str()}" 45 + f"{''}" -46 | int() | UP018 [*] Unnecessary `int` call (rewrite as a literal) @@ -200,10 +176,8 @@ UP018 [*] Unnecessary `int` call (rewrite as a literal) | help: Replace with integer literal | -45 | f"{str()}" - - int() +46 - int() 46 + 0 -47 | int(1) | UP018 [*] Unnecessary `int` call (rewrite as a literal) @@ -218,10 +192,8 @@ UP018 [*] Unnecessary `int` call (rewrite as a literal) | help: Replace with integer literal | -46 | int() - - int(1) +47 - int(1) 47 + 1 -48 | float() | UP018 [*] Unnecessary `float` call (rewrite as a literal) @@ -236,10 +208,8 @@ UP018 [*] Unnecessary `float` call (rewrite as a literal) | help: Replace with float literal | -47 | int(1) - - float() +48 - float() 48 + 0.0 -49 | float(1.0) | UP018 [*] Unnecessary `float` call (rewrite as a literal) @@ -254,10 +224,8 @@ UP018 [*] Unnecessary `float` call (rewrite as a literal) | help: Replace with float literal | -48 | float() - - float(1.0) +49 - float(1.0) 49 + 1.0 -50 | bool() | UP018 [*] Unnecessary `bool` call (rewrite as a literal) @@ -272,10 +240,8 @@ UP018 [*] Unnecessary `bool` call (rewrite as a literal) | help: Replace with boolean literal | -49 | float(1.0) - - bool() +50 - bool() 50 + False -51 | bool(True) | UP018 [*] Unnecessary `bool` call (rewrite as a literal) @@ -289,10 +255,8 @@ UP018 [*] Unnecessary `bool` call (rewrite as a literal) | help: Replace with boolean literal | -50 | bool() - - bool(True) +51 - bool(True) 51 + True -52 | bool(False) | UP018 [*] Unnecessary `bool` call (rewrite as a literal) @@ -307,10 +271,8 @@ UP018 [*] Unnecessary `bool` call (rewrite as a literal) | help: Replace with boolean literal | -51 | bool(True) - - bool(False) +52 - bool(False) 52 + False -53 | | UP018 [*] Unnecessary `int` call (rewrite as a literal) @@ -324,10 +286,8 @@ UP018 [*] Unnecessary `int` call (rewrite as a literal) | help: Replace with integer literal | -54 | # These become a literal but retain parentheses - - int(1).denominator +55 - int(1).denominator 55 + (1).denominator -56 | | UP018 [*] Unnecessary `int` call (rewrite as a literal) @@ -341,10 +301,8 @@ UP018 [*] Unnecessary `int` call (rewrite as a literal) | help: Replace with integer literal | -57 | # These too are literals in spirit - - int(+1) +58 - int(+1) 58 + +1 -59 | int(-1) | UP018 [*] Unnecessary `int` call (rewrite as a literal) @@ -359,10 +317,8 @@ UP018 [*] Unnecessary `int` call (rewrite as a literal) | help: Replace with integer literal | -58 | int(+1) - - int(-1) +59 - int(-1) 59 + -1 -60 | float(+1.0) | UP018 [*] Unnecessary `float` call (rewrite as a literal) @@ -376,10 +332,8 @@ UP018 [*] Unnecessary `float` call (rewrite as a literal) | help: Replace with float literal | -59 | int(-1) - - float(+1.0) +60 - float(+1.0) 60 + +1.0 -61 | float(-1.0) | UP018 [*] Unnecessary `float` call (rewrite as a literal) @@ -391,10 +345,8 @@ UP018 [*] Unnecessary `float` call (rewrite as a literal) | ^^^^^^^^^^^ help: Replace with float literal | -60 | float(+1.0) - - float(-1.0) +61 - float(-1.0) 61 + -1.0 -62 | | UP018 [*] Unnecessary `int` call (rewrite as a literal) @@ -407,10 +359,8 @@ UP018 [*] Unnecessary `int` call (rewrite as a literal) | help: Replace with integer literal | -64 | # https://github.com/astral-sh/ruff/issues/15859 - - int(-1) ** 0 # (-1) ** 0 +65 - int(-1) ** 0 # (-1) ** 0 65 + (-1) ** 0 # (-1) ** 0 -66 | 2 ** int(-1) # 2 ** -1 | UP018 [*] Unnecessary `int` call (rewrite as a literal) @@ -425,10 +375,8 @@ UP018 [*] Unnecessary `int` call (rewrite as a literal) | help: Replace with integer literal | -65 | int(-1) ** 0 # (-1) ** 0 - - 2 ** int(-1) # 2 ** -1 +66 - 2 ** int(-1) # 2 ** -1 66 + 2 ** (-1) # 2 ** -1 -67 | | UP018 [*] Unnecessary `int` call (rewrite as a literal) @@ -442,10 +390,8 @@ UP018 [*] Unnecessary `int` call (rewrite as a literal) | help: Replace with integer literal | -67 | - - int(-1)[0] # (-1)[0] +68 - int(-1)[0] # (-1)[0] 68 + (-1)[0] # (-1)[0] -69 | 2[int(-1)] # 2[-1] | UP018 [*] Unnecessary `int` call (rewrite as a literal) @@ -459,10 +405,8 @@ UP018 [*] Unnecessary `int` call (rewrite as a literal) | help: Replace with integer literal | -68 | int(-1)[0] # (-1)[0] - - 2[int(-1)] # 2[-1] +69 - 2[int(-1)] # 2[-1] 69 + 2[(-1)] # 2[-1] -70 | | UP018 [*] Unnecessary `int` call (rewrite as a literal) @@ -476,10 +420,8 @@ UP018 [*] Unnecessary `int` call (rewrite as a literal) | help: Replace with integer literal | -70 | - - int(-1)(0) # (-1)(0) +71 - int(-1)(0) # (-1)(0) 71 + (-1)(0) # (-1)(0) -72 | 2(int(-1)) # 2(-1) | UP018 [*] Unnecessary `int` call (rewrite as a literal) @@ -493,10 +435,8 @@ UP018 [*] Unnecessary `int` call (rewrite as a literal) | help: Replace with integer literal | -71 | int(-1)(0) # (-1)(0) - - 2(int(-1)) # 2(-1) +72 - 2(int(-1)) # 2(-1) 72 + 2((-1)) # 2(-1) -73 | | UP018 [*] Unnecessary `float` call (rewrite as a literal) @@ -511,10 +451,8 @@ UP018 [*] Unnecessary `float` call (rewrite as a literal) | help: Replace with float literal | -73 | - - float(-1.0).foo # (-1.0).foo +74 - float(-1.0).foo # (-1.0).foo 74 + (-1.0).foo # (-1.0).foo -75 | | UP018 [*] Unnecessary `int` call (rewrite as a literal) @@ -526,10 +464,8 @@ UP018 [*] Unnecessary `int` call (rewrite as a literal) | ^^^^^^^ help: Replace with integer literal | -75 | - - await int(-1) # await (-1) +76 - await int(-1) # await (-1) 76 + await (-1) # await (-1) -77 | | UP018 [*] Unnecessary `int` call (rewrite as a literal) @@ -541,10 +477,8 @@ UP018 [*] Unnecessary `int` call (rewrite as a literal) | help: Replace with integer literal | -78 | - - int(+1) ** 0 +79 - int(+1) ** 0 79 + (+1) ** 0 -80 | float(+1.0)() | UP018 [*] Unnecessary `float` call (rewrite as a literal) @@ -555,10 +489,8 @@ UP018 [*] Unnecessary `float` call (rewrite as a literal) | ^^^^^^^^^^^ help: Replace with float literal | -79 | int(+1) ** 0 - - float(+1.0)() +80 - float(+1.0)() 80 + (+1.0)() -81 | | UP018 [*] Unnecessary `str` call (rewrite as a literal) @@ -574,14 +506,8 @@ UP018 [*] Unnecessary `str` call (rewrite as a literal) | help: Replace with string literal | -82 | - - str( - - '''Lorem - - ipsum''' # Comment - - ).foo 83 + '''Lorem -84 + ipsum'''.foo -85 | +84 ~ ipsum'''.foo | note: This is an unsafe fix and may change runtime behavior @@ -596,10 +522,8 @@ UP018 [*] Unnecessary `bool` call (rewrite as a literal) | help: Replace with boolean literal | -88 | # https://github.com/astral-sh/ruff/issues/17606 - - bool(True)and None +89 - bool(True)and None 89 + True and None -90 | int(1)and None | UP018 [*] Unnecessary `int` call (rewrite as a literal) @@ -614,10 +538,8 @@ UP018 [*] Unnecessary `int` call (rewrite as a literal) | help: Replace with integer literal | -89 | bool(True)and None - - int(1)and None +90 - int(1)and None 90 + 1 and None -91 | float(1.)and None | UP018 [*] Unnecessary `float` call (rewrite as a literal) @@ -631,10 +553,8 @@ UP018 [*] Unnecessary `float` call (rewrite as a literal) | help: Replace with float literal | -90 | int(1)and None - - float(1.)and None +91 - float(1.)and None 91 + 1. and None -92 | bool(True)and() | UP018 [*] Unnecessary `bool` call (rewrite as a literal) @@ -646,10 +566,8 @@ UP018 [*] Unnecessary `bool` call (rewrite as a literal) | ^^^^^^^^^^ help: Replace with boolean literal | -91 | float(1.)and None - - bool(True)and() +92 - bool(True)and() 92 + True and() -93 | | UP018 [*] Unnecessary `str` call (rewrite as a literal) @@ -662,12 +580,10 @@ UP018 [*] Unnecessary `str` call (rewrite as a literal) 101 | str( | help: Replace with string literal - | -98 | # UP018 - Extended detections - - str("A" "B") -99 + "A" "B" -100 | str("A" "B").lower() - | + | +99 - str("A" "B") +99 + "A" "B" + | UP018 [*] Unnecessary `str` call (rewrite as a literal) --> UP018.py:100:1 @@ -681,10 +597,8 @@ UP018 [*] Unnecessary `str` call (rewrite as a literal) | help: Replace with string literal | -99 | str("A" "B") - - str("A" "B").lower() +100 - str("A" "B").lower() 100 + "A" "B".lower() -101 | str( | UP018 [*] Unnecessary `str` call (rewrite as a literal) @@ -702,14 +616,8 @@ UP018 [*] Unnecessary `str` call (rewrite as a literal) | help: Replace with string literal | -100 | str("A" "B").lower() - - str( - - "A" - - "B" - - ) 101 + ("A" 102 + "B") -103 | str(object="!") | UP018 [*] Unnecessary `str` call (rewrite as a literal) @@ -724,10 +632,8 @@ UP018 [*] Unnecessary `str` call (rewrite as a literal) | help: Replace with string literal | -104 | ) - - str(object="!") +105 - str(object="!") 105 + "!" -106 | complex(1j) | UP018 [*] Unnecessary `complex` call (rewrite as a literal) @@ -742,10 +648,8 @@ UP018 [*] Unnecessary `complex` call (rewrite as a literal) | help: Replace with complex literal | -105 | str(object="!") - - complex(1j) +106 - complex(1j) 106 + 1j -107 | complex(real=1j) | UP018 [*] Unnecessary `complex` call (rewrite as a literal) @@ -760,10 +664,8 @@ UP018 [*] Unnecessary `complex` call (rewrite as a literal) | help: Replace with complex literal | -106 | complex(1j) - - complex(real=1j) +107 - complex(real=1j) 107 + 1j -108 | complex() | UP018 [*] Unnecessary `complex` call (rewrite as a literal) @@ -778,10 +680,8 @@ UP018 [*] Unnecessary `complex` call (rewrite as a literal) | help: Replace with complex literal | -107 | complex(real=1j) - - complex() +108 - complex() 108 + 0j -109 | complex(0j) | UP018 [*] Unnecessary `complex` call (rewrite as a literal) @@ -796,10 +696,8 @@ UP018 [*] Unnecessary `complex` call (rewrite as a literal) | help: Replace with complex literal | -108 | complex() - - complex(0j) +109 - complex(0j) 109 + 0j -110 | complex(real=0j) | UP018 [*] Unnecessary `complex` call (rewrite as a literal) @@ -814,10 +712,8 @@ UP018 [*] Unnecessary `complex` call (rewrite as a literal) | help: Replace with complex literal | -109 | complex(0j) - - complex(real=0j) +110 - complex(real=0j) 110 + 0j -111 | (complex(0j)).real | UP018 [*] Unnecessary `complex` call (rewrite as a literal) @@ -832,10 +728,8 @@ UP018 [*] Unnecessary `complex` call (rewrite as a literal) | help: Replace with complex literal | -110 | complex(real=0j) - - (complex(0j)).real +111 - (complex(0j)).real 111 + (0j).real -112 | complex(1j).real | UP018 [*] Unnecessary `complex` call (rewrite as a literal) @@ -849,10 +743,8 @@ UP018 [*] Unnecessary `complex` call (rewrite as a literal) | help: Replace with complex literal | -111 | (complex(0j)).real - - complex(1j).real +112 - complex(1j).real 112 + 1j.real -113 | complex(real=1j).real | UP018 [*] Unnecessary `complex` call (rewrite as a literal) @@ -864,7 +756,6 @@ UP018 [*] Unnecessary `complex` call (rewrite as a literal) | ^^^^^^^^^^^^^^^^ help: Replace with complex literal | -112 | complex(1j).real - - complex(real=1j).real +113 - complex(real=1j).real 113 + 1j.real | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP018_CR.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP018_CR.py.snap index b16bc7a8bf7cf..840fe4af00d79 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP018_CR.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP018_CR.py.snap @@ -13,7 +13,9 @@ UP018 [*] Unnecessary `int` call (rewrite as a literal) | help: Replace with integer literal | -1 | # Keep parenthesis around preserved CR - int(- 2 + (- 3 | 1) | +1 - # Keep parenthesis around preserved CR␍int(-␍ 1)␍int(+␍ 1) +1 + # Keep parenthesis around preserved CR␍(-␍ 1)␍int(+␍ 1) + | UP018 [*] Unnecessary `int` call (rewrite as a literal) --> UP018_CR.py:4:1 @@ -25,5 +27,6 @@ UP018 [*] Unnecessary `int` call (rewrite as a literal) | |______^ help: Replace with integer literal | -3 | 1) - int(+ 4 + (+ 5 | 1) +1 - # Keep parenthesis around preserved CR␍int(-␍ 1)␍int(+␍ 1) +1 + # Keep parenthesis around preserved CR␍int(-␍ 1)␍(+␍ 1) | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP018_LF.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP018_LF.py.snap index 3f367e591faeb..650b68509950b 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP018_LF.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP018_LF.py.snap @@ -14,10 +14,8 @@ UP018 [*] Unnecessary `int` call (rewrite as a literal) | help: Replace with integer literal | -2 | - - int(- 3 + (- -4 | 1) +4 + 1) | UP018 [*] Unnecessary `int` call (rewrite as a literal) @@ -30,8 +28,6 @@ UP018 [*] Unnecessary `int` call (rewrite as a literal) | |______^ help: Replace with integer literal | -5 | - - int(+ 6 + (+ -7 | 1) +7 + 1) | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP019.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP019.py.snap index 142f093d4e1fd..ebf6df72f3055 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP019.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP019.py.snap @@ -10,10 +10,8 @@ UP019 [*] `typing.Text` is deprecated, use `str` | help: Replace with `str` | -6 | - - def print_word(word: Text) -> None: +7 - def print_word(word: Text) -> None: 7 + def print_word(word: str) -> None: -8 | print(word) | UP019 [*] `typing.Text` is deprecated, use `str` @@ -25,10 +23,8 @@ UP019 [*] `typing.Text` is deprecated, use `str` | help: Replace with `str` | -10 | - - def print_second_word(word: typing.Text) -> None: +11 - def print_second_word(word: typing.Text) -> None: 11 + def print_second_word(word: str) -> None: -12 | print(word) | UP019 [*] `typing.Text` is deprecated, use `str` @@ -40,10 +36,8 @@ UP019 [*] `typing.Text` is deprecated, use `str` | help: Replace with `str` | -14 | - - def print_third_word(word: Hello.Text) -> None: +15 - def print_third_word(word: Hello.Text) -> None: 15 + def print_third_word(word: str) -> None: -16 | print(word) | UP019 [*] `typing.Text` is deprecated, use `str` @@ -55,10 +49,8 @@ UP019 [*] `typing.Text` is deprecated, use `str` | help: Replace with `str` | -18 | - - def print_fourth_word(word: Goodbye) -> None: +19 - def print_fourth_word(word: Goodbye) -> None: 19 + def print_fourth_word(word: str) -> None: -20 | print(word) | UP019 [*] `typing_extensions.Text` is deprecated, use `str` @@ -70,10 +62,8 @@ UP019 [*] `typing_extensions.Text` is deprecated, use `str` | help: Replace with `str` | -27 | - - def print_fifth_word(word: typing_extensions.Text) -> None: +28 - def print_fifth_word(word: typing_extensions.Text) -> None: 28 + def print_fifth_word(word: str) -> None: -29 | print(word) | UP019 [*] `typing_extensions.Text` is deprecated, use `str` @@ -85,10 +75,8 @@ UP019 [*] `typing_extensions.Text` is deprecated, use `str` | help: Replace with `str` | -31 | - - def print_sixth_word(word: TypingExt.Text) -> None: +32 - def print_sixth_word(word: TypingExt.Text) -> None: 32 + def print_sixth_word(word: str) -> None: -33 | print(word) | UP019 [*] `typing_extensions.Text` is deprecated, use `str` @@ -100,8 +88,6 @@ UP019 [*] `typing_extensions.Text` is deprecated, use `str` | help: Replace with `str` | -35 | - - def print_seventh_word(word: TextAlias) -> None: +36 - def print_seventh_word(word: TextAlias) -> None: 36 + def print_seventh_word(word: str) -> None: -37 | print(word) | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP020.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP020.py.snap index 74af353bd20ba..0d5c0a4e7809f 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP020.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP020.py.snap @@ -12,10 +12,8 @@ UP020 [*] Use builtin `open` | help: Replace with builtin `open` | -2 | - - with io.open("f.txt", mode="r", buffering=-1, **kwargs) as f: +3 - with io.open("f.txt", mode="r", buffering=-1, **kwargs) as f: 3 + with open("f.txt", mode="r", buffering=-1, **kwargs) as f: -4 | print(f.read()) | UP020 [*] Use builtin `open` @@ -28,14 +26,11 @@ UP020 [*] Use builtin `open` 9 | print(f.read()) | help: Replace with builtin `open` - | -6 | from io import open -7 + import builtins -8 | - - with open("f.txt") as f: -9 + with builtins.open("f.txt") as f: -10 | print(f.read()) - | + | +7 + import builtins +8 + +9 ~ with builtins.open("f.txt") as f: + | UP020 [*] Use builtin `open` --> UP020.py:13:5 @@ -50,15 +45,11 @@ UP020 [*] Use builtin `open` | help: Replace with builtin `open` | -6 | from io import open -7 + import builtins -8 | --------------------------------------------------------------------------------- + 7 + import builtins + 8 + + 9 | with open("f.txt") as f: + … 13 | with ( - - io # text - - # text - - .open("file.txt") as f -14 + builtins.open("file.txt") as f -15 | ): +14 ~ builtins.open("file.txt") as f | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP021.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP021.py.snap index d2f7ec5eb3380..0b1d926cd21c1 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP021.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP021.py.snap @@ -12,10 +12,8 @@ UP021 [*] `universal_newlines` is deprecated, use `text` | help: Replace with `text` keyword argument | -4 | # Errors - - subprocess.run(["foo"], universal_newlines=True, check=True) +5 - subprocess.run(["foo"], universal_newlines=True, check=True) 5 + subprocess.run(["foo"], text=True, check=True) -6 | subprocess.run(["foo"], universal_newlines=True, text=True) | UP021 [*] `universal_newlines` is deprecated, use `text` @@ -29,10 +27,8 @@ UP021 [*] `universal_newlines` is deprecated, use `text` | help: Replace with `text` keyword argument | -5 | subprocess.run(["foo"], universal_newlines=True, check=True) - - subprocess.run(["foo"], universal_newlines=True, text=True) +6 - subprocess.run(["foo"], universal_newlines=True, text=True) 6 + subprocess.run(["foo"], text=True) -7 | run(["foo"], universal_newlines=True, check=False) | UP021 [*] `universal_newlines` is deprecated, use `text` @@ -47,8 +43,6 @@ UP021 [*] `universal_newlines` is deprecated, use `text` | help: Replace with `text` keyword argument | -6 | subprocess.run(["foo"], universal_newlines=True, text=True) - - run(["foo"], universal_newlines=True, check=False) +7 - run(["foo"], universal_newlines=True, check=False) 7 + run(["foo"], text=True, check=False) -8 | | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP022.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP022.py.snap index 2c7ef96bdc6a5..582797fefad03 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP022.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP022.py.snap @@ -13,10 +13,8 @@ UP022 [*] Prefer `capture_output` over sending `stdout` and `stderr` to `PIPE` | help: Replace with `capture_output` keyword argument | -3 | - - output = run(["foo"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) +4 - output = run(["foo"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 4 + output = run(["foo"], capture_output=True) -5 | | note: This is an unsafe fix and may change runtime behavior @@ -32,10 +30,8 @@ UP022 [*] Prefer `capture_output` over sending `stdout` and `stderr` to `PIPE` | help: Replace with `capture_output` keyword argument | -5 | - - output = subprocess.run(["foo"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) +6 - output = subprocess.run(["foo"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 6 + output = subprocess.run(["foo"], capture_output=True) -7 | | note: This is an unsafe fix and may change runtime behavior @@ -51,10 +47,8 @@ UP022 [*] Prefer `capture_output` over sending `stdout` and `stderr` to `PIPE` | help: Replace with `capture_output` keyword argument | -7 | - - output = subprocess.run(stdout=subprocess.PIPE, args=["foo"], stderr=subprocess.PIPE) +8 - output = subprocess.run(stdout=subprocess.PIPE, args=["foo"], stderr=subprocess.PIPE) 8 + output = subprocess.run(capture_output=True, args=["foo"]) -9 | | note: This is an unsafe fix and may change runtime behavior @@ -73,10 +67,8 @@ UP022 [*] Prefer `capture_output` over sending `stdout` and `stderr` to `PIPE` | help: Replace with `capture_output` keyword argument | -10 | output = subprocess.run( - - ["foo"], stdout=subprocess.PIPE, check=True, stderr=subprocess.PIPE +11 - ["foo"], stdout=subprocess.PIPE, check=True, stderr=subprocess.PIPE 11 + ["foo"], capture_output=True, check=True -12 | ) | note: This is an unsafe fix and may change runtime behavior @@ -95,10 +87,8 @@ UP022 [*] Prefer `capture_output` over sending `stdout` and `stderr` to `PIPE` | help: Replace with `capture_output` keyword argument | -14 | output = subprocess.run( - - ["foo"], stderr=subprocess.PIPE, check=True, stdout=subprocess.PIPE +15 - ["foo"], stderr=subprocess.PIPE, check=True, stdout=subprocess.PIPE 15 + ["foo"], capture_output=True, check=True -16 | ) | note: This is an unsafe fix and may change runtime behavior @@ -123,12 +113,9 @@ UP022 [*] Prefer `capture_output` over sending `stdout` and `stderr` to `PIPE` | help: Replace with `capture_output` keyword argument | -19 | ["foo"], - - stdout=subprocess.PIPE, -20 + capture_output=True, +20 ~ capture_output=True, 21 | check=True, - - stderr=subprocess.PIPE, -22 | text=True, +22 ~ text=True, | note: This is an unsafe fix and may change runtime behavior @@ -151,12 +138,9 @@ UP022 [*] Prefer `capture_output` over sending `stdout` and `stderr` to `PIPE` | help: Replace with `capture_output` keyword argument | -30 | ["foo"], - - stdout=subprocess.PIPE, -31 + capture_output=True, +31 ~ capture_output=True, 32 | check=True, - - stderr=subprocess.PIPE, -33 | text=True, +33 ~ text=True, | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP023.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP023.py.snap index 5173b72ee5ffd..2406230d1b2dd 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP023.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP023.py.snap @@ -11,10 +11,8 @@ UP023 [*] `cElementTree` is deprecated, use `ElementTree` | help: Replace with `ElementTree` | -1 | # These two imports have something after cElementTree, so they should be fixed. - - from xml.etree.cElementTree import XML, Element, SubElement +2 - from xml.etree.cElementTree import XML, Element, SubElement 2 + from xml.etree.ElementTree import XML, Element, SubElement -3 | import xml.etree.cElementTree as ET | UP023 [*] `cElementTree` is deprecated, use `ElementTree` @@ -29,10 +27,8 @@ UP023 [*] `cElementTree` is deprecated, use `ElementTree` | help: Replace with `ElementTree` | -2 | from xml.etree.cElementTree import XML, Element, SubElement - - import xml.etree.cElementTree as ET +3 - import xml.etree.cElementTree as ET 3 + import xml.etree.ElementTree as ET -4 | | UP023 [*] `cElementTree` is deprecated, use `ElementTree` @@ -45,10 +41,8 @@ UP023 [*] `cElementTree` is deprecated, use `ElementTree` | help: Replace with `ElementTree` | -5 | # Weird spacing should not cause issues. - - from xml.etree.cElementTree import XML +6 - from xml.etree.cElementTree import XML 6 + from xml.etree.ElementTree import XML -7 | import xml.etree.cElementTree as ET | UP023 [*] `cElementTree` is deprecated, use `ElementTree` @@ -63,10 +57,8 @@ UP023 [*] `cElementTree` is deprecated, use `ElementTree` | help: Replace with `ElementTree` | -6 | from xml.etree.cElementTree import XML - - import xml.etree.cElementTree as ET +7 - import xml.etree.cElementTree as ET 7 + import xml.etree.ElementTree as ET -8 | | UP023 [*] `cElementTree` is deprecated, use `ElementTree` @@ -84,10 +76,11 @@ UP023 [*] `cElementTree` is deprecated, use `ElementTree` | help: Replace with `ElementTree` | -9 | # Multi line imports should also work fine. - - from xml.etree.cElementTree import ( 10 + from xml.etree.ElementTree import ( -11 | XML, +11 + XML, +12 + Element, +13 + SubElement, +14 + ) | UP023 [*] `cElementTree` is deprecated, use `ElementTree` @@ -101,10 +94,8 @@ UP023 [*] `cElementTree` is deprecated, use `ElementTree` | help: Replace with `ElementTree` | -15 | if True: - - import xml.etree.cElementTree as ET +16 - import xml.etree.cElementTree as ET 16 + import xml.etree.ElementTree as ET -17 | from xml.etree import cElementTree as CET | UP023 [*] `cElementTree` is deprecated, use `ElementTree` @@ -119,10 +110,8 @@ UP023 [*] `cElementTree` is deprecated, use `ElementTree` | help: Replace with `ElementTree` | -16 | import xml.etree.cElementTree as ET - - from xml.etree import cElementTree as CET +17 - from xml.etree import cElementTree as CET 17 + from xml.etree import ElementTree as CET -18 | | UP023 [*] `cElementTree` is deprecated, use `ElementTree` @@ -137,10 +126,8 @@ UP023 [*] `cElementTree` is deprecated, use `ElementTree` | help: Replace with `ElementTree` | -18 | - - from xml.etree import cElementTree as ET +19 - from xml.etree import cElementTree as ET 19 + from xml.etree import ElementTree as ET -20 | | UP023 [*] `cElementTree` is deprecated, use `ElementTree` @@ -155,10 +142,8 @@ UP023 [*] `cElementTree` is deprecated, use `ElementTree` | help: Replace with `ElementTree` | -20 | - - import contextlib, xml.etree.cElementTree as ET +21 - import contextlib, xml.etree.cElementTree as ET 21 + import contextlib, xml.etree.ElementTree as ET -22 | | UP023 [*] `cElementTree` is deprecated, use `ElementTree` @@ -172,8 +157,6 @@ UP023 [*] `cElementTree` is deprecated, use `ElementTree` | help: Replace with `ElementTree` | -23 | # This should fix the second, but not the first invocation. - - import xml.etree.cElementTree, xml.etree.cElementTree as ET +24 - import xml.etree.cElementTree, xml.etree.cElementTree as ET 24 + import xml.etree.cElementTree, xml.etree.ElementTree as ET -25 | | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP024_0.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP024_0.py.snap index d088f9c82d1fa..5fd476ac4cef0 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP024_0.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP024_0.py.snap @@ -12,10 +12,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `EnvironmentError` with builtin `OSError` | -5 | pass - - except EnvironmentError: +6 - except EnvironmentError: 6 + except OSError: -7 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -29,10 +27,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `IOError` with builtin `OSError` | -10 | pass - - except IOError: +11 - except IOError: 11 + except OSError: -12 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -46,10 +42,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `WindowsError` with builtin `OSError` | -15 | pass - - except WindowsError: +16 - except WindowsError: 16 + except OSError: -17 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -63,10 +57,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `mmap.error` with builtin `OSError` | -20 | pass - - except mmap.error: +21 - except mmap.error: 21 + except OSError: -22 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -80,10 +72,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `select.error` with builtin `OSError` | -25 | pass - - except select.error: +26 - except select.error: 26 + except OSError: -27 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -97,10 +87,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `socket.error` with builtin `OSError` | -30 | pass - - except socket.error: +31 - except socket.error: 31 + except OSError: -32 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -114,10 +102,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `error` with builtin `OSError` | -35 | pass - - except error: +36 - except error: 36 + except OSError: -37 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -132,10 +118,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace with builtin `OSError` | -42 | pass - - except (IOError,): +43 - except (IOError,): 43 + except OSError: -44 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -150,10 +134,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace with builtin `OSError` | -46 | pass - - except (mmap.error,): +47 - except (mmap.error,): 47 + except OSError: -48 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -167,10 +149,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace with builtin `OSError` | -50 | pass - - except (EnvironmentError, IOError, OSError, select.error): +51 - except (EnvironmentError, IOError, OSError, select.error): 51 + except OSError: -52 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -184,10 +164,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace with builtin `OSError` | -57 | pass - - except (IOError, KeyError, OSError): +58 - except (IOError, KeyError, OSError): 58 + except (KeyError, OSError): -59 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -202,10 +180,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace with builtin `OSError` | -64 | pass - - except (IOError, error): +65 - except (IOError, error): 65 + except (OSError, error): -66 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -219,10 +195,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `mmap.error` with builtin `OSError` | -86 | pass - - except (mmap).error: +87 - except (mmap).error: 87 + except OSError: -88 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -236,10 +210,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace with builtin `OSError` | -104 | mac_address = get_primary_mac_address() - - except(IOError, OSError) as ex: +105 - except(IOError, OSError) as ex: 105 + except OSError as ex: -106 | msg = 'Unable to query URL to get Owner ID: {u}\n{e}'.format(u=owner_id_url, e=ex) | UP024 [*] Replace aliased errors with `OSError` @@ -253,8 +225,6 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `os.error` with builtin `OSError` | -113 | pass - - except os.error: +114 - except os.error: 114 + except OSError: -115 | pass | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP024_0.py__preview.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP024_0.py__preview.snap index 409c6efa9c3c2..6b3709656f68b 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP024_0.py__preview.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP024_0.py__preview.snap @@ -12,10 +12,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `EnvironmentError` with builtin `OSError` | -5 | pass - - except EnvironmentError: +6 - except EnvironmentError: 6 + except OSError: -7 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -29,10 +27,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `IOError` with builtin `OSError` | -10 | pass - - except IOError: +11 - except IOError: 11 + except OSError: -12 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -46,10 +42,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `WindowsError` with builtin `OSError` | -15 | pass - - except WindowsError: +16 - except WindowsError: 16 + except OSError: -17 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -63,10 +57,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `mmap.error` with builtin `OSError` | -20 | pass - - except mmap.error: +21 - except mmap.error: 21 + except OSError: -22 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -80,10 +72,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `select.error` with builtin `OSError` | -25 | pass - - except select.error: +26 - except select.error: 26 + except OSError: -27 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -97,10 +87,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `socket.error` with builtin `OSError` | -30 | pass - - except socket.error: +31 - except socket.error: 31 + except OSError: -32 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -114,10 +102,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `error` with builtin `OSError` | -35 | pass - - except error: +36 - except error: 36 + except OSError: -37 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -132,10 +118,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace with builtin `OSError` | -42 | pass - - except (IOError,): +43 - except (IOError,): 43 + except OSError: -44 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -150,10 +134,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace with builtin `OSError` | -46 | pass - - except (mmap.error,): +47 - except (mmap.error,): 47 + except OSError: -48 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -167,10 +149,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace with builtin `OSError` | -50 | pass - - except (EnvironmentError, IOError, OSError, select.error): +51 - except (EnvironmentError, IOError, OSError, select.error): 51 + except OSError: -52 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -184,10 +164,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace with builtin `OSError` | -57 | pass - - except (IOError, KeyError, OSError): +58 - except (IOError, KeyError, OSError): 58 + except (KeyError, OSError): -59 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -202,10 +180,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace with builtin `OSError` | -64 | pass - - except (IOError, error): +65 - except (IOError, error): 65 + except (OSError, error): -66 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -219,10 +195,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `mmap.error` with builtin `OSError` | -86 | pass - - except (mmap).error: +87 - except (mmap).error: 87 + except OSError: -88 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -236,10 +210,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace with builtin `OSError` | -104 | mac_address = get_primary_mac_address() - - except(IOError, OSError) as ex: +105 - except(IOError, OSError) as ex: 105 + except OSError as ex: -106 | msg = 'Unable to query URL to get Owner ID: {u}\n{e}'.format(u=owner_id_url, e=ex) | UP024 [*] Replace aliased errors with `OSError` @@ -253,8 +225,6 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `os.error` with builtin `OSError` | -113 | pass - - except os.error: +114 - except os.error: 114 + except OSError: -115 | pass | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP024_1.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP024_1.py.snap index 8201836c52204..a79a2143f9065 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP024_1.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP024_1.py.snap @@ -13,10 +13,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace with builtin `OSError` | -4 | pass - - except (OSError, mmap.error, IOError): +5 - except (OSError, mmap.error, IOError): 5 + except OSError: -6 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -30,10 +28,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace with builtin `OSError` | -6 | pass - - except (OSError, socket.error, KeyError): +7 - except (OSError, socket.error, KeyError): 7 + except (OSError, KeyError): -8 | pass | UP024 [*] Replace aliased errors with `OSError` @@ -52,12 +48,10 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace with builtin `OSError` | -11 | pass - - except ( - - OSError, - - select.error, - - IOError, - - ): +12 - except ( +13 - OSError, +14 - select.error, +15 - IOError, +16 - ): 12 + except OSError: -13 | pass | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP024_2.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP024_2.py.snap index bd02547a50007..386f950a696bc 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP024_2.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP024_2.py.snap @@ -13,10 +13,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `socket.error` with builtin `OSError` | -9 | import socket, mmap, select, resource - - raise socket.error +10 - raise socket.error 10 + raise OSError -11 | raise mmap.error | UP024 [*] Replace aliased errors with `OSError` @@ -31,10 +29,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `mmap.error` with builtin `OSError` | -10 | raise socket.error - - raise mmap.error +11 - raise mmap.error 11 + raise OSError -12 | raise select.error | UP024 [*] Replace aliased errors with `OSError` @@ -48,10 +44,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `select.error` with builtin `OSError` | -11 | raise mmap.error - - raise select.error +12 - raise select.error 12 + raise OSError -13 | raise resource.error | UP024 [*] Replace aliased errors with `OSError` @@ -66,10 +60,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `resource.error` with builtin `OSError` | -12 | raise select.error - - raise resource.error +13 - raise resource.error 13 + raise OSError -14 | | UP024 [*] Replace aliased errors with `OSError` @@ -84,10 +76,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `socket.error` with builtin `OSError` | -14 | - - raise socket.error() +15 - raise socket.error() 15 + raise OSError() -16 | raise mmap.error(1) | UP024 [*] Replace aliased errors with `OSError` @@ -101,10 +91,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `mmap.error` with builtin `OSError` | -15 | raise socket.error() - - raise mmap.error(1) +16 - raise mmap.error(1) 16 + raise OSError(1) -17 | raise select.error(1, 2) | UP024 [*] Replace aliased errors with `OSError` @@ -118,10 +106,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `select.error` with builtin `OSError` | -16 | raise mmap.error(1) - - raise select.error(1, 2) +17 - raise select.error(1, 2) 17 + raise OSError(1, 2) -18 | raise resource.error(1, "strerror", "filename") | UP024 [*] Replace aliased errors with `OSError` @@ -136,10 +122,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `resource.error` with builtin `OSError` | -17 | raise select.error(1, 2) - - raise resource.error(1, "strerror", "filename") +18 - raise resource.error(1, "strerror", "filename") 18 + raise OSError(1, "strerror", "filename") -19 | | UP024 [*] Replace aliased errors with `OSError` @@ -154,10 +138,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `socket.error` with builtin `OSError` | -19 | - - raise socket.error( +20 - raise socket.error( 20 + raise OSError( -21 | 1, | UP024 [*] Replace aliased errors with `OSError` @@ -171,10 +153,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `error` with builtin `OSError` | -26 | from mmap import error - - raise error +27 - raise error 27 + raise OSError -28 | | UP024 [*] Replace aliased errors with `OSError` @@ -188,10 +168,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `error` with builtin `OSError` | -29 | from socket import error - - raise error(1) +30 - raise error(1) 30 + raise OSError(1) -31 | | UP024 [*] Replace aliased errors with `OSError` @@ -205,10 +183,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `error` with builtin `OSError` | -32 | from select import error - - raise error(1, 2) +33 - raise error(1, 2) 33 + raise OSError(1, 2) -34 | | UP024 [*] Replace aliased errors with `OSError` @@ -222,10 +198,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `error` with builtin `OSError` | -35 | from resource import error - - raise error(1, "strerror", "filename") +36 - raise error(1, "strerror", "filename") 36 + raise OSError(1, "strerror", "filename") -37 | | UP024 [*] Replace aliased errors with `OSError` @@ -239,10 +213,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `EnvironmentError` with builtin `OSError` | -38 | # Testing the names - - raise EnvironmentError +39 - raise EnvironmentError 39 + raise OSError -40 | raise IOError | UP024 [*] Replace aliased errors with `OSError` @@ -256,10 +228,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `IOError` with builtin `OSError` | -39 | raise EnvironmentError - - raise IOError +40 - raise IOError 40 + raise OSError -41 | raise WindowsError | UP024 [*] Replace aliased errors with `OSError` @@ -274,10 +244,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `WindowsError` with builtin `OSError` | -40 | raise IOError - - raise WindowsError +41 - raise WindowsError 41 + raise OSError -42 | | UP024 [*] Replace aliased errors with `OSError` @@ -292,10 +260,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `EnvironmentError` with builtin `OSError` | -42 | - - raise EnvironmentError() +43 - raise EnvironmentError() 43 + raise OSError() -44 | raise IOError(1) | UP024 [*] Replace aliased errors with `OSError` @@ -308,10 +274,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `IOError` with builtin `OSError` | -43 | raise EnvironmentError() - - raise IOError(1) +44 - raise IOError(1) 44 + raise OSError(1) -45 | raise WindowsError(1, 2) | UP024 [*] Replace aliased errors with `OSError` @@ -326,10 +290,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `WindowsError` with builtin `OSError` | -44 | raise IOError(1) - - raise WindowsError(1, 2) +45 - raise WindowsError(1, 2) 45 + raise OSError(1, 2) -46 | | UP024 [*] Replace aliased errors with `OSError` @@ -344,10 +306,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `EnvironmentError` with builtin `OSError` | -46 | - - raise EnvironmentError( +47 - raise EnvironmentError( 47 + raise OSError( -48 | 1, | UP024 [*] Replace aliased errors with `OSError` @@ -362,10 +322,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `WindowsError` with builtin `OSError` | -52 | - - raise WindowsError +53 - raise WindowsError 53 + raise OSError -54 | raise EnvironmentError(1) | UP024 [*] Replace aliased errors with `OSError` @@ -378,10 +336,8 @@ UP024 [*] Replace aliased errors with `OSError` | help: Replace `EnvironmentError` with builtin `OSError` | -53 | raise WindowsError - - raise EnvironmentError(1) +54 - raise EnvironmentError(1) 54 + raise OSError(1) -55 | raise IOError(1, 2) | UP024 [*] Replace aliased errors with `OSError` @@ -393,7 +349,6 @@ UP024 [*] Replace aliased errors with `OSError` | ^^^^^^^ help: Replace `IOError` with builtin `OSError` | -54 | raise EnvironmentError(1) - - raise IOError(1, 2) +55 - raise IOError(1, 2) 55 + raise OSError(1, 2) | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP024_4.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP024_4.py.snap index 35f7e607343e9..dae883fd15417 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP024_4.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP024_4.py.snap @@ -11,9 +11,7 @@ UP024 [*] Replace aliased errors with `OSError` 10 | return HttpResponseServerError("cache: cannot connect to broker.") | help: Replace with builtin `OSError` - | -8 | conn._close() - - except (socket.error, exceptions.OperationalError): -9 + except (OSError, exceptions.OperationalError): -10 | return HttpResponseServerError("cache: cannot connect to broker.") - | + | +9 - except (socket.error, exceptions.OperationalError): +9 + except (OSError, exceptions.OperationalError): + | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP025.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP025.py.snap index a3315333bfee7..c1338626b1c99 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP025.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP025.py.snap @@ -11,9 +11,8 @@ UP025 [*] Remove unicode literals from strings | help: Remove unicode prefix | - - u"Hello" +1 - u"Hello" 1 + "Hello" -2 | | UP025 [*] Remove unicode literals from strings @@ -28,10 +27,8 @@ UP025 [*] Remove unicode literals from strings | help: Remove unicode prefix | -2 | - - x = u"Hello" # UP025 +3 - x = u"Hello" # UP025 3 + x = "Hello" # UP025 -4 | | UP025 [*] Remove unicode literals from strings @@ -46,10 +43,8 @@ UP025 [*] Remove unicode literals from strings | help: Remove unicode prefix | -4 | - - u'world' # UP025 +5 - u'world' # UP025 5 + 'world' # UP025 -6 | | UP025 [*] Remove unicode literals from strings @@ -64,10 +59,8 @@ UP025 [*] Remove unicode literals from strings | help: Remove unicode prefix | -6 | - - print(u"Hello") # UP025 +7 - print(u"Hello") # UP025 7 + print("Hello") # UP025 -8 | | UP025 [*] Remove unicode literals from strings @@ -81,12 +74,10 @@ UP025 [*] Remove unicode literals from strings 11 | import foo | help: Remove unicode prefix - | -8 | - - print(u'world') # UP025 -9 + print('world') # UP025 -10 | - | + | +9 - print(u'world') # UP025 +9 + print('world') # UP025 + | UP025 [*] Remove unicode literals from strings --> UP025.py:13:5 @@ -100,10 +91,8 @@ UP025 [*] Remove unicode literals from strings | help: Remove unicode prefix | -12 | - - foo(u"Hello", U"world", a=u"Hello", b=u"world") # UP025 +13 - foo(u"Hello", U"world", a=u"Hello", b=u"world") # UP025 13 + foo("Hello", U"world", a=u"Hello", b=u"world") # UP025 -14 | | UP025 [*] Remove unicode literals from strings @@ -118,10 +107,8 @@ UP025 [*] Remove unicode literals from strings | help: Remove unicode prefix | -12 | - - foo(u"Hello", U"world", a=u"Hello", b=u"world") # UP025 +13 - foo(u"Hello", U"world", a=u"Hello", b=u"world") # UP025 13 + foo(u"Hello", "world", a=u"Hello", b=u"world") # UP025 -14 | | UP025 [*] Remove unicode literals from strings @@ -136,10 +123,8 @@ UP025 [*] Remove unicode literals from strings | help: Remove unicode prefix | -12 | - - foo(u"Hello", U"world", a=u"Hello", b=u"world") # UP025 +13 - foo(u"Hello", U"world", a=u"Hello", b=u"world") # UP025 13 + foo(u"Hello", U"world", a="Hello", b=u"world") # UP025 -14 | | UP025 [*] Remove unicode literals from strings @@ -154,10 +139,8 @@ UP025 [*] Remove unicode literals from strings | help: Remove unicode prefix | -12 | - - foo(u"Hello", U"world", a=u"Hello", b=u"world") # UP025 +13 - foo(u"Hello", U"world", a=u"Hello", b=u"world") # UP025 13 + foo(u"Hello", U"world", a=u"Hello", b="world") # UP025 -14 | | UP025 [*] Remove unicode literals from strings @@ -171,10 +154,8 @@ UP025 [*] Remove unicode literals from strings | help: Remove unicode prefix | -15 | # Retain quotes when fixing. - - x = u'hello' # UP025 +16 - x = u'hello' # UP025 16 + x = 'hello' # UP025 -17 | x = u"""hello""" # UP025 | UP025 [*] Remove unicode literals from strings @@ -189,10 +170,8 @@ UP025 [*] Remove unicode literals from strings | help: Remove unicode prefix | -16 | x = u'hello' # UP025 - - x = u"""hello""" # UP025 +17 - x = u"""hello""" # UP025 17 + x = """hello""" # UP025 -18 | x = u'''hello''' # UP025 | UP025 [*] Remove unicode literals from strings @@ -206,10 +185,8 @@ UP025 [*] Remove unicode literals from strings | help: Remove unicode prefix | -17 | x = u"""hello""" # UP025 - - x = u'''hello''' # UP025 +18 - x = u'''hello''' # UP025 18 + x = '''hello''' # UP025 -19 | x = u'Hello "World"' # UP025 | UP025 [*] Remove unicode literals from strings @@ -224,10 +201,8 @@ UP025 [*] Remove unicode literals from strings | help: Remove unicode prefix | -18 | x = u'''hello''' # UP025 - - x = u'Hello "World"' # UP025 +19 - x = u'Hello "World"' # UP025 19 + x = 'Hello "World"' # UP025 -20 | | UP025 [*] Remove unicode literals from strings @@ -241,10 +216,8 @@ UP025 [*] Remove unicode literals from strings | help: Remove unicode prefix | -26 | - - f"foo"u"bar" # OK +27 - f"foo"u"bar" # OK 27 + f"foo" "bar" # OK -28 | f"foo" u"bar" # OK | UP025 [*] Remove unicode literals from strings @@ -258,10 +231,8 @@ UP025 [*] Remove unicode literals from strings | help: Remove unicode prefix | -27 | f"foo"u"bar" # OK - - f"foo" u"bar" # OK +28 - f"foo" u"bar" # OK 28 + f"foo" "bar" # OK -29 | | UP025 [*] Remove unicode literals from strings @@ -275,10 +246,8 @@ UP025 [*] Remove unicode literals from strings | help: Remove unicode prefix | -30 | # https://github.com/astral-sh/ruff/issues/18895 - - ""u"" +31 - ""u"" 31 + "" "" -32 | ""u"hi" | UP025 [*] Remove unicode literals from strings @@ -293,10 +262,8 @@ UP025 [*] Remove unicode literals from strings | help: Remove unicode prefix | -31 | ""u"" - - ""u"hi" +32 - ""u"hi" 32 + "" "hi" -33 | """"""""""""""""""""u"hi" | UP025 [*] Remove unicode literals from strings @@ -310,10 +277,8 @@ UP025 [*] Remove unicode literals from strings | help: Remove unicode prefix | -32 | ""u"hi" - - """"""""""""""""""""u"hi" +33 - """"""""""""""""""""u"hi" 33 + """""""""""""""""""" "hi" -34 | ""U"helloooo" | UP025 [*] Remove unicode literals from strings @@ -325,7 +290,6 @@ UP025 [*] Remove unicode literals from strings | ^^^^^^^^^^^ help: Remove unicode prefix | -33 | """"""""""""""""""""u"hi" - - ""U"helloooo" +34 - ""U"helloooo" 34 + "" "helloooo" | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP026.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP026.py.snap index 0a8c718d06276..2c5eceed6291d 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP026.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP026.py.snap @@ -13,11 +13,8 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -2 | if True: - - import mock -3 + from unittest import mock -4 | - | +3 | from unittest import mock + | +++++++++++++ UP026 [*] `mock` is deprecated, use `unittest.mock` --> UP026.py:7:12 @@ -31,11 +28,8 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -6 | if True: - - import mock, sys -7 + import sys +7 ~ import sys 8 + from unittest import mock -9 | | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -50,11 +44,8 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -10 | if True: - - from mock import * -11 + from unittest.mock import * -12 | - | +11 | from unittest.mock import * + | +++++++++ UP026 [*] `mock` is deprecated, use `unittest.mock` --> UP026.py:14:8 @@ -67,10 +58,8 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -13 | # Error (`from unittest import mock`) - - import mock.mock +14 - import mock.mock 14 + from unittest import mock -15 | | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -84,11 +73,8 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -16 | # Error (`from unittest import mock`) - - import contextlib, mock, sys 17 + import contextlib, sys 18 + from unittest import mock -19 | | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -101,11 +87,8 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -19 | # Error (`from unittest import mock`) - - import mock, sys 20 + import sys 21 + from unittest import mock -22 | x = "This code should be preserved one line below the mock" | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -119,10 +102,8 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -23 | # Error (`from unittest import mock`) - - from mock import mock +24 - from mock import mock 24 + from unittest import mock -25 | | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -141,16 +122,12 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -26 | # Error (keep trailing comma) - - from mock import ( - - mock, 27 + from unittest.mock import ( -28 | a, -29 | b, -30 | c, -31 | ) +28 + a, +29 + b, +30 + c, +31 + ) 32 + from unittest import mock -33 | from mock import ( | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -170,16 +147,12 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -32 | ) - - from mock import ( 33 + from unittest.mock import ( -34 | a, -35 | b, -36 | c, - - mock, -37 | ) +34 + a, +35 + b, +36 + c, +37 + ) 38 + from unittest import mock -39 | | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -198,16 +171,12 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -40 | # Error (avoid trailing comma) - - from mock import ( - - mock, 41 + from unittest.mock import ( -42 | a, -43 | b, -44 | c -45 | ) +42 + a, +43 + b, +44 + c +45 + ) 46 + from unittest import mock -47 | from mock import ( | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -227,17 +196,12 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -46 | ) - - from mock import ( 47 + from unittest.mock import ( -48 | a, -49 | b, - - c, - - mock +48 + a, +49 + b, 50 + c -51 | ) +51 + ) 52 + from unittest import mock -53 | from mock import mock, a, b, c | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -251,11 +215,8 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -52 | ) - - from mock import mock, a, b, c 53 + from unittest.mock import a, b, c 54 + from unittest import mock -55 | from mock import a, b, c, mock | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -270,11 +231,8 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -53 | from mock import mock, a, b, c - - from mock import a, b, c, mock 54 + from unittest.mock import a, b, c 55 + from unittest import mock -56 | | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -294,16 +252,12 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -57 | if False: - - from mock import ( - - mock, -58 + from unittest.mock import ( -59 | a, -60 | b, -61 | c -62 | ) +58 ~ from unittest.mock import ( +59 + a, +60 + b, +61 + c +62 + ) 63 + from unittest import mock -64 | | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -317,11 +271,8 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -68 | # Error (`from unittest import mock`) - - import mock, mock 69 + from unittest import mock 70 + from unittest import mock -71 | | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -335,11 +286,8 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -68 | # Error (`from unittest import mock`) - - import mock, mock 69 + from unittest import mock 70 + from unittest import mock -71 | | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -353,11 +301,8 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -71 | # Error (`from unittest import mock as foo`) - - import mock as foo -72 + from unittest import mock as foo -73 | - | +72 | from unittest import mock as foo + | +++++++++++++ UP026 [*] `mock` is deprecated, use `unittest.mock` --> UP026.py:75:1 @@ -370,10 +315,8 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -74 | # Error (`from unittest import mock as foo`) - - from mock import mock as foo +75 - from mock import mock as foo 75 + from unittest import mock as foo -76 | | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -388,12 +331,9 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -78 | # This should yield multiple, aliased imports. - - import mock as foo, mock as bar, mock -79 + from unittest import mock as foo +79 ~ from unittest import mock as foo 80 + from unittest import mock as bar 81 + from unittest import mock -82 | | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -408,12 +348,9 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -78 | # This should yield multiple, aliased imports. - - import mock as foo, mock as bar, mock -79 + from unittest import mock as foo +79 ~ from unittest import mock as foo 80 + from unittest import mock as bar 81 + from unittest import mock -82 | | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -428,12 +365,9 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -78 | # This should yield multiple, aliased imports. - - import mock as foo, mock as bar, mock -79 + from unittest import mock as foo +79 ~ from unittest import mock as foo 80 + from unittest import mock as bar 81 + from unittest import mock -82 | | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -447,13 +381,10 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -81 | # This should yield multiple, aliased imports, and preserve `os`. - - import mock as foo, mock as bar, mock, os -82 + import os +82 ~ import os 83 + from unittest import mock as foo 84 + from unittest import mock as bar 85 + from unittest import mock -86 | | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -467,13 +398,10 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -81 | # This should yield multiple, aliased imports, and preserve `os`. - - import mock as foo, mock as bar, mock, os -82 + import os +82 ~ import os 83 + from unittest import mock as foo 84 + from unittest import mock as bar 85 + from unittest import mock -86 | | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -487,13 +415,10 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | help: Import from `unittest.mock` instead | -81 | # This should yield multiple, aliased imports, and preserve `os`. - - import mock as foo, mock as bar, mock, os -82 + import os +82 ~ import os 83 + from unittest import mock as foo 84 + from unittest import mock as bar 85 + from unittest import mock -86 | | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -505,12 +430,9 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Import from `unittest.mock` instead | -85 | # This should yield multiple, aliased imports. - - from mock import mock as foo, mock as bar, mock -86 + from unittest import mock as foo +86 ~ from unittest import mock as foo 87 + from unittest import mock as bar 88 + from unittest import mock -89 | | UP026 [*] `mock` is deprecated, use `unittest.mock` @@ -521,7 +443,6 @@ UP026 [*] `mock` is deprecated, use `unittest.mock` | ^^^^^^^^^ help: Replace `mock.mock` with `mock` | -92 | # Error (`mock.Mock()`). - - x = mock.mock.Mock() +93 - x = mock.mock.Mock() 93 + x = mock.Mock() | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP028_0.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP028_0.py.snap index c8e7dca2fe151..5b3ff69133889 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP028_0.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP028_0.py.snap @@ -10,11 +10,9 @@ UP028 [*] Replace `yield` over `for` loop with `yield from` | |_______________^ help: Replace with `yield from` | -1 | def f(): - - for x in y: - - yield x +2 - for x in y: +3 - yield x 2 + yield from y -3 | | note: This is an unsafe fix and may change runtime behavior @@ -27,11 +25,9 @@ UP028 [*] Replace `yield` over `for` loop with `yield from` | |____________________^ help: Replace with `yield from` | -6 | def g(): - - for x, y in z: - - yield (x, y) +7 - for x, y in z: +8 - yield (x, y) 7 + yield from z -8 | | note: This is an unsafe fix and may change runtime behavior @@ -44,11 +40,9 @@ UP028 [*] Replace `yield` over `for` loop with `yield from` | |_______________^ help: Replace with `yield from` | -11 | def h(): - - for x in [1, 2, 3]: - - yield x +12 - for x in [1, 2, 3]: +13 - yield x 12 + yield from [1, 2, 3] -13 | | note: This is an unsafe fix and may change runtime behavior @@ -61,11 +55,9 @@ UP028 [*] Replace `yield` over `for` loop with `yield from` | |_______________^ help: Replace with `yield from` | -16 | def i(): - - for x in {x for x in y}: - - yield x +17 - for x in {x for x in y}: +18 - yield x 17 + yield from {x for x in y} -18 | | note: This is an unsafe fix and may change runtime behavior @@ -78,11 +70,9 @@ UP028 [*] Replace `yield` over `for` loop with `yield from` | |_______________^ help: Replace with `yield from` | -21 | def j(): - - for x in (1, 2, 3): - - yield x +22 - for x in (1, 2, 3): +23 - yield x 22 + yield from (1, 2, 3) -23 | | note: This is an unsafe fix and may change runtime behavior @@ -95,11 +85,9 @@ UP028 [*] Replace `yield` over `for` loop with `yield from` | |__________________^ help: Replace with `yield from` | -26 | def k(): - - for x, y in {3: "x", 6: "y"}: - - yield x, y +27 - for x, y in {3: "x", 6: "y"}: +28 - yield x, y 27 + yield from {3: "x", 6: "y"} -28 | | note: This is an unsafe fix and may change runtime behavior @@ -120,17 +108,11 @@ UP028 [*] Replace `yield` over `for` loop with `yield from` | help: Replace with `yield from` | -32 | # Comment two\n' - - for x, y in { # Comment three\n' -33 + yield from { # Comment three\n' -34 | 3: "x", # Comment four\n' -35 | # Comment five\n' -36 | 6: "y", # Comment six\n' - - }: # Comment seven\n' - - # Comment eight\n' - - yield x, y # Comment nine\n' -37 + } # Comment nine\n' -38 | # Comment ten', +33 ~ yield from { # Comment three\n' +34 + 3: "x", # Comment four\n' +35 + # Comment five\n' +36 + 6: "y", # Comment six\n' +37 ~ } # Comment nine\n' | note: This is an unsafe fix and may change runtime behavior @@ -143,11 +125,9 @@ UP028 [*] Replace `yield` over `for` loop with `yield from` | |__________________^ help: Replace with `yield from` | -43 | def f(): - - for x, y in [{3: (3, [44, "long ss"]), 6: "y"}]: - - yield x, y +44 - for x, y in [{3: (3, [44, "long ss"]), 6: "y"}]: +45 - yield x, y 44 + yield from [{3: (3, [44, "long ss"]), 6: "y"}] -45 | | note: This is an unsafe fix and may change runtime behavior @@ -163,11 +143,9 @@ UP028 [*] Replace `yield` over `for` loop with `yield from` | help: Replace with `yield from` | -48 | def f(): - - for x, y in z(): - - yield x, y +49 - for x, y in z(): +50 - yield x, y 49 + yield from z() -50 | | note: This is an unsafe fix and may change runtime behavior @@ -185,12 +163,10 @@ UP028 [*] Replace `yield` over `for` loop with `yield from` | help: Replace with `yield from` | -54 | # This comment is preserved\n' - - for x, y in z(): # Comment one\n' - - # Comment two\n' - - yield x, y # Comment three\n' +55 - for x, y in z(): # Comment one\n' +56 - # Comment two\n' +57 - yield x, y # Comment three\n' 55 + yield from z() # Comment three\n' -56 | # Comment four\n' | note: This is an unsafe fix and may change runtime behavior @@ -204,11 +180,9 @@ UP028 [*] Replace `yield` over `for` loop with `yield from` | |_______________^ help: Replace with `yield from` | -66 | yield x - - for z in x: - - yield z +67 - for z in x: +68 - yield z 67 + yield from x -68 | | note: This is an unsafe fix and may change runtime behavior @@ -223,11 +197,9 @@ UP028 [*] Replace `yield` over `for` loop with `yield from` | help: Replace with `yield from` | -71 | def f(): - - for x, y in z(): - - yield x, y +72 - for x, y in z(): +73 - yield x, y 72 + yield from z() -73 | x = 1 | note: This is an unsafe fix and may change runtime behavior @@ -244,15 +216,10 @@ UP028 [*] Replace `yield` over `for` loop with `yield from` | |_______________^ help: Replace with `yield from` | -78 | def _serve_method(fn): - - for h in ( -79 + yield from ( -80 | TaggedText.from_file(args.input) -81 | .markup(highlight=args.region) - - ): - - yield h +79 ~ yield from ( +80 + TaggedText.from_file(args.input) +81 + .markup(highlight=args.region) 82 + ) -83 | | note: This is an unsafe fix and may change runtime behavior @@ -269,11 +236,9 @@ UP028 [*] Replace `yield` over `for` loop with `yield from` | help: Replace with `yield from` | -96 | def f(): - - for x in (1, 2, 3): - - yield x +97 - for x in (1, 2, 3): +98 - yield x 97 + yield from (1, 2, 3) -98 | # Shadowing with an `except` | note: This is an unsafe fix and may change runtime behavior @@ -290,11 +255,9 @@ UP028 [*] Replace `yield` over `for` loop with `yield from` | help: Replace with `yield from` | -107 | def f(): - - for x in (1, 2, 3): - - yield x +108 - for x in (1, 2, 3): +109 - yield x 108 + yield from (1, 2, 3) -109 | # Shadowing with `with` | note: This is an unsafe fix and may change runtime behavior @@ -311,11 +274,9 @@ UP028 [*] Replace `yield` over `for` loop with `yield from` | help: Replace with `yield from` | -117 | def f(): - - for x in (1, 2, 3): - - yield x +118 - for x in (1, 2, 3): +119 - yield x 118 + yield from (1, 2, 3) -119 | # Shadowing with a type annotation | note: This is an unsafe fix and may change runtime behavior @@ -332,11 +293,9 @@ UP028 [*] Replace `yield` over `for` loop with `yield from` | help: Replace with `yield from` | -133 | def f(): - - for x in (1, 2, 3): - - yield x +134 - for x in (1, 2, 3): +135 - yield x 134 + yield from (1, 2, 3) -135 | # Shadowing with multiple `except` blocks | note: This is an unsafe fix and may change runtime behavior @@ -350,11 +309,9 @@ UP028 [*] Replace `yield` over `for` loop with `yield from` | |_______________^ help: Replace with `yield from` | -169 | def f(): - - for a in 1,: - - yield a +170 - for a in 1,: +171 - yield a 170 + yield from (1,) -171 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP029_0.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP029_0.py.snap index bc4f7fd756866..29666ace85c1b 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP029_0.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP029_0.py.snap @@ -11,8 +11,7 @@ UP029 [*] Unnecessary builtin import: `*` | help: Remove unnecessary builtin import | - - from builtins import * -1 | from builtins import ascii, bytes, compile +1 - from builtins import * | note: This is an unsafe fix and may change runtime behavior @@ -27,10 +26,8 @@ UP029 [*] Unnecessary builtin imports: `ascii`, `bytes` | help: Remove unnecessary builtin import | -1 | from builtins import * - - from builtins import ascii, bytes, compile +2 - from builtins import ascii, bytes, compile 2 + from builtins import compile -3 | from builtins import str as _str | note: This is an unsafe fix and may change runtime behavior @@ -46,10 +43,8 @@ UP029 [*] Unnecessary builtin imports: `filter`, `zip` | help: Remove unnecessary builtin import | -3 | from builtins import str as _str - - from six.moves import filter, zip, zip_longest +4 - from six.moves import filter, zip, zip_longest 4 + from six.moves import zip_longest -5 | from io import open | note: This is an unsafe fix and may change runtime behavior @@ -65,8 +60,6 @@ UP029 [*] Unnecessary builtin import: `open` | help: Remove unnecessary builtin import | -4 | from six.moves import filter, zip, zip_longest - - from io import open -5 | import io +5 - from io import open | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP029_1.py_skip_required_imports.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP029_1.py_skip_required_imports.snap index 69d538baef1c7..2b7a7691216b6 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP029_1.py_skip_required_imports.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP029_1.py_skip_required_imports.snap @@ -8,7 +8,7 @@ UP029 [*] Unnecessary builtin import: `int` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove unnecessary builtin import | - - from builtins import str, int +1 - from builtins import str, int 1 + from builtins import str | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP029_3.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP029_3.py.snap index 449da39a0b333..38a95890dcb24 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP029_3.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP029_3.py.snap @@ -13,9 +13,7 @@ UP029 [*] Unnecessary builtin import: `pow` | help: Remove unnecessary builtin import | -18 | from math import * - - from builtins import pow # UP029, false positive due to the star import -19 | +19 - from builtins import pow # UP029, false positive due to the star import | note: This is an unsafe fix and may change runtime behavior @@ -32,10 +30,8 @@ UP029 [*] Unnecessary builtin import: `str` | help: Remove unnecessary builtin import | -24 | def unsafe_fix(): - - from builtins import ( - - str, # UP029, removes this comment - - ) -25 | +25 - from builtins import ( +26 - str, # UP029, removes this comment +27 - ) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP030_0.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP030_0.py.snap index 1a6e2d88d4297..e32b95aceea70 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP030_0.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP030_0.py.snap @@ -13,10 +13,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -2 | - - "{0}" "{1}" "{2}".format(1, 2, 3) +3 - "{0}" "{1}" "{2}".format(1, 2, 3) 3 + "{}" "{}" "{}".format(1, 2, 3) -4 | | note: This is an unsafe fix and may change runtime behavior @@ -34,12 +32,9 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -4 | - - "a {3} complicated {1} string with {0} {2}".format( - - "first", "second", "third", "fourth" 5 + "a {} complicated {} string with {} {}".format( 6 + "fourth", "second", "first", "third" -7 | ) +7 + ) | note: This is an unsafe fix and may change runtime behavior @@ -54,12 +49,10 @@ UP030 [*] Use implicit references for positional format fields 11 | '{0:x}'.format(30) | help: Remove explicit positional indices - | -8 | - - '{0}'.format(1) -9 + '{}'.format(1) -10 | - | + | +9 - '{0}'.format(1) +9 + '{}'.format(1) + | note: This is an unsafe fix and may change runtime behavior UP030 [*] Use implicit references for positional format fields @@ -74,10 +67,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -10 | - - '{0:x}'.format(30) +11 - '{0:x}'.format(30) 11 + '{:x}'.format(30) -12 | | note: This is an unsafe fix and may change runtime behavior @@ -93,10 +84,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -12 | - - x = '{0}'.format(1) +13 - x = '{0}'.format(1) 13 + x = '{}'.format(1) -14 | | note: This is an unsafe fix and may change runtime behavior @@ -112,10 +101,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -14 | - - '''{0}\n{1}\n'''.format(1, 2) +15 - '''{0}\n{1}\n'''.format(1, 2) 15 + '''{}\n{}\n'''.format(1, 2) -16 | | note: This is an unsafe fix and may change runtime behavior @@ -133,12 +120,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -16 | - - x = "foo {0}" \ - - "bar {1}".format(1, 2) -17 + x = "foo {}" \ +17 ~ x = "foo {}" \ 18 + "bar {}".format(1, 2) -19 | | note: This is an unsafe fix and may change runtime behavior @@ -154,10 +137,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -19 | - - ("{0}").format(1) +20 - ("{0}").format(1) 20 + ("{}").format(1) -21 | | note: This is an unsafe fix and may change runtime behavior @@ -173,10 +154,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -21 | - - "\N{snowman} {0}".format(1) +22 - "\N{snowman} {0}".format(1) 22 + "\N{snowman} {}".format(1) -23 | | note: This is an unsafe fix and may change runtime behavior @@ -191,12 +170,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -24 | print( - - 'foo{0}' - - 'bar{1}'.format(1, 2) -25 + 'foo{}' +25 ~ 'foo{}' 26 + 'bar{}'.format(1, 2) -27 | ) | note: This is an unsafe fix and may change runtime behavior @@ -211,12 +186,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -29 | print( - - 'foo{0}' # ohai\n" - - 'bar{1}'.format(1, 2) -30 + 'foo{}' # ohai\n" +30 ~ 'foo{}' # ohai\n" 31 + 'bar{}'.format(1, 2) -32 | ) | note: This is an unsafe fix and may change runtime behavior @@ -244,10 +215,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -38 | - - "{0}".format(*args) +39 - "{0}".format(*args) 39 + "{}".format(*args) -40 | | note: This is an unsafe fix and may change runtime behavior @@ -263,10 +232,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -40 | - - "{0}".format(**kwargs) +41 - "{0}".format(**kwargs) 41 + "{}".format(**kwargs) -42 | | note: This is an unsafe fix and may change runtime behavior @@ -282,10 +249,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -42 | - - "{0}_{1}".format(*args) +43 - "{0}_{1}".format(*args) 43 + "{}_{}".format(*args) -44 | | note: This is an unsafe fix and may change runtime behavior @@ -301,10 +266,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -44 | - - "{0}_{1}".format(1, *args) +45 - "{0}_{1}".format(1, *args) 45 + "{}_{}".format(1, *args) -46 | | note: This is an unsafe fix and may change runtime behavior @@ -320,10 +283,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -46 | - - "{0}_{1}".format(1, 2, *args) +47 - "{0}_{1}".format(1, 2, *args) 47 + "{}_{}".format(1, 2, *args) -48 | | note: This is an unsafe fix and may change runtime behavior @@ -339,10 +300,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -48 | - - "{0}_{1}".format(*args, 1, 2) +49 - "{0}_{1}".format(*args, 1, 2) 49 + "{}_{}".format(*args, 1, 2) -50 | | note: This is an unsafe fix and may change runtime behavior @@ -358,10 +317,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -50 | - - "{0}_{1}_{2}".format(1, **kwargs) +51 - "{0}_{1}_{2}".format(1, **kwargs) 51 + "{}_{}_{}".format(1, **kwargs) -52 | | note: This is an unsafe fix and may change runtime behavior @@ -377,10 +334,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -52 | - - "{0}_{1}_{2}".format(1, 2, **kwargs) +53 - "{0}_{1}_{2}".format(1, 2, **kwargs) 53 + "{}_{}_{}".format(1, 2, **kwargs) -54 | | note: This is an unsafe fix and may change runtime behavior @@ -396,10 +351,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -54 | - - "{0}_{1}_{2}".format(1, 2, 3, **kwargs) +55 - "{0}_{1}_{2}".format(1, 2, 3, **kwargs) 55 + "{}_{}_{}".format(1, 2, 3, **kwargs) -56 | | note: This is an unsafe fix and may change runtime behavior @@ -415,10 +368,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -56 | - - "{0}_{1}_{2}".format(1, 2, 3, *args, **kwargs) +57 - "{0}_{1}_{2}".format(1, 2, 3, *args, **kwargs) 57 + "{}_{}_{}".format(1, 2, 3, *args, **kwargs) -58 | | note: This is an unsafe fix and may change runtime behavior @@ -434,10 +385,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -58 | - - "{1}_{0}".format(1, 2, *args) +59 - "{1}_{0}".format(1, 2, *args) 59 + "{}_{}".format(2, 1, ) -60 | | note: This is an unsafe fix and may change runtime behavior @@ -453,10 +402,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -60 | - - "{1}_{0}".format(1, 2) +61 - "{1}_{0}".format(1, 2) 61 + "{}_{}".format(2, 1) -62 | | note: This is an unsafe fix and may change runtime behavior @@ -472,10 +419,8 @@ UP030 [*] Use implicit references for positional format fields | help: Remove explicit positional indices | -62 | - - r"\d{{1,2}} {0}".format(42) +63 - r"\d{{1,2}} {0}".format(42) 63 + r"\d{{1,2}} {}".format(42) -64 | | note: This is an unsafe fix and may change runtime behavior @@ -488,8 +433,7 @@ UP030 [*] Use implicit references for positional format fields | ^^^^^^^^^^^^^^^^^^^^^ help: Remove explicit positional indices | -64 | - - "{{{0}}}".format(123) +65 - "{{{0}}}".format(123) 65 + "{{{}}}".format(123) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP031_0.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP031_0.py.snap index 5251a71ac32d3..11b9223d940ce 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP031_0.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP031_0.py.snap @@ -12,10 +12,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -3 | # UP031 - - print('%s %s' % (a, b)) +4 - print('%s %s' % (a, b)) 4 + print('{} {}'.format(a, b)) -5 | | note: This is an unsafe fix and may change runtime behavior @@ -31,10 +29,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -5 | - - print('%s%s' % (a, b)) +6 - print('%s%s' % (a, b)) 6 + print('{}{}'.format(a, b)) -7 | | note: This is an unsafe fix and may change runtime behavior @@ -50,10 +46,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -7 | - - print("trivial" % ()) +8 - print("trivial" % ()) 8 + print("trivial".format()) -9 | | note: This is an unsafe fix and may change runtime behavior @@ -69,10 +63,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -9 | - - print("%s" % ("simple",)) +10 - print("%s" % ("simple",)) 10 + print("{}".format("simple")) -11 | | note: This is an unsafe fix and may change runtime behavior @@ -88,10 +80,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -11 | - - print("%s" % ("%s" % ("nested",),)) +12 - print("%s" % ("%s" % ("nested",),)) 12 + print("{}".format("%s" % ("nested",))) -13 | | note: This is an unsafe fix and may change runtime behavior @@ -107,10 +97,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -11 | - - print("%s" % ("%s" % ("nested",),)) +12 - print("%s" % ("%s" % ("nested",),)) 12 + print("%s" % ("{}".format("nested"),)) -13 | | note: This is an unsafe fix and may change runtime behavior @@ -126,10 +114,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -13 | - - print("%s%% percent" % (15,)) +14 - print("%s%% percent" % (15,)) 14 + print("{}% percent".format(15)) -15 | | note: This is an unsafe fix and may change runtime behavior @@ -145,10 +131,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -15 | - - print("%f" % (15,)) +16 - print("%f" % (15,)) 16 + print("{:f}".format(15)) -17 | | note: This is an unsafe fix and may change runtime behavior @@ -164,10 +148,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -17 | - - print("%.f" % (15,)) +18 - print("%.f" % (15,)) 18 + print("{:.0f}".format(15)) -19 | | note: This is an unsafe fix and may change runtime behavior @@ -183,10 +165,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -19 | - - print("%.3f" % (15,)) +20 - print("%.3f" % (15,)) 20 + print("{:.3f}".format(15)) -21 | | note: This is an unsafe fix and may change runtime behavior @@ -202,10 +182,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -21 | - - print("%3f" % (15,)) +22 - print("%3f" % (15,)) 22 + print("{:3f}".format(15)) -23 | | note: This is an unsafe fix and may change runtime behavior @@ -221,10 +199,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -23 | - - print("%-5f" % (5,)) +24 - print("%-5f" % (5,)) 24 + print("{:<5f}".format(5)) -25 | | note: This is an unsafe fix and may change runtime behavior @@ -240,10 +216,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -25 | - - print("%9f" % (5,)) +26 - print("%9f" % (5,)) 26 + print("{:9f}".format(5)) -27 | | note: This is an unsafe fix and may change runtime behavior @@ -259,10 +233,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -27 | - - print("%#o" % (123,)) +28 - print("%#o" % (123,)) 28 + print("{:#o}".format(123)) -29 | | note: This is an unsafe fix and may change runtime behavior @@ -278,10 +250,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -29 | - - print("brace {} %s" % (1,)) +30 - print("brace {} %s" % (1,)) 30 + print("brace {{}} {}".format(1)) -31 | | note: This is an unsafe fix and may change runtime behavior @@ -296,12 +266,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -32 | print(( - - "foo %s " - - "bar %s" % (x, y) -33 + "foo {} " +33 ~ "foo {} " 34 + "bar {}".format(x, y) -35 | )) | note: This is an unsafe fix and may change runtime behavior @@ -317,10 +283,9 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -37 | print( - - "%s" % ( -38 + "{}".format( -39 | "trailing comma", +38 ~ "{}".format( +39 + "trailing comma", +40 + ) | note: This is an unsafe fix and may change runtime behavior @@ -336,10 +301,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -42 | - - print("foo %s " % (x,)) +43 - print("foo %s " % (x,)) 43 + print("foo {} ".format(x)) -44 | | note: This is an unsafe fix and may change runtime behavior @@ -355,10 +318,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -44 | - - print("%(k)s" % {"k": "v"}) +45 - print("%(k)s" % {"k": "v"}) 45 + print("{k}".format(k="v")) -46 | | note: This is an unsafe fix and may change runtime behavior @@ -378,16 +339,10 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -46 | - - print("%(k)s" % { - - "k": "v", - - "i": "j" - - }) -47 + print("{k}".format( +47 ~ print("{k}".format( 48 + k="v", 49 + i="j", -50 + )) -51 | +50 ~ )) | note: This is an unsafe fix and may change runtime behavior @@ -403,10 +358,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -51 | - - print("%(to_list)s" % {"to_list": []}) +52 - print("%(to_list)s" % {"to_list": []}) 52 + print("{to_list}".format(to_list=[])) -53 | | note: This is an unsafe fix and may change runtime behavior @@ -422,10 +375,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -53 | - - print("%(k)s" % {"k": "v", "i": 1, "j": []}) +54 - print("%(k)s" % {"k": "v", "i": 1, "j": []}) 54 + print("{k}".format(k="v", i=1, j=[])) -55 | | note: This is an unsafe fix and may change runtime behavior @@ -441,10 +392,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -55 | - - print("%(ab)s" % {"a" "b": 1}) +56 - print("%(ab)s" % {"a" "b": 1}) 56 + print("{ab}".format(ab=1)) -57 | | note: This is an unsafe fix and may change runtime behavior @@ -457,10 +406,8 @@ UP031 [*] Use format specifiers instead of percent format | ^^^^^^^^^^^^^^^^^^^^^ help: Replace with format specifiers | -57 | - - print("%(a)s" % {"a" : 1}) +58 - print("%(a)s" % {"a" : 1}) 58 + print("{a}".format(a=1)) -59 | | note: This is an unsafe fix and may change runtime behavior @@ -475,12 +422,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -61 | print( - - "foo %(foo)s " - - "bar %(bar)s" % {"foo": x, "bar": y} -62 + "foo {foo} " +62 ~ "foo {foo} " 63 + "bar {bar}".format(foo=x, bar=y) -64 | ) | note: This is an unsafe fix and may change runtime behavior @@ -496,12 +439,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -67 | print( - - "foo %(foo)s " - - "bar %(bar)s" % {"foo": x, **bar} -68 + "foo {foo} " +68 ~ "foo {foo} " 69 + "bar {bar}".format(foo=x, **bar) -70 | ) | note: This is an unsafe fix and may change runtime behavior @@ -517,10 +456,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -71 | - - print("%s \N{snowman}" % (a,)) +72 - print("%s \N{snowman}" % (a,)) 72 + print("{} \N{snowman}".format(a)) -73 | | note: This is an unsafe fix and may change runtime behavior @@ -536,10 +473,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -73 | - - print("%(foo)s \N{snowman}" % {"foo": 1}) +74 - print("%(foo)s \N{snowman}" % {"foo": 1}) 74 + print("{foo} \N{snowman}".format(foo=1)) -75 | | note: This is an unsafe fix and may change runtime behavior @@ -555,10 +490,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -75 | - - print(("foo %s " "bar %s") % (x, y)) +76 - print(("foo %s " "bar %s") % (x, y)) 76 + print(("foo {} " "bar {}").format(x, y)) -77 | | note: This is an unsafe fix and may change runtime behavior @@ -573,10 +506,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -78 | # Single-value expressions - - print('Hello %s' % "World") +79 - print('Hello %s' % "World") 79 + print('Hello {}'.format("World")) -80 | print('Hello %s' % f"World") | note: This is an unsafe fix and may change runtime behavior @@ -592,10 +523,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -79 | print('Hello %s' % "World") - - print('Hello %s' % f"World") +80 - print('Hello %s' % f"World") 80 + print('Hello {}'.format(f"World")) -81 | print('Hello %s (%s)' % bar) | note: This is an unsafe fix and may change runtime behavior @@ -611,10 +540,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -80 | print('Hello %s' % f"World") - - print('Hello %s (%s)' % bar) +81 - print('Hello %s (%s)' % bar) 81 + print('Hello {} ({})'.format(*bar)) -82 | print('Hello %s (%s)' % bar.baz) | note: This is an unsafe fix and may change runtime behavior @@ -630,10 +557,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -81 | print('Hello %s (%s)' % bar) - - print('Hello %s (%s)' % bar.baz) +82 - print('Hello %s (%s)' % bar.baz) 82 + print('Hello {} ({})'.format(*bar.baz)) -83 | print('Hello %s (%s)' % bar['bop']) | note: This is an unsafe fix and may change runtime behavior @@ -649,10 +574,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -82 | print('Hello %s (%s)' % bar.baz) - - print('Hello %s (%s)' % bar['bop']) +83 - print('Hello %s (%s)' % bar['bop']) 83 + print('Hello {} ({})'.format(*bar['bop'])) -84 | print('Hello %(arg)s' % bar) | note: This is an unsafe fix and may change runtime behavior @@ -668,10 +591,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -83 | print('Hello %s (%s)' % bar['bop']) - - print('Hello %(arg)s' % bar) +84 - print('Hello %(arg)s' % bar) 84 + print('Hello {arg}'.format(**bar)) -85 | print('Hello %(arg)s' % bar.baz) | note: This is an unsafe fix and may change runtime behavior @@ -686,10 +607,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -84 | print('Hello %(arg)s' % bar) - - print('Hello %(arg)s' % bar.baz) +85 - print('Hello %(arg)s' % bar.baz) 85 + print('Hello {arg}'.format(**bar.baz)) -86 | print('Hello %(arg)s' % bar['bop']) | note: This is an unsafe fix and may change runtime behavior @@ -705,10 +624,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -85 | print('Hello %(arg)s' % bar.baz) - - print('Hello %(arg)s' % bar['bop']) +86 - print('Hello %(arg)s' % bar['bop']) 86 + print('Hello {arg}'.format(**bar['bop'])) -87 | | note: This is an unsafe fix and may change runtime behavior @@ -726,14 +643,10 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -89 | ( - - "foo %s " - - "bar %s" - - ) % (x, y) +89 + ( 90 + "foo {} " 91 + "bar {}" 92 + ).format(x, y) -93 | | note: This is an unsafe fix and may change runtime behavior @@ -752,14 +665,10 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -94 | ( - - "foo %(foo)s " - - "bar %(bar)s" - - ) % {"foo": x, "bar": y} +94 + ( 95 + "foo {foo} " 96 + "bar {bar}" 97 + ).format(foo=x, bar=y) -98 | | note: This is an unsafe fix and may change runtime behavior @@ -774,11 +683,9 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -99 | ( - - """foo %s""" - - % (x,) +100 - """foo %s""" +101 - % (x,) 100 + """foo {}""".format(x) -101 | ) | note: This is an unsafe fix and may change runtime behavior @@ -795,13 +702,9 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -105 | """ - - foo %s - - """ - - % (x,) +105 ~ """ 106 + foo {} 107 + """.format(x) -108 | ) | note: This is an unsafe fix and may change runtime behavior @@ -816,10 +719,9 @@ UP031 [*] Use format specifiers instead of percent format | |_^ help: Replace with format specifiers | -110 | - - "%s" % ( 111 + "{}".format( -112 | x, # comment +112 + x, # comment +113 + ) | note: This is an unsafe fix and may change runtime behavior @@ -838,10 +740,11 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -115 | - - path = "%s-%s-%s.pem" % ( -116 + path = "{}-{}-{}.pem".format( -117 | safe_domain_name(cn), # common name, which should be filename safe because it is IDNA-encoded, but in case of a malformed cert make sure it's ok to use as a filename +116 ~ path = "{}-{}-{}.pem".format( +117 + safe_domain_name(cn), # common name, which should be filename safe because it is IDNA-encoded, but in case of a malformed cert make sure it's ok to use as a filename +118 + cert.not_valid_after.date().isoformat().replace("-", ""), # expiration date +119 + hexlify(cert.fingerprint(hashes.SHA256())).decode("ascii")[0:8], # fingerprint prefix +120 + ) | note: This is an unsafe fix and may change runtime behavior @@ -856,10 +759,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -122 | # UP031 (no longer false negatives; now offer potentially unsafe fixes) - - 'Hello %s' % bar +123 - 'Hello %s' % bar 123 + 'Hello {}'.format(bar) -124 | | note: This is an unsafe fix and may change runtime behavior @@ -875,10 +776,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -124 | - - 'Hello %s' % bar.baz +125 - 'Hello %s' % bar.baz 125 + 'Hello {}'.format(bar.baz) -126 | | note: This is an unsafe fix and may change runtime behavior @@ -894,10 +793,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -126 | - - 'Hello %s' % bar['bop'] +127 - 'Hello %s' % bar['bop'] 127 + 'Hello {}'.format(bar['bop']) -128 | | note: This is an unsafe fix and may change runtime behavior @@ -913,10 +810,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -130 | # Refer: https://github.com/astral-sh/ruff/issues/11736 - - x: "'%s + %s' % (1, 2)" +131 - x: "'%s + %s' % (1, 2)" 131 + x: "'{} + {}'.format(1, 2)" -132 | | note: This is an unsafe fix and may change runtime behavior @@ -931,10 +826,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -133 | # See: https://github.com/astral-sh/ruff/issues/12421 - - print("%.2X" % 1) +134 - print("%.2X" % 1) 134 + print("{:02X}".format(1)) -135 | print("%.02X" % 1) | note: This is an unsafe fix and may change runtime behavior @@ -950,10 +843,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -134 | print("%.2X" % 1) - - print("%.02X" % 1) +135 - print("%.02X" % 1) 135 + print("{:02X}".format(1)) -136 | print("%02X" % 1) | note: This is an unsafe fix and may change runtime behavior @@ -969,10 +860,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -135 | print("%.02X" % 1) - - print("%02X" % 1) +136 - print("%02X" % 1) 136 + print("{:02X}".format(1)) -137 | print("%.00002X" % 1) | note: This is an unsafe fix and may change runtime behavior @@ -987,10 +876,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -136 | print("%02X" % 1) - - print("%.00002X" % 1) +137 - print("%.00002X" % 1) 137 + print("{:02X}".format(1)) -138 | print("%.20X" % 1) | note: This is an unsafe fix and may change runtime behavior @@ -1006,10 +893,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -137 | print("%.00002X" % 1) - - print("%.20X" % 1) +138 - print("%.20X" % 1) 138 + print("{:020X}".format(1)) -139 | | note: This is an unsafe fix and may change runtime behavior @@ -1024,10 +909,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -139 | - - print("%2X" % 1) +140 - print("%2X" % 1) 140 + print("{:2X}".format(1)) -141 | print("%02X" % 1) | note: This is an unsafe fix and may change runtime behavior @@ -1042,10 +925,8 @@ UP031 [*] Use format specifiers instead of percent format | help: Replace with format specifiers | -140 | print("%2X" % 1) - - print("%02X" % 1) +141 - print("%02X" % 1) 141 + print("{:02X}".format(1)) -142 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP032_0.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP032_0.py.snap index 774ff321e9809..1eb18b4be8a4e 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP032_0.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP032_0.py.snap @@ -13,10 +13,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -4 | - - "{} {}".format(a, b) +5 - "{} {}".format(a, b) 5 + f"{a} {b}" -6 | | UP032 [*] Use f-string instead of `format` call @@ -31,10 +29,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -6 | - - "{1} {0}".format(a, b) +7 - "{1} {0}".format(a, b) 7 + f"{b} {a}" -8 | | UP032 [*] Use f-string instead of `format` call @@ -48,12 +44,10 @@ UP032 [*] Use f-string instead of `format` call 11 | "{x.y}".format(x=z) | help: Convert to f-string - | -8 | - - "{0} {1} {0}".format(a, b) -9 + f"{a} {b} {a}" -10 | - | + | +9 - "{0} {1} {0}".format(a, b) +9 + f"{a} {b} {a}" + | UP032 [*] Use f-string instead of `format` call --> UP032_0.py:11:1 @@ -67,10 +61,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -10 | - - "{x.y}".format(x=z) +11 - "{x.y}".format(x=z) 11 + f"{z.y}" -12 | | UP032 [*] Use f-string instead of `format` call @@ -85,10 +77,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -12 | - - "{x} {y} {x}".format(x=a, y=b) +13 - "{x} {y} {x}".format(x=a, y=b) 13 + f"{a} {b} {a}" -14 | | UP032 [*] Use f-string instead of `format` call @@ -103,10 +93,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -14 | - - "{.x} {.y}".format(a, b) +15 - "{.x} {.y}".format(a, b) 15 + f"{a.x} {b.y}" -16 | | UP032 [*] Use f-string instead of `format` call @@ -121,10 +109,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -16 | - - "{} {}".format(a.b, c.d) +17 - "{} {}".format(a.b, c.d) 17 + f"{a.b} {c.d}" -18 | | UP032 [*] Use f-string instead of `format` call @@ -139,10 +125,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -18 | - - "{}".format(a()) +19 - "{}".format(a()) 19 + f"{a()}" -20 | | UP032 [*] Use f-string instead of `format` call @@ -157,10 +141,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -20 | - - "{}".format(a.b()) +21 - "{}".format(a.b()) 21 + f"{a.b()}" -22 | | UP032 [*] Use f-string instead of `format` call @@ -175,10 +157,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -22 | - - "{}".format(a.b().c()) +23 - "{}".format(a.b().c()) 23 + f"{a.b().c()}" -24 | | UP032 [*] Use f-string instead of `format` call @@ -193,10 +173,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -24 | - - "hello {}!".format(name) +25 - "hello {}!".format(name) 25 + f"hello {name}!" -26 | | UP032 [*] Use f-string instead of `format` call @@ -211,10 +189,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -26 | - - "{}{b}{}".format(a, c, b=b) +27 - "{}{b}{}".format(a, c, b=b) 27 + f"{a}{b}{c}" -28 | | UP032 [*] Use f-string instead of `format` call @@ -229,10 +205,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -28 | - - "{}".format(0x0) +29 - "{}".format(0x0) 29 + f"{0x0}" -30 | | UP032 [*] Use f-string instead of `format` call @@ -247,10 +221,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -30 | - - "{} {}".format(a, b) +31 - "{} {}".format(a, b) 31 + f"{a} {b}" -32 | | UP032 [*] Use f-string instead of `format` call @@ -265,10 +237,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -32 | - - """{} {}""".format(a, b) +33 - """{} {}""".format(a, b) 33 + f"""{a} {b}""" -34 | | UP032 [*] Use f-string instead of `format` call @@ -283,10 +253,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -34 | - - "foo{}".format(1) +35 - "foo{}".format(1) 35 + f"foo{1}" -36 | | UP032 [*] Use f-string instead of `format` call @@ -301,10 +269,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -36 | - - r"foo{}".format(1) +37 - r"foo{}".format(1) 37 + rf"foo{1}" -38 | | UP032 [*] Use f-string instead of `format` call @@ -319,10 +285,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -38 | - - x = "{a}".format(a=1) +39 - x = "{a}".format(a=1) 39 + x = f"{1}" -40 | | UP032 [*] Use f-string instead of `format` call @@ -337,10 +301,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -40 | - - print("foo {} ".format(x)) +41 - print("foo {} ".format(x)) 41 + print(f"foo {x} ") -42 | | UP032 [*] Use f-string instead of `format` call @@ -355,10 +317,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -42 | - - "{a[b]}".format(a=a) +43 - "{a[b]}".format(a=a) 43 + f"{a['b']}" -44 | | UP032 [*] Use f-string instead of `format` call @@ -373,10 +333,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -44 | - - "{a.a[b]}".format(a=a) +45 - "{a.a[b]}".format(a=a) 45 + f"{a.a['b']}" -46 | | UP032 [*] Use f-string instead of `format` call @@ -391,10 +349,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -46 | - - "{}{{}}{}".format(escaped, y) +47 - "{}{{}}{}".format(escaped, y) 47 + f"{escaped}{{}}{y}" -48 | | UP032 [*] Use f-string instead of `format` call @@ -409,10 +365,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -48 | - - "{}".format(a) +49 - "{}".format(a) 49 + f"{a}" -50 | | UP032 [*] Use f-string instead of `format` call @@ -427,10 +381,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -50 | - - '({}={{0!e}})'.format(a) +51 - '({}={{0!e}})'.format(a) 51 + f'({a}={{0!e}})' -52 | | UP032 [*] Use f-string instead of `format` call @@ -445,10 +397,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -52 | - - "{[b]}".format(a) +53 - "{[b]}".format(a) 53 + f"{a['b']}" -54 | | UP032 [*] Use f-string instead of `format` call @@ -463,10 +413,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -54 | - - '{[b]}'.format(a) +55 - '{[b]}'.format(a) 55 + f'{a["b"]}' -56 | | UP032 [*] Use f-string instead of `format` call @@ -481,10 +429,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -56 | - - """{[b]}""".format(a) +57 - """{[b]}""".format(a) 57 + f"""{a["b"]}""" -58 | | UP032 [*] Use f-string instead of `format` call @@ -499,10 +445,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -58 | - - '''{[b]}'''.format(a) +59 - '''{[b]}'''.format(a) 59 + f'''{a["b"]}''' -60 | | UP032 [*] Use f-string instead of `format` call @@ -519,12 +463,10 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -60 | - - "{}".format( - - 1 - - ) +61 - "{}".format( +62 - 1 +63 - ) 61 + f"{1}" -62 | | UP032 [*] Use f-string instead of `format` call @@ -541,12 +483,10 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -64 | - - "123456789 {}".format( - - 1111111111111111111111111111111111111111111111111111111111111111111111111, - - ) +65 - "123456789 {}".format( +66 - 1111111111111111111111111111111111111111111111111111111111111111111111111, +67 - ) 65 + f"123456789 {1111111111111111111111111111111111111111111111111111111111111111111111111}" -66 | | UP032 [*] Use f-string instead of `format` call @@ -563,13 +503,9 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -68 | 69 + f""" 70 + {1} -71 | """ - - {} - - """.format(1) -72 | +71 + """ | UP032 [*] Use f-string instead of `format` call @@ -589,16 +525,9 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -72 | - - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = """ - - {} - - """.format( - - 111111 - - ) -73 + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = f""" +73 ~ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = f""" 74 + {111111} 75 + """ -76 | | UP032 [*] Use f-string instead of `format` call @@ -613,10 +542,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -78 | - - "{a}" "{b}".format(a=1, b=1) +79 - "{a}" "{b}".format(a=1, b=1) 79 + f"{1}" f"{1}" -80 | | UP032 [*] Use f-string instead of `format` call @@ -634,14 +561,10 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -81 | ( - - "{a}" - - "{b}" - - ).format(a=1, b=1) +81 + ( 82 + f"{1}" 83 + f"{1}" 84 + ) -85 | | UP032 [*] Use f-string instead of `format` call @@ -661,16 +584,10 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -86 | ( - - "{a}" - - "" - - "{b}" - - "" - - ).format(a=1, b=1) +86 + ( 87 + f"{1}" 88 + f"{1}" 89 + ) -90 | | UP032 [*] Use f-string instead of `format` call @@ -690,17 +607,14 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -95 | # comment - - "{a}" -96 + f"{1}" -97 | # comment - - "{b}" -98 + f"{1}" -99 | ) -100 | # comment - - .format(a=1, b=1) + 94 ~ ( + 95 + # comment + 96 + f"{1}" + 97 + # comment + 98 + f"{1}" + 99 + ) +100 + # comment 101 + -102 | ) | UP032 [*] Use f-string instead of `format` call @@ -715,13 +629,10 @@ UP032 [*] Use f-string instead of `format` call | |_____________^ help: Convert to f-string | -104 | ( - - "{a}" +104 + ( 105 + f"{1}" -106 | "b" - - ).format(a=1) +106 + "b" 107 + ) -108 | | UP032 [*] Use f-string instead of `format` call @@ -732,10 +643,8 @@ UP032 [*] Use f-string instead of `format` call | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Convert to f-string | -110 | def d(osname, version, release): - - return"{}-{}.{}".format(osname, version, release) +111 - return"{}-{}.{}".format(osname, version, release) 111 + return f"{osname}-{version}.{release}" -112 | | UP032 [*] Use f-string instead of `format` call @@ -746,10 +655,8 @@ UP032 [*] Use f-string instead of `format` call | ^^^^^^^^^^^^^^ help: Convert to f-string | -114 | def e(): - - yield"{}".format(1) +115 - yield"{}".format(1) 115 + yield f"{1}" -116 | | UP032 [*] Use f-string instead of `format` call @@ -759,10 +666,8 @@ UP032 [*] Use f-string instead of `format` call | ^^^^^^^^^^^^^^ help: Convert to f-string | -117 | - - assert"{}".format(1) +118 - assert"{}".format(1) 118 + assert f"{1}" -119 | | UP032 [*] Use f-string instead of `format` call @@ -773,10 +678,8 @@ UP032 [*] Use f-string instead of `format` call | ^^^^^^^^^^^^^^^^^^^^ help: Convert to f-string | -121 | async def c(): - - return "{}".format(await 3) +122 - return "{}".format(await 3) 122 + return f"{await 3}" -123 | | UP032 [*] Use f-string instead of `format` call @@ -787,10 +690,8 @@ UP032 [*] Use f-string instead of `format` call | ^^^^^^^^^^^^^^^^^^^^^^^^ help: Convert to f-string | -125 | async def c(): - - return "{}".format(1 + await 3) +126 - return "{}".format(1 + await 3) 126 + return f"{1 + await 3}" -127 | | UP032 [*] Use f-string instead of `format` call @@ -803,10 +704,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -128 | - - "{}".format(1 * 2) +129 - "{}".format(1 * 2) 129 + f"{1 * 2}" -130 | | UP032 [*] Use f-string instead of `format` call @@ -821,10 +720,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -134 | - - "\N{snowman} {}".format(a) +135 - "\N{snowman} {}".format(a) 135 + f"\N{snowman} {a}" -136 | | UP032 [*] Use f-string instead of `format` call @@ -841,12 +738,10 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -158 | - - "123456789 {}".format( - - 11111111111111111111111111111111111111111111111111111111111111111111111111, - - ) +159 - "123456789 {}".format( +160 - 11111111111111111111111111111111111111111111111111111111111111111111111111, +161 - ) 159 + f"123456789 {11111111111111111111111111111111111111111111111111111111111111111111111111}" -160 | | UP032 [*] Use f-string instead of `format` call @@ -869,21 +764,11 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -162 | 163 + f""" 164 + {1} 165 + {2} 166 + {111111111111111111111111111111111111111111111111111111111111111111111111111111111111111} -167 | """ - - {} - - {} - - {} - - """.format( - - 1, - - 2, - - 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111, - - ) -168 | +167 + """ | UP032 [*] Use f-string instead of `format` call @@ -902,14 +787,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -172 | - - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = """{} - - """.format( - - 111111 - - ) -173 + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = f"""{111111} +173 ~ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = f"""{111111} 174 + """ -175 | | UP032 Use f-string instead of `format` call @@ -935,10 +814,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -207 | # existing line length, so it's fine. - - "".format(self.internal_ids, self.external_ids, self.properties, self.tags, self.others) +208 - "".format(self.internal_ids, self.external_ids, self.properties, self.tags, self.others) 208 + f"" -209 | | UP032 [*] Use f-string instead of `format` call @@ -954,11 +831,9 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -210 | # When fixing, trim the trailing empty string. - - raise ValueError("Conflicting configuration dicts: {!r} {!r}" - - "".format(new_dict, d)) +211 - raise ValueError("Conflicting configuration dicts: {!r} {!r}" +212 - "".format(new_dict, d)) 211 + raise ValueError(f"Conflicting configuration dicts: {new_dict!r} {d!r}") -212 | | UP032 [*] Use f-string instead of `format` call @@ -974,12 +849,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -214 | # When fixing, trim the trailing empty string. - - raise ValueError("Conflicting configuration dicts: {!r} {!r}" - - .format(new_dict, d)) -215 + raise ValueError(f"Conflicting configuration dicts: {new_dict!r} {d!r}" -216 + ) -217 | +215 ~ raise ValueError(f"Conflicting configuration dicts: {new_dict!r} {d!r}" +216 ~ ) | UP032 [*] Use f-string instead of `format` call @@ -993,11 +864,9 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -218 | raise ValueError( - - "Conflicting configuration dicts: {!r} {!r}" - - "".format(new_dict, d) +219 - "Conflicting configuration dicts: {!r} {!r}" +220 - "".format(new_dict, d) 219 + f"Conflicting configuration dicts: {new_dict!r} {d!r}" -220 | ) | UP032 [*] Use f-string instead of `format` call @@ -1012,11 +881,9 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -223 | raise ValueError( - - "Conflicting configuration dicts: {!r} {!r}" - - "".format(new_dict, d) +224 - "Conflicting configuration dicts: {!r} {!r}" +225 - "".format(new_dict, d) 224 + f"Conflicting configuration dicts: {new_dict!r} {d!r}" -225 | | UP032 [*] Use f-string instead of `format` call @@ -1033,13 +900,10 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -230 | ( +230 + ( 231 + f"{a}" -232 | "{}" - - "{{}}" - - ).format(a) +232 + "{}" 233 + ) -234 | | UP032 [*] Use f-string instead of `format` call @@ -1051,10 +915,8 @@ UP032 [*] Use f-string instead of `format` call | ^^^^^^^^^^^^^^^^^^^^^^^ help: Convert to f-string | -234 | - - ("{}" "{{}}").format(a) +235 - ("{}" "{{}}").format(a) 235 + (f"{a}" "{}") -236 | | UP032 [*] Use f-string instead of `format` call @@ -1071,14 +933,10 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -239 | ( - - "{}" - - "{{{}}}" - - ).format(a, b) +239 + ( 240 + f"{a}" 241 + f"{{{b}}}" 242 + ) -243 | | UP032 [*] Use f-string instead of `format` call @@ -1093,10 +951,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -243 | - - ("{}" "{{{}}}").format(a, b) +244 - ("{}" "{{{}}}").format(a, b) 244 + (f"{a}" f"{{{b}}}") -245 | | UP032 [*] Use f-string instead of `format` call @@ -1110,10 +966,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -246 | # The dictionary should be parenthesized. - - "{}".format({0: 1}[0]) +247 - "{}".format({0: 1}[0]) 247 + f"{({0: 1}[0])}" -248 | | UP032 [*] Use f-string instead of `format` call @@ -1127,10 +981,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -249 | # The dictionary should be parenthesized. - - "{}".format({0: 1}.bar) +250 - "{}".format({0: 1}.bar) 250 + f"{({0: 1}.bar)}" -251 | | UP032 [*] Use f-string instead of `format` call @@ -1144,10 +996,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -252 | # The dictionary should be parenthesized. - - "{}".format({0: 1}()) +253 - "{}".format({0: 1}()) 253 + f"{({0: 1}())}" -254 | | UP032 [*] Use f-string instead of `format` call @@ -1161,10 +1011,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -259 | # The string _should_ be converted, since the function call is repeated in the arguments. - - "{0} {1}".format(foo(), foo()) +260 - "{0} {1}".format(foo(), foo()) 260 + f"{foo()} {foo()}" -261 | | UP032 [*] Use f-string instead of `format` call @@ -1178,10 +1026,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -262 | # The call should be removed, but the string itself should remain. - - ''.format(self.project) +263 - ''.format(self.project) 263 + '' -264 | | UP032 [*] Use f-string instead of `format` call @@ -1195,10 +1041,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -265 | # The call should be removed, but the string itself should remain. - - "".format(self.project) +266 - "".format(self.project) 266 + "" -267 | | UP032 [*] Use f-string instead of `format` call @@ -1213,10 +1057,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -269 | # Refer: https://github.com/astral-sh/ruff/issues/11736 - - x: "'{} + {}'.format(x, y)" +270 - x: "'{} + {}'.format(x, y)" 270 + x: "f'{x} + {y}'" -271 | | UP032 [*] Use f-string instead of `format` call @@ -1230,10 +1072,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -275 | number = 0 - - string = "{}".format(number := number + 1) +276 - string = "{}".format(number := number + 1) 276 + string = f"{(number := number + 1)}" -277 | print(string) | UP032 [*] Use f-string instead of `format` call @@ -1247,10 +1087,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -279 | # Unicode escape - - "\N{angle}AOB = {angle}°".format(angle=180) +280 - "\N{angle}AOB = {angle}°".format(angle=180) 280 + f"\N{angle}AOB = {180}°" -281 | | UP032 [*] Use f-string instead of `format` call @@ -1261,7 +1099,6 @@ UP032 [*] Use f-string instead of `format` call | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Convert to f-string | -282 | # Raw string with \N{...} - - r"\N{angle}AOB = {angle}°".format(angle=180) +283 - r"\N{angle}AOB = {angle}°".format(angle=180) 283 + rf"\N{180}AOB = {180}°" | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP032_1.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP032_1.py.snap index 0480f71b84e28..1e1ae2532ec1d 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP032_1.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP032_1.py.snap @@ -8,6 +8,6 @@ UP032 [*] Use f-string instead of `format` call | ^^^^^^^^^^^^^^^^^^^^ help: Convert to f-string | - - "{} {}".format(a, b) # Intentionally at start-of-file, to ensure graceful handling. +1 - "{} {}".format(a, b) # Intentionally at start-of-file, to ensure graceful handling. 1 + f"{a} {b}" # Intentionally at start-of-file, to ensure graceful handling. | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP032_2.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP032_2.py.snap index 3c6fa7aee74e8..f1c19ed1a50bb 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP032_2.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP032_2.py.snap @@ -12,10 +12,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -1 | # Errors - - "{.real}".format(1) +2 - "{.real}".format(1) 2 + f"{(1).real}" -3 | "{0.real}".format(1) | UP032 [*] Use f-string instead of `format` call @@ -29,10 +27,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -2 | "{.real}".format(1) - - "{0.real}".format(1) +3 - "{0.real}".format(1) 3 + f"{(1).real}" -4 | "{a.real}".format(a=1) | UP032 [*] Use f-string instead of `format` call @@ -47,10 +43,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -3 | "{0.real}".format(1) - - "{a.real}".format(a=1) +4 - "{a.real}".format(a=1) 4 + f"{(1).real}" -5 | | UP032 [*] Use f-string instead of `format` call @@ -65,10 +59,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -5 | - - "{.real}".format(1.0) +6 - "{.real}".format(1.0) 6 + f"{1.0.real}" -7 | "{0.real}".format(1.0) | UP032 [*] Use f-string instead of `format` call @@ -81,10 +73,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -6 | "{.real}".format(1.0) - - "{0.real}".format(1.0) +7 - "{0.real}".format(1.0) 7 + f"{1.0.real}" -8 | "{a.real}".format(a=1.0) | UP032 [*] Use f-string instead of `format` call @@ -99,10 +89,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -7 | "{0.real}".format(1.0) - - "{a.real}".format(a=1.0) +8 - "{a.real}".format(a=1.0) 8 + f"{1.0.real}" -9 | | UP032 [*] Use f-string instead of `format` call @@ -117,10 +105,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -9 | - - "{.real}".format(1j) +10 - "{.real}".format(1j) 10 + f"{1j.real}" -11 | "{0.real}".format(1j) | UP032 [*] Use f-string instead of `format` call @@ -133,10 +119,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -10 | "{.real}".format(1j) - - "{0.real}".format(1j) +11 - "{0.real}".format(1j) 11 + f"{1j.real}" -12 | "{a.real}".format(a=1j) | UP032 [*] Use f-string instead of `format` call @@ -151,10 +135,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -11 | "{0.real}".format(1j) - - "{a.real}".format(a=1j) +12 - "{a.real}".format(a=1j) 12 + f"{1j.real}" -13 | | UP032 [*] Use f-string instead of `format` call @@ -169,10 +151,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -13 | - - "{.real}".format(0b01) +14 - "{.real}".format(0b01) 14 + f"{0b01.real}" -15 | "{0.real}".format(0b01) | UP032 [*] Use f-string instead of `format` call @@ -185,10 +165,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -14 | "{.real}".format(0b01) - - "{0.real}".format(0b01) +15 - "{0.real}".format(0b01) 15 + f"{0b01.real}" -16 | "{a.real}".format(a=0b01) | UP032 [*] Use f-string instead of `format` call @@ -203,10 +181,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -15 | "{0.real}".format(0b01) - - "{a.real}".format(a=0b01) +16 - "{a.real}".format(a=0b01) 16 + f"{0b01.real}" -17 | | UP032 [*] Use f-string instead of `format` call @@ -221,10 +197,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -17 | - - "{}".format(1 + 2) +18 - "{}".format(1 + 2) 18 + f"{1 + 2}" -19 | "{}".format([1, 2]) | UP032 [*] Use f-string instead of `format` call @@ -238,10 +212,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -18 | "{}".format(1 + 2) - - "{}".format([1, 2]) +19 - "{}".format([1, 2]) 19 + f"{[1, 2]}" -20 | "{}".format({1, 2}) | UP032 [*] Use f-string instead of `format` call @@ -256,10 +228,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -19 | "{}".format([1, 2]) - - "{}".format({1, 2}) +20 - "{}".format({1, 2}) 20 + f"{({1, 2})}" -21 | "{}".format({1: 2, 3: 4}) | UP032 [*] Use f-string instead of `format` call @@ -273,10 +243,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -20 | "{}".format({1, 2}) - - "{}".format({1: 2, 3: 4}) +21 - "{}".format({1: 2, 3: 4}) 21 + f"{({1: 2, 3: 4})}" -22 | "{}".format((i for i in range(2))) | UP032 [*] Use f-string instead of `format` call @@ -291,10 +259,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -21 | "{}".format({1: 2, 3: 4}) - - "{}".format((i for i in range(2))) +22 - "{}".format((i for i in range(2))) 22 + f"{(i for i in range(2))}" -23 | | UP032 [*] Use f-string instead of `format` call @@ -309,10 +275,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -23 | - - "{.real}".format(1 + 2) +24 - "{.real}".format(1 + 2) 24 + f"{(1 + 2).real}" -25 | "{.real}".format([1, 2]) | UP032 [*] Use f-string instead of `format` call @@ -326,10 +290,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -24 | "{.real}".format(1 + 2) - - "{.real}".format([1, 2]) +25 - "{.real}".format([1, 2]) 25 + f"{[1, 2].real}" -26 | "{.real}".format({1, 2}) | UP032 [*] Use f-string instead of `format` call @@ -344,10 +306,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -25 | "{.real}".format([1, 2]) - - "{.real}".format({1, 2}) +26 - "{.real}".format({1, 2}) 26 + f"{({1, 2}).real}" -27 | "{.real}".format({1: 2, 3: 4}) | UP032 [*] Use f-string instead of `format` call @@ -361,10 +321,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -26 | "{.real}".format({1, 2}) - - "{.real}".format({1: 2, 3: 4}) +27 - "{.real}".format({1: 2, 3: 4}) 27 + f"{({1: 2, 3: 4}).real}" -28 | "{}".format((i for i in range(2))) | UP032 [*] Use f-string instead of `format` call @@ -379,10 +337,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -27 | "{.real}".format({1: 2, 3: 4}) - - "{}".format((i for i in range(2))) +28 - "{}".format((i for i in range(2))) 28 + f"{(i for i in range(2))}" -29 | | UP032 [*] Use f-string instead of `format` call @@ -396,10 +352,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -30 | # https://github.com/astral-sh/ruff/issues/21017 - - "{.real}".format(1_2) +31 - "{.real}".format(1_2) 31 + f"{(1_2).real}" -32 | "{0.real}".format(1_2) | UP032 [*] Use f-string instead of `format` call @@ -413,10 +367,8 @@ UP032 [*] Use f-string instead of `format` call | help: Convert to f-string | -31 | "{.real}".format(1_2) - - "{0.real}".format(1_2) +32 - "{0.real}".format(1_2) 32 + f"{(1_2).real}" -33 | "{a.real}".format(a=1_2) | UP032 [*] Use f-string instead of `format` call @@ -428,7 +380,6 @@ UP032 [*] Use f-string instead of `format` call | ^^^^^^^^^^^^^^^^^^^^^^^^ help: Convert to f-string | -32 | "{0.real}".format(1_2) - - "{a.real}".format(a=1_2) +33 - "{a.real}".format(a=1_2) 33 + f"{(1_2).real}" | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP033_0.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP033_0.py.snap index 5e37754c60b7b..f1a6b553194b2 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP033_0.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP033_0.py.snap @@ -11,10 +11,10 @@ UP033 [*] Use `@functools.cache` instead of `@functools.lru_cache(maxsize=None)` | help: Rewrite with `@functools.cache | +1 ~ import functools +2 | 3 | - - @functools.lru_cache(maxsize=None) -4 + @functools.cache -5 | def fixme(): +4 ~ @functools.cache | UP033 [*] Use `@functools.cache` instead of `@functools.lru_cache(maxsize=None)` @@ -28,10 +28,11 @@ UP033 [*] Use `@functools.cache` instead of `@functools.lru_cache(maxsize=None)` | help: Rewrite with `@functools.cache | -9 | @other_decorator - - @functools.lru_cache(maxsize=None) -10 + @functools.cache -11 | def fixme(): + 1 ~ import functools + 2 | + … + 9 | @other_decorator +10 ~ @functools.cache | UP033 [*] Use `@functools.cache` instead of `@functools.lru_cache(maxsize=None)` @@ -44,10 +45,11 @@ UP033 [*] Use `@functools.cache` instead of `@functools.lru_cache(maxsize=None)` | help: Rewrite with `@functools.cache | + 1 ~ import functools + 2 | + … 14 | - - @functools.lru_cache(maxsize=None) -15 + @functools.cache -16 | @other_decorator +15 ~ @functools.cache | UP033 [*] Use `@functools.cache` instead of `@functools.lru_cache(maxsize=None)` @@ -63,11 +65,10 @@ UP033 [*] Use `@functools.cache` instead of `@functools.lru_cache(maxsize=None)` | help: Rewrite with `@functools.cache | + 1 ~ import functools + 2 | + … 49 | - - @functools.lru_cache( - - maxsize=None, # text - - ) -50 + @functools.cache -51 | def fixme_unsafe(): +50 ~ @functools.cache | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP033_1.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP033_1.py.snap index 4c75b0162ae1b..52e7297a3901c 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP033_1.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP033_1.py.snap @@ -11,13 +11,10 @@ UP033 [*] Use `@functools.cache` instead of `@functools.lru_cache(maxsize=None)` | help: Rewrite with `@functools.cache | - - from functools import lru_cache -1 + from functools import lru_cache, cache +1 ~ from functools import lru_cache, cache 2 | 3 | - - @lru_cache(maxsize=None) -4 + @cache -5 | def fixme(): +4 ~ @cache | UP033 [*] Use `@functools.cache` instead of `@functools.lru_cache(maxsize=None)` @@ -31,14 +28,11 @@ UP033 [*] Use `@functools.cache` instead of `@functools.lru_cache(maxsize=None)` | help: Rewrite with `@functools.cache | - - from functools import lru_cache -1 + from functools import lru_cache, cache -2 | --------------------------------------------------------------------------------- -9 | @other_decorator - - @lru_cache(maxsize=None) -10 + @cache -11 | def fixme(): + 1 ~ from functools import lru_cache, cache + 2 | + … + 9 | @other_decorator +10 ~ @cache | UP033 [*] Use `@functools.cache` instead of `@functools.lru_cache(maxsize=None)` @@ -51,12 +45,9 @@ UP033 [*] Use `@functools.cache` instead of `@functools.lru_cache(maxsize=None)` | help: Rewrite with `@functools.cache | - - from functools import lru_cache -1 + from functools import lru_cache, cache -2 | --------------------------------------------------------------------------------- + 1 ~ from functools import lru_cache, cache + 2 | + … 14 | - - @lru_cache(maxsize=None) -15 + @cache -16 | @other_decorator +15 ~ @cache | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP034.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP034.py.snap index aec8e312733b9..fb4a809acbbd7 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP034.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP034.py.snap @@ -12,10 +12,8 @@ UP034 [*] Avoid extraneous parentheses | help: Remove extraneous parentheses | -1 | # UP034 - - print(("foo")) +2 - print(("foo")) 2 + print("foo") -3 | | UP034 [*] Avoid extraneous parentheses @@ -29,10 +27,8 @@ UP034 [*] Avoid extraneous parentheses | help: Remove extraneous parentheses | -4 | # UP034 - - print(("hell((goodbye))o")) +5 - print(("hell((goodbye))o")) 5 + print("hell((goodbye))o") -6 | | UP034 [*] Avoid extraneous parentheses @@ -46,10 +42,8 @@ UP034 [*] Avoid extraneous parentheses | help: Remove extraneous parentheses | -7 | # UP034 - - print((("foo"))) +8 - print((("foo"))) 8 + print(("foo")) -9 | | UP034 [*] Avoid extraneous parentheses @@ -63,10 +57,8 @@ UP034 [*] Avoid extraneous parentheses | help: Remove extraneous parentheses | -10 | # UP034 - - print((((1)))) +11 - print((((1)))) 11 + print(((1))) -12 | | UP034 [*] Avoid extraneous parentheses @@ -80,10 +72,8 @@ UP034 [*] Avoid extraneous parentheses | help: Remove extraneous parentheses | -13 | # UP034 - - print(("foo{}".format(1))) +14 - print(("foo{}".format(1))) 14 + print("foo{}".format(1)) -15 | | UP034 [*] Avoid extraneous parentheses @@ -97,10 +87,8 @@ UP034 [*] Avoid extraneous parentheses | help: Remove extraneous parentheses | -17 | print( - - ("foo{}".format(1)) +18 - ("foo{}".format(1)) 18 + "foo{}".format(1) -19 | ) | UP034 [*] Avoid extraneous parentheses @@ -116,13 +104,9 @@ UP034 [*] Avoid extraneous parentheses | help: Remove extraneous parentheses | -22 | print( - - ( -23 + -24 | "foo" - - ) +23 ~ +24 + "foo" 25 + -26 | ) | UP034 [*] Avoid extraneous parentheses @@ -137,10 +121,8 @@ UP034 [*] Avoid extraneous parentheses | help: Remove extraneous parentheses | -29 | def f(): - - x = int(((yield 1))) +30 - x = int(((yield 1))) 30 + x = int((yield 1)) -31 | | UP034 [*] Avoid extraneous parentheses @@ -154,10 +136,8 @@ UP034 [*] Avoid extraneous parentheses | help: Remove extraneous parentheses | -34 | print( - - ("foo{}".format(1)) +35 - ("foo{}".format(1)) 35 + "foo{}".format(1) -36 | ) | UP034 [*] Avoid extraneous parentheses @@ -171,8 +151,6 @@ UP034 [*] Avoid extraneous parentheses | help: Remove extraneous parentheses | -38 | # UP034 - - print((x for x in range(3))) +39 - print((x for x in range(3))) 39 + print(x for x in range(3)) -40 | | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP035.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP035.py.snap index b84ae75f6a71a..d8d033eaa388b 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP035.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP035.py.snap @@ -12,11 +12,8 @@ UP035 [*] Import from `collections.abc` instead: `Mapping` | help: Import from `collections.abc` | -1 | # UP035 - - from collections import Mapping -2 + from collections.abc import Mapping -3 | - | +2 | from collections.abc import Mapping + | ++++ UP035 [*] Import from `collections.abc` instead: `Mapping` --> UP035.py:4:1 @@ -30,11 +27,8 @@ UP035 [*] Import from `collections.abc` instead: `Mapping` | help: Import from `collections.abc` | -3 | - - from collections import Mapping as MAP -4 + from collections.abc import Mapping as MAP -5 | - | +4 | from collections.abc import Mapping as MAP + | ++++ UP035 [*] Import from `collections.abc` instead: `Mapping`, `Sequence` --> UP035.py:6:1 @@ -48,11 +42,8 @@ UP035 [*] Import from `collections.abc` instead: `Mapping`, `Sequence` | help: Import from `collections.abc` | -5 | - - from collections import Mapping, Sequence -6 + from collections.abc import Mapping, Sequence -7 | - | +6 | from collections.abc import Mapping, Sequence + | ++++ UP035 [*] Import from `collections.abc` instead: `Mapping` --> UP035.py:8:1 @@ -65,13 +56,10 @@ UP035 [*] Import from `collections.abc` instead: `Mapping` 10 | from collections import (Counter, Mapping) | help: Import from `collections.abc` - | -7 | - - from collections import Counter, Mapping -8 + from collections import Counter -9 + from collections.abc import Mapping -10 | - | + | +8 + from collections import Counter +9 + from collections.abc import Mapping + | UP035 [*] Import from `collections.abc` instead: `Mapping` --> UP035.py:10:1 @@ -85,11 +73,8 @@ UP035 [*] Import from `collections.abc` instead: `Mapping` | help: Import from `collections.abc` | -9 | - - from collections import (Counter, Mapping) 10 + from collections import (Counter) 11 + from collections.abc import Mapping -12 | | UP035 [*] Import from `collections.abc` instead: `Mapping` @@ -105,12 +90,8 @@ UP035 [*] Import from `collections.abc` instead: `Mapping` | help: Import from `collections.abc` | -11 | - - from collections import (Counter, - - Mapping) 12 + from collections import (Counter) 13 + from collections.abc import Mapping -14 | | UP035 [*] Import from `collections.abc` instead: `Mapping` @@ -126,12 +107,8 @@ UP035 [*] Import from `collections.abc` instead: `Mapping` | help: Import from `collections.abc` | -14 | - - from collections import Counter, \ - - Mapping 15 + from collections import Counter 16 + from collections.abc import Mapping -17 | | UP035 [*] Import from `collections.abc` instead: `Mapping`, `Sequence` @@ -146,11 +123,8 @@ UP035 [*] Import from `collections.abc` instead: `Mapping`, `Sequence` | help: Import from `collections.abc` | -17 | - - from collections import Counter, Mapping, Sequence 18 + from collections import Counter 19 + from collections.abc import Mapping, Sequence -20 | | UP035 [*] Import from `collections.abc` instead: `Mapping` @@ -165,11 +139,8 @@ UP035 [*] Import from `collections.abc` instead: `Mapping` | help: Import from `collections.abc` | -19 | - - from collections import Mapping as mapping, Counter 20 + from collections import Counter 21 + from collections.abc import Mapping as mapping -22 | | UP035 [*] Import from `collections.abc` instead: `Mapping` @@ -183,11 +154,8 @@ UP035 [*] Import from `collections.abc` instead: `Mapping` | help: Import from `collections.abc` | -22 | if True: - - from collections import Mapping, Counter -23 + from collections import Counter +23 ~ from collections import Counter 24 + from collections.abc import Mapping -25 | | UP035 [*] Import from `collections.abc` instead: `Mapping` @@ -202,11 +170,8 @@ UP035 [*] Import from `collections.abc` instead: `Mapping` | help: Import from `collections.abc` | -27 | pass - - from collections import Mapping, Counter -28 + from collections import Counter +28 ~ from collections import Counter 29 + from collections.abc import Mapping -30 | | UP035 [*] Import from `collections.abc` instead: `Mapping` @@ -221,11 +186,8 @@ UP035 [*] Import from `collections.abc` instead: `Mapping` | help: Import from `collections.abc` | -29 | - - if True: from collections import Mapping -30 + if True: from collections.abc import Mapping -31 | - | +30 | if True: from collections.abc import Mapping + | ++++ UP035 [*] Import from `collections.abc` instead: `Mapping` --> UP035.py:33:1 @@ -237,11 +199,8 @@ UP035 [*] Import from `collections.abc` instead: `Mapping` | help: Import from `collections.abc` | -32 | import os - - from collections import Counter, Mapping 33 + from collections import Counter 34 + from collections.abc import Mapping -35 | import sys | UP035 [*] Import from `collections.abc` instead: `Mapping`, `Callable` @@ -260,14 +219,11 @@ UP035 [*] Import from `collections.abc` instead: `Mapping`, `Callable` | help: Import from `collections.abc` | -37 | from collections import ( - - Mapping, - - Callable, -38 | Bad, -39 | Good, -40 | ) +37 ~ from collections import ( +38 + Bad, +39 + Good, +40 + ) 41 + from collections.abc import Mapping, Callable -42 | | UP035 [*] Import from `collections.abc` instead: `Callable` @@ -282,11 +238,8 @@ UP035 [*] Import from `collections.abc` instead: `Callable` | help: Import from `collections.abc` | -43 | - - from typing import Callable, Match, Pattern, List, OrderedDict, AbstractSet, ContextManager 44 + from typing import Match, Pattern, List, OrderedDict, AbstractSet, ContextManager 45 + from collections.abc import Callable -46 | | UP035 [*] Import from `collections` instead: `OrderedDict` @@ -301,11 +254,8 @@ UP035 [*] Import from `collections` instead: `OrderedDict` | help: Import from `collections` | -43 | - - from typing import Callable, Match, Pattern, List, OrderedDict, AbstractSet, ContextManager 44 + from typing import Callable, Match, Pattern, List, AbstractSet, ContextManager 45 + from collections import OrderedDict -46 | | UP035 [*] Import from `re` instead: `Match`, `Pattern` @@ -320,11 +270,8 @@ UP035 [*] Import from `re` instead: `Match`, `Pattern` | help: Import from `re` | -43 | - - from typing import Callable, Match, Pattern, List, OrderedDict, AbstractSet, ContextManager 44 + from typing import Callable, List, OrderedDict, AbstractSet, ContextManager 45 + from re import Match, Pattern -46 | | UP035 `typing.List` is deprecated, use `list` instead @@ -396,10 +343,8 @@ UP035 [*] Import from `collections` instead: `OrderedDict` | help: Import from `collections` | -50 | from typing import ContextManager - - from typing import OrderedDict +51 - from typing import OrderedDict 51 + from collections import OrderedDict -52 | from typing_extensions import OrderedDict | UP035 [*] Import from `typing` instead: `OrderedDict` @@ -414,10 +359,8 @@ UP035 [*] Import from `typing` instead: `OrderedDict` | help: Import from `typing` | -51 | from typing import OrderedDict - - from typing_extensions import OrderedDict +52 - from typing_extensions import OrderedDict 52 + from typing import OrderedDict -53 | from typing import Callable | UP035 [*] Import from `collections.abc` instead: `Callable` @@ -432,10 +375,8 @@ UP035 [*] Import from `collections.abc` instead: `Callable` | help: Import from `collections.abc` | -52 | from typing_extensions import OrderedDict - - from typing import Callable +53 - from typing import Callable 53 + from collections.abc import Callable -54 | from typing import ByteString | UP035 [*] Import from `collections.abc` instead: `ByteString` @@ -450,10 +391,8 @@ UP035 [*] Import from `collections.abc` instead: `ByteString` | help: Import from `collections.abc` | -53 | from typing import Callable - - from typing import ByteString +54 - from typing import ByteString 54 + from collections.abc import ByteString -55 | from typing import Container | UP035 [*] Import from `collections.abc` instead: `Container` @@ -468,10 +407,8 @@ UP035 [*] Import from `collections.abc` instead: `Container` | help: Import from `collections.abc` | -54 | from typing import ByteString - - from typing import Container +55 - from typing import Container 55 + from collections.abc import Container -56 | from typing import Hashable | UP035 [*] Import from `collections.abc` instead: `Hashable` @@ -486,10 +423,8 @@ UP035 [*] Import from `collections.abc` instead: `Hashable` | help: Import from `collections.abc` | -55 | from typing import Container - - from typing import Hashable +56 - from typing import Hashable 56 + from collections.abc import Hashable -57 | from typing import ItemsView | UP035 [*] Import from `collections.abc` instead: `ItemsView` @@ -504,10 +439,8 @@ UP035 [*] Import from `collections.abc` instead: `ItemsView` | help: Import from `collections.abc` | -56 | from typing import Hashable - - from typing import ItemsView +57 - from typing import ItemsView 57 + from collections.abc import ItemsView -58 | from typing import Iterable | UP035 [*] Import from `collections.abc` instead: `Iterable` @@ -522,10 +455,8 @@ UP035 [*] Import from `collections.abc` instead: `Iterable` | help: Import from `collections.abc` | -57 | from typing import ItemsView - - from typing import Iterable +58 - from typing import Iterable 58 + from collections.abc import Iterable -59 | from typing import Iterator | UP035 [*] Import from `collections.abc` instead: `Iterator` @@ -540,10 +471,8 @@ UP035 [*] Import from `collections.abc` instead: `Iterator` | help: Import from `collections.abc` | -58 | from typing import Iterable - - from typing import Iterator +59 - from typing import Iterator 59 + from collections.abc import Iterator -60 | from typing import KeysView | UP035 [*] Import from `collections.abc` instead: `KeysView` @@ -558,10 +487,8 @@ UP035 [*] Import from `collections.abc` instead: `KeysView` | help: Import from `collections.abc` | -59 | from typing import Iterator - - from typing import KeysView +60 - from typing import KeysView 60 + from collections.abc import KeysView -61 | from typing import Mapping | UP035 [*] Import from `collections.abc` instead: `Mapping` @@ -576,10 +503,8 @@ UP035 [*] Import from `collections.abc` instead: `Mapping` | help: Import from `collections.abc` | -60 | from typing import KeysView - - from typing import Mapping +61 - from typing import Mapping 61 + from collections.abc import Mapping -62 | from typing import MappingView | UP035 [*] Import from `collections.abc` instead: `MappingView` @@ -594,10 +519,8 @@ UP035 [*] Import from `collections.abc` instead: `MappingView` | help: Import from `collections.abc` | -61 | from typing import Mapping - - from typing import MappingView +62 - from typing import MappingView 62 + from collections.abc import MappingView -63 | from typing import MutableMapping | UP035 [*] Import from `collections.abc` instead: `MutableMapping` @@ -612,10 +535,8 @@ UP035 [*] Import from `collections.abc` instead: `MutableMapping` | help: Import from `collections.abc` | -62 | from typing import MappingView - - from typing import MutableMapping +63 - from typing import MutableMapping 63 + from collections.abc import MutableMapping -64 | from typing import MutableSequence | UP035 [*] Import from `collections.abc` instead: `MutableSequence` @@ -630,10 +551,8 @@ UP035 [*] Import from `collections.abc` instead: `MutableSequence` | help: Import from `collections.abc` | -63 | from typing import MutableMapping - - from typing import MutableSequence +64 - from typing import MutableSequence 64 + from collections.abc import MutableSequence -65 | from typing import MutableSet | UP035 [*] Import from `collections.abc` instead: `MutableSet` @@ -648,10 +567,8 @@ UP035 [*] Import from `collections.abc` instead: `MutableSet` | help: Import from `collections.abc` | -64 | from typing import MutableSequence - - from typing import MutableSet +65 - from typing import MutableSet 65 + from collections.abc import MutableSet -66 | from typing import Sequence | UP035 [*] Import from `collections.abc` instead: `Sequence` @@ -666,10 +583,8 @@ UP035 [*] Import from `collections.abc` instead: `Sequence` | help: Import from `collections.abc` | -65 | from typing import MutableSet - - from typing import Sequence +66 - from typing import Sequence 66 + from collections.abc import Sequence -67 | from typing import Sized | UP035 [*] Import from `collections.abc` instead: `Sized` @@ -684,10 +599,8 @@ UP035 [*] Import from `collections.abc` instead: `Sized` | help: Import from `collections.abc` | -66 | from typing import Sequence - - from typing import Sized +67 - from typing import Sized 67 + from collections.abc import Sized -68 | from typing import ValuesView | UP035 [*] Import from `collections.abc` instead: `ValuesView` @@ -702,10 +615,8 @@ UP035 [*] Import from `collections.abc` instead: `ValuesView` | help: Import from `collections.abc` | -67 | from typing import Sized - - from typing import ValuesView +68 - from typing import ValuesView 68 + from collections.abc import ValuesView -69 | from typing import Awaitable | UP035 [*] Import from `collections.abc` instead: `Awaitable` @@ -720,10 +631,8 @@ UP035 [*] Import from `collections.abc` instead: `Awaitable` | help: Import from `collections.abc` | -68 | from typing import ValuesView - - from typing import Awaitable +69 - from typing import Awaitable 69 + from collections.abc import Awaitable -70 | from typing import AsyncIterator | UP035 [*] Import from `collections.abc` instead: `AsyncIterator` @@ -738,10 +647,8 @@ UP035 [*] Import from `collections.abc` instead: `AsyncIterator` | help: Import from `collections.abc` | -69 | from typing import Awaitable - - from typing import AsyncIterator +70 - from typing import AsyncIterator 70 + from collections.abc import AsyncIterator -71 | from typing import AsyncIterable | UP035 [*] Import from `collections.abc` instead: `AsyncIterable` @@ -756,10 +663,8 @@ UP035 [*] Import from `collections.abc` instead: `AsyncIterable` | help: Import from `collections.abc` | -70 | from typing import AsyncIterator - - from typing import AsyncIterable +71 - from typing import AsyncIterable 71 + from collections.abc import AsyncIterable -72 | from typing import Coroutine | UP035 [*] Import from `collections.abc` instead: `Coroutine` @@ -774,10 +679,8 @@ UP035 [*] Import from `collections.abc` instead: `Coroutine` | help: Import from `collections.abc` | -71 | from typing import AsyncIterable - - from typing import Coroutine +72 - from typing import Coroutine 72 + from collections.abc import Coroutine -73 | from typing import Collection | UP035 [*] Import from `collections.abc` instead: `Collection` @@ -792,10 +695,8 @@ UP035 [*] Import from `collections.abc` instead: `Collection` | help: Import from `collections.abc` | -72 | from typing import Coroutine - - from typing import Collection +73 - from typing import Collection 73 + from collections.abc import Collection -74 | from typing import AsyncGenerator | UP035 [*] Import from `collections.abc` instead: `AsyncGenerator` @@ -810,10 +711,8 @@ UP035 [*] Import from `collections.abc` instead: `AsyncGenerator` | help: Import from `collections.abc` | -73 | from typing import Collection - - from typing import AsyncGenerator +74 - from typing import AsyncGenerator 74 + from collections.abc import AsyncGenerator -75 | from typing import Reversible | UP035 [*] Import from `collections.abc` instead: `Reversible` @@ -828,10 +727,8 @@ UP035 [*] Import from `collections.abc` instead: `Reversible` | help: Import from `collections.abc` | -74 | from typing import AsyncGenerator - - from typing import Reversible +75 - from typing import Reversible 75 + from collections.abc import Reversible -76 | from typing import Generator | UP035 [*] Import from `collections.abc` instead: `Generator` @@ -846,10 +743,8 @@ UP035 [*] Import from `collections.abc` instead: `Generator` | help: Import from `collections.abc` | -75 | from typing import Reversible - - from typing import Generator +76 - from typing import Generator 76 + from collections.abc import Generator -77 | from typing import Callable | UP035 [*] Import from `collections.abc` instead: `Callable` @@ -863,10 +758,8 @@ UP035 [*] Import from `collections.abc` instead: `Callable` | help: Import from `collections.abc` | -76 | from typing import Generator - - from typing import Callable +77 - from typing import Callable 77 + from collections.abc import Callable -78 | from typing import cast | UP035 [*] Import from `typing` instead: `SupportsIndex` @@ -880,10 +773,8 @@ UP035 [*] Import from `typing` instead: `SupportsIndex` | help: Import from `typing` | -83 | # UP035 on py312+ only - - from typing_extensions import SupportsIndex +84 - from typing_extensions import SupportsIndex 84 + from typing import SupportsIndex -85 | | UP035 [*] Import from `typing` instead: `NamedTuple` @@ -897,10 +788,8 @@ UP035 [*] Import from `typing` instead: `NamedTuple` | help: Import from `typing` | -86 | # UP035 on py312+ only - - from typing_extensions import NamedTuple +87 - from typing_extensions import NamedTuple 87 + from typing import NamedTuple -88 | | UP035 [*] Import from `typing` instead: `dataclass_transform` @@ -914,10 +803,8 @@ UP035 [*] Import from `typing` instead: `dataclass_transform` | help: Import from `typing` | -89 | # UP035 on py312+ only: `typing_extensions` supports `frozen_default` (backported from 3.12). - - from typing_extensions import dataclass_transform +90 - from typing_extensions import dataclass_transform 90 + from typing import dataclass_transform -91 | | UP035 [*] Import from `enum` instead: `StrEnum` @@ -931,10 +818,8 @@ UP035 [*] Import from `enum` instead: `StrEnum` | help: Import from `enum` | -92 | # UP035 - - from backports.strenum import StrEnum +93 - from backports.strenum import StrEnum 93 + from enum import StrEnum -94 | | UP035 [*] Import from `typing` instead: `override` @@ -948,10 +833,8 @@ UP035 [*] Import from `typing` instead: `override` | help: Import from `typing` | -95 | # UP035 - - from typing_extensions import override +96 - from typing_extensions import override 96 + from typing import override -97 | | UP035 [*] Import from `collections.abc` instead: `Buffer` @@ -964,12 +847,10 @@ UP035 [*] Import from `collections.abc` instead: `Buffer` 101 | # UP035 | help: Import from `collections.abc` - | -98 | # UP035 - - from typing_extensions import Buffer -99 + from collections.abc import Buffer -100 | - | + | +99 - from typing_extensions import Buffer +99 + from collections.abc import Buffer + | UP035 [*] Import from `types` instead: `get_original_bases` --> UP035.py:102:1 @@ -982,10 +863,8 @@ UP035 [*] Import from `types` instead: `get_original_bases` | help: Import from `types` | -101 | # UP035 - - from typing_extensions import get_original_bases +102 - from typing_extensions import get_original_bases 102 + from types import get_original_bases -103 | | UP035 [*] Import from `typing` instead: `TypeVar` @@ -999,10 +878,8 @@ UP035 [*] Import from `typing` instead: `TypeVar` | help: Import from `typing` | -104 | # UP035 on py313+ only - - from typing_extensions import TypeVar +105 - from typing_extensions import TypeVar 105 + from typing import TypeVar -106 | | UP035 [*] Import from `types` instead: `CapsuleType` @@ -1016,10 +893,8 @@ UP035 [*] Import from `types` instead: `CapsuleType` | help: Import from `types` | -107 | # UP035 on py313+ only - - from typing_extensions import CapsuleType +108 - from typing_extensions import CapsuleType 108 + from types import CapsuleType -109 | | UP035 [*] Import from `warnings` instead: `deprecated` @@ -1033,10 +908,8 @@ UP035 [*] Import from `warnings` instead: `deprecated` | help: Import from `warnings` | -110 | # UP035 on py313+ only - - from typing_extensions import deprecated +111 - from typing_extensions import deprecated 111 + from warnings import deprecated -112 | | UP035 [*] Import from `typing` instead: `get_type_hints` @@ -1050,10 +923,8 @@ UP035 [*] Import from `typing` instead: `get_type_hints` | help: Import from `typing` | -113 | # UP035 on py313+ only - - from typing_extensions import get_type_hints +114 - from typing_extensions import get_type_hints 114 + from typing import get_type_hints -115 | | UP035 [*] Import from `typing` instead: `BinaryIO` @@ -1067,10 +938,8 @@ UP035 [*] Import from `typing` instead: `BinaryIO` | help: Import from `typing` | -121 | # UP035 on py37+ only - - from typing.io import BinaryIO +122 - from typing.io import BinaryIO 122 + from typing import BinaryIO -123 | | UP035 [*] Import from `typing` instead: `IO` @@ -1084,10 +953,8 @@ UP035 [*] Import from `typing` instead: `IO` | help: Import from `typing` | -124 | # UP035 on py37+ only - - from typing.io import IO +125 - from typing.io import IO 125 + from typing import IO -126 | | UP035 [*] Import from `typing` instead: `TextIO` @@ -1101,10 +968,8 @@ UP035 [*] Import from `typing` instead: `TextIO` | help: Import from `typing` | -127 | # UP035 on py37+ only - - from typing.io import TextIO +128 - from typing.io import TextIO 128 + from typing import TextIO -129 | | UP035 [*] Import from `re` instead: `Match` @@ -1118,10 +983,8 @@ UP035 [*] Import from `re` instead: `Match` | help: Import from `re` | -130 | # UP035 on py37+ only - - from typing.re import Match +131 - from typing.re import Match 131 + from re import Match -132 | | UP035 [*] Import from `re` instead: `Pattern` @@ -1132,7 +995,6 @@ UP035 [*] Import from `re` instead: `Pattern` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Import from `re` | -133 | # UP035 on py37+ only - - from typing.re import Pattern +134 - from typing.re import Pattern 134 + from re import Pattern | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_0.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_0.py.snap index 99e33b6322233..293bb99b4de64 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_0.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_0.py.snap @@ -13,13 +13,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -2 | - - if sys.version_info < (3,0): - - print("py2") - - else: - - print("py3") +3 - if sys.version_info < (3,0): +4 - print("py2") +5 - else: +6 - print("py3") 3 + print("py3") -4 | | note: This is an unsafe fix and may change runtime behavior @@ -34,18 +32,16 @@ UP036 [*] Version block is outdated for minimum Python version 10 | print("py2!") | help: Remove outdated version block - | -7 | - - if sys.version_info < (3,0): - - if True: - - print("py2!") - - else: - - print("???") - - else: - - print("py3") -8 + print("py3") -9 | - | + | + 8 - if sys.version_info < (3,0): + 9 - if True: +10 - print("py2!") +11 - else: +12 - print("???") +13 - else: +14 - print("py3") + 8 + print("py3") + | note: This is an unsafe fix and may change runtime behavior UP036 [*] Version block is outdated for minimum Python version @@ -59,11 +55,9 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -15 | - - if sys.version_info < (3,0): print("PY2!") - - else: print("PY3!") +16 - if sys.version_info < (3,0): print("PY2!") +17 - else: print("PY3!") 16 + print("PY3!") -17 | | note: This is an unsafe fix and may change runtime behavior @@ -78,13 +72,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -19 | if True: - - if sys.version_info < (3,0): - - print("PY2") - - else: - - print("PY3") +20 - if sys.version_info < (3,0): +21 - print("PY2") +22 - else: +23 - print("PY3") 20 + print("PY3") -21 | | note: This is an unsafe fix and may change runtime behavior @@ -100,12 +92,10 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -24 | - - if sys.version_info < (3,0): print(1 if True else 3) - - else: - - print("py3") +25 - if sys.version_info < (3,0): print(1 if True else 3) +26 - else: +27 - print("py3") 25 + print("py3") -26 | | note: This is an unsafe fix and may change runtime behavior @@ -121,18 +111,9 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -28 | - - if sys.version_info < (3,0): - - def f(): - - print("py2") - - else: - - def f(): - - print("py3") - - print("This the next") 29 + def f(): 30 + print("py3") 31 + print("This the next") -32 | | note: This is an unsafe fix and may change runtime behavior @@ -148,13 +129,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -36 | - - if sys.version_info > (3,0): - - print("py3") - - else: - - print("py2") +37 - if sys.version_info > (3,0): +38 - print("py3") +39 - else: +40 - print("py2") 37 + print("py3") -38 | | note: This is an unsafe fix and may change runtime behavior @@ -170,13 +149,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -44 | - - if sys.version_info > (3,0): - - print("py3") - - else: - - print("py2") +45 - if sys.version_info > (3,0): +46 - print("py3") +47 - else: +48 - print("py2") 45 + print("py3") -46 | # ohai | note: This is an unsafe fix and may change runtime behavior @@ -191,11 +168,9 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -52 | - - if sys.version_info > (3,0): print("py3") - - else: print("py2") +53 - if sys.version_info > (3,0): print("py3") +54 - else: print("py2") 53 + print("py3") -54 | | note: This is an unsafe fix and may change runtime behavior @@ -211,13 +186,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -55 | - - if sys.version_info > (3,): - - print("py3") - - else: - - print("py2") +56 - if sys.version_info > (3,): +57 - print("py3") +58 - else: +59 - print("py2") 56 + print("py3") -57 | | note: This is an unsafe fix and may change runtime behavior @@ -232,13 +205,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -61 | if True: - - if sys.version_info > (3,): - - print("py3") - - else: - - print("py2") +62 - if sys.version_info > (3,): +63 - print("py3") +64 - else: +65 - print("py2") 62 + print("py3") -63 | | note: This is an unsafe fix and may change runtime behavior @@ -254,13 +225,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -66 | - - if sys.version_info < (3,): - - print("py2") - - else: - - print("py3") +67 - if sys.version_info < (3,): +68 - print("py2") +69 - else: +70 - print("py3") 67 + print("py3") -68 | | note: This is an unsafe fix and may change runtime behavior @@ -275,16 +244,14 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -72 | def f(): - - if sys.version_info < (3,0): - - try: - - yield - - finally: - - pass - - else: - - yield +73 - if sys.version_info < (3,0): +74 - try: +75 - yield +76 - finally: +77 - pass +78 - else: +79 - yield 73 + yield -74 | | note: This is an unsafe fix and may change runtime behavior @@ -300,16 +267,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -85 | - - if sys.version_info < (3,0): - - def f(py2): - - pass - - else: - - def f(py3): - - pass 86 + def f(py3): 87 + pass -88 | | note: This is an unsafe fix and may change runtime behavior @@ -323,15 +282,13 @@ UP036 [*] Version block is outdated for minimum Python version 99 | else: | help: Remove outdated version block - | -96 | if True: - - if sys.version_info < (3,0): - - 2 - - else: - - 3 -97 + 3 -98 | - | + | + 97 - if sys.version_info < (3,0): + 98 - 2 + 99 - else: +100 - 3 + 97 + 3 + | note: This is an unsafe fix and may change runtime behavior UP036 [*] Version block is outdated for minimum Python version @@ -346,22 +303,10 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -103 | - - if sys.version_info < (3,0): - - def f(): - - print("py2") - - def g(): - - print("py2") - - else: - - def f(): - - print("py3") - - def g(): - - print("py3") 104 + def f(): 105 + print("py3") 106 + def g(): 107 + print("py3") -108 | | note: This is an unsafe fix and may change runtime behavior @@ -376,11 +321,9 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -115 | if True: - - if sys.version_info > (3,): - - print(3) +116 - if sys.version_info > (3,): +117 - print(3) 116 + print(3) -117 | # comment | note: This is an unsafe fix and may change runtime behavior @@ -395,10 +338,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -121 | if True: - - if sys.version_info > (3,): print(3) +122 - if sys.version_info > (3,): print(3) 122 + print(3) -123 | | note: This is an unsafe fix and may change runtime behavior @@ -412,11 +353,9 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -124 | if True: - - if sys.version_info > (3,): - - print(3) +125 - if sys.version_info > (3,): +126 - print(3) 125 + print(3) -126 | | note: This is an unsafe fix and may change runtime behavior @@ -431,18 +370,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -129 | if True: - - if sys.version_info <= (3, 0): - - expected_error = [] - - else: - - expected_error = [ 130 + expected_error = [ -131 | ":1:5: Generator expression must be parenthesized", -132 | "max(1 for i in range(10), key=lambda x: x+1)", -133 | " ^", - - ] +131 + ":1:5: Generator expression must be parenthesized", +132 + "max(1 for i in range(10), key=lambda x: x+1)", +133 + " ^", 134 + ] -135 | | note: This is an unsafe fix and may change runtime behavior @@ -456,18 +388,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -139 | - - if sys.version_info <= (3, 0): - - expected_error = [] - - else: - - expected_error = [ 140 + expected_error = [ -141 | ":1:5: Generator expression must be parenthesized", -142 | "max(1 for i in range(10), key=lambda x: x+1)", -143 | " ^", - - ] +141 + ":1:5: Generator expression must be parenthesized", +142 + "max(1 for i in range(10), key=lambda x: x+1)", +143 + " ^", 144 + ] -145 | | note: This is an unsafe fix and may change runtime behavior @@ -481,25 +406,17 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -149 | - - if sys.version_info > (3,0): - - """this 150 + """this -151 | is valid""" -152 | - - """the indentation on +151 + is valid""" +152 + 153 + """the indentation on -154 | this line is significant""" -155 | - - "this is" \ +154 + this line is significant""" +155 + 156 + "this is" \ -157 | "allowed too" -158 | - - ("so is" - - "this for some reason") +157 + "allowed too" +158 + 159 + ("so is" 160 + "this for some reason") -161 | | note: This is an unsafe fix and may change runtime behavior @@ -514,10 +431,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -162 | - - if sys.version_info > (3, 0): expected_error = \ 163 + expected_error = \ -164 | [] +164 + [] | note: This is an unsafe fix and may change runtime behavior @@ -533,10 +448,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -165 | - - if sys.version_info > (3, 0): expected_error = [] +166 - if sys.version_info > (3, 0): expected_error = [] 166 + expected_error = [] -167 | | note: This is an unsafe fix and may change runtime behavior @@ -551,11 +464,9 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -167 | - - if sys.version_info > (3, 0): \ - - expected_error = [] +168 - if sys.version_info > (3, 0): \ +169 - expected_error = [] 168 + expected_error = [] -169 | | note: This is an unsafe fix and may change runtime behavior @@ -569,10 +480,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -171 | if True: - - if sys.version_info > (3, 0): expected_error = \ -172 + expected_error = \ -173 | [] +172 ~ expected_error = \ +173 + [] | note: This is an unsafe fix and may change runtime behavior @@ -587,10 +496,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -175 | if True: - - if sys.version_info > (3, 0): expected_error = [] +176 - if sys.version_info > (3, 0): expected_error = [] 176 + expected_error = [] -177 | | note: This is an unsafe fix and may change runtime behavior @@ -604,9 +511,7 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -178 | if True: - - if sys.version_info > (3, 0): \ -179 | expected_error = [] +179 - if sys.version_info > (3, 0): \ | note: This is an unsafe fix and may change runtime behavior @@ -621,10 +526,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -181 | - - if sys.version_info < (3,13): - - print("py3") -182 | +182 - if sys.version_info < (3,13): +183 - print("py3") | note: This is an unsafe fix and may change runtime behavior @@ -639,10 +542,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -184 | - - if sys.version_info <= (3,13): - - print("py3") -185 | +185 - if sys.version_info <= (3,13): +186 - print("py3") | note: This is an unsafe fix and may change runtime behavior @@ -657,10 +558,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -187 | - - if sys.version_info <= (3,13): - - print("py3") -188 | +188 - if sys.version_info <= (3,13): +189 - print("py3") | note: This is an unsafe fix and may change runtime behavior @@ -705,11 +604,9 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -199 | - - if sys.version_info > (3,13): - - print("py3") +200 - if sys.version_info > (3,13): +201 - print("py3") 200 + print("py3") -201 | | note: This is an unsafe fix and may change runtime behavior @@ -724,11 +621,9 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -202 | - - if sys.version_info >= (3,13): - - print("py3") +203 - if sys.version_info >= (3,13): +204 - print("py3") 203 + print("py3") -204 | | note: This is an unsafe fix and may change runtime behavior @@ -742,11 +637,9 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -206 | # Slices on `sys.version_info` should be treated equivalently. - - if sys.version_info[:2] >= (3,0): - - print("py3") +207 - if sys.version_info[:2] >= (3,0): +208 - print("py3") 207 + print("py3") -208 | | note: This is an unsafe fix and may change runtime behavior @@ -761,11 +654,9 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -209 | - - if sys.version_info[:3] >= (3,0): - - print("py3") +210 - if sys.version_info[:3] >= (3,0): +211 - print("py3") 210 + print("py3") -211 | | note: This is an unsafe fix and may change runtime behavior @@ -781,19 +672,14 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -218 | - - if sys.version_info > (3,0): - - f"this is\ 219 + f"this is\ -220 | allowed too" -221 | - - f"""the indentation on +220 + allowed too" +221 + 222 + f"""the indentation on -223 | this line is significant""" -224 | - - "this is\ +223 + this line is significant""" +224 + 225 + "this is\ -226 | allowed too" +226 + allowed too" | note: This is an unsafe fix and may change runtime behavior @@ -808,11 +694,9 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -228 | - - if sys.version_info[0] == 3: - - print("py3") +229 - if sys.version_info[0] == 3: +230 - print("py3") 229 + print("py3") -230 | | note: This is an unsafe fix and may change runtime behavior @@ -827,11 +711,9 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -231 | - - if sys.version_info[0] <= 3: - - print("py3") +232 - if sys.version_info[0] <= 3: +233 - print("py3") 232 + print("py3") -233 | | note: This is an unsafe fix and may change runtime behavior @@ -846,10 +728,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -234 | - - if sys.version_info[0] < 3: - - print("py3") -235 | +235 - if sys.version_info[0] < 3: +236 - print("py3") | note: This is an unsafe fix and may change runtime behavior @@ -864,11 +744,9 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -237 | - - if sys.version_info[0] >= 3: - - print("py3") +238 - if sys.version_info[0] >= 3: +239 - print("py3") 238 + print("py3") -239 | | note: This is an unsafe fix and may change runtime behavior @@ -883,10 +761,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -240 | - - if sys.version_info[0] > 3: - - print("py3") -241 | +241 - if sys.version_info[0] > 3: +242 - print("py3") | note: This is an unsafe fix and may change runtime behavior @@ -901,10 +777,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -243 | - - if sys.version_info[0] == 2: - - print("py3") -244 | +244 - if sys.version_info[0] == 2: +245 - print("py3") | note: This is an unsafe fix and may change runtime behavior @@ -919,10 +793,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -246 | - - if sys.version_info[0] <= 2: - - print("py3") -247 | +247 - if sys.version_info[0] <= 2: +248 - print("py3") | note: This is an unsafe fix and may change runtime behavior @@ -937,10 +809,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -249 | - - if sys.version_info[0] < 2: - - print("py3") -250 | +250 - if sys.version_info[0] < 2: +251 - print("py3") | note: This is an unsafe fix and may change runtime behavior @@ -955,11 +825,9 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -252 | - - if sys.version_info[0] >= 2: - - print("py3") +253 - if sys.version_info[0] >= 2: +254 - print("py3") 253 + print("py3") -254 | | note: This is an unsafe fix and may change runtime behavior @@ -974,9 +842,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -255 | - - if sys.version_info[0] > 2: - - print("py3") +256 - if sys.version_info[0] > 2: +257 - print("py3") 256 + print("py3") | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_1.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_1.py.snap index dc984cc4f7560..b8183326bbe5c 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_1.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_1.py.snap @@ -13,13 +13,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -2 | - - if sys.version_info == 2: - - 2 - - else: - - 3 +3 - if sys.version_info == 2: +4 - 2 +5 - else: +6 - 3 3 + 3 -4 | | note: This is an unsafe fix and may change runtime behavior @@ -34,15 +32,13 @@ UP036 [*] Version block is outdated for minimum Python version 10 | else: | help: Remove outdated version block - | -7 | - - if sys.version_info < (3,): - - 2 - - else: - - 3 -8 + 3 -9 | - | + | + 8 - if sys.version_info < (3,): + 9 - 2 +10 - else: +11 - 3 + 8 + 3 + | note: This is an unsafe fix and may change runtime behavior UP036 [*] Version block is outdated for minimum Python version @@ -57,13 +53,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -12 | - - if sys.version_info < (3,0): - - 2 - - else: - - 3 +13 - if sys.version_info < (3,0): +14 - 2 +15 - else: +16 - 3 13 + 3 -14 | | note: This is an unsafe fix and may change runtime behavior @@ -79,13 +73,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -17 | - - if sys.version_info == 3: - - 3 - - else: - - 2 +18 - if sys.version_info == 3: +19 - 3 +20 - else: +21 - 2 18 + 3 -19 | | note: This is an unsafe fix and may change runtime behavior @@ -101,13 +93,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -22 | - - if sys.version_info > (3,): - - 3 - - else: - - 2 +23 - if sys.version_info > (3,): +24 - 3 +25 - else: +26 - 2 23 + 3 -24 | | note: This is an unsafe fix and may change runtime behavior @@ -123,13 +113,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -27 | - - if sys.version_info >= (3,): - - 3 - - else: - - 2 +28 - if sys.version_info >= (3,): +29 - 3 +30 - else: +31 - 2 28 + 3 -29 | | note: This is an unsafe fix and may change runtime behavior @@ -145,13 +133,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -34 | - - if version_info > (3,): - - 3 - - else: - - 2 +35 - if version_info > (3,): +36 - 3 +37 - else: +38 - 2 35 + 3 -36 | | note: This is an unsafe fix and may change runtime behavior @@ -167,10 +153,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -41 | print(1) - - elif sys.version_info < (3,0): - - print(2) -42 | else: +42 - elif sys.version_info < (3,0): +43 - print(2) | note: This is an unsafe fix and may change runtime behavior @@ -186,13 +170,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -48 | print(1) - - elif sys.version_info > (3,): 49 + else: -50 | print(3) - - else: - - print(2) -51 | +50 + print(3) | note: This is an unsafe fix and may change runtime behavior @@ -207,10 +186,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -55 | print(1) - - elif sys.version_info > (3,): 56 + else: -57 | print(3) +57 + print(3) | note: This is an unsafe fix and may change runtime behavior @@ -225,10 +202,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -61 | print(1) - - elif sys.version_info > (3,): -62 + else: -63 | print(3) +62 ~ else: +63 + print(3) | note: This is an unsafe fix and may change runtime behavior @@ -244,10 +219,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -66 | print(1) - - elif sys.version_info < (3,0): - - print(2) -67 | else: +67 - elif sys.version_info < (3,0): +68 - print(2) | note: This is an unsafe fix and may change runtime behavior @@ -262,9 +235,7 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -74 | print(1) - - elif sys.version_info > (3,): -75 + else: -76 | print(3) +75 ~ else: +76 + print(3) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_2.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_2.py.snap index b5f22bdca3efb..1f237adceb20a 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_2.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_2.py.snap @@ -13,13 +13,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -3 | - - if sys.version_info > (3, 5): - - 3+6 - - else: - - 3-5 +4 - if sys.version_info > (3, 5): +5 - 3+6 +6 - else: +7 - 3-5 4 + 3+6 -5 | | note: This is an unsafe fix and may change runtime behavior @@ -35,13 +33,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -8 | - - if version_info > (3, 5): - - 3+6 - - else: - - 3-5 -9 + 3+6 -10 | + 9 - if version_info > (3, 5): +10 - 3+6 +11 - else: +12 - 3-5 + 9 + 3+6 | note: This is an unsafe fix and may change runtime behavior @@ -57,13 +53,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -13 | - - if sys.version_info >= (3,6): - - 3+6 - - else: - - 3-5 +14 - if sys.version_info >= (3,6): +15 - 3+6 +16 - else: +17 - 3-5 14 + 3+6 -15 | | note: This is an unsafe fix and may change runtime behavior @@ -79,13 +73,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -18 | - - if version_info >= (3,6): - - 3+6 - - else: - - 3-5 +19 - if version_info >= (3,6): +20 - 3+6 +21 - else: +22 - 3-5 19 + 3+6 -20 | | note: This is an unsafe fix and may change runtime behavior @@ -101,13 +93,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -23 | - - if sys.version_info < (3,6): - - 3-5 - - else: - - 3+6 +24 - if sys.version_info < (3,6): +25 - 3-5 +26 - else: +27 - 3+6 24 + 3+6 -25 | | note: This is an unsafe fix and may change runtime behavior @@ -123,13 +113,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -28 | - - if sys.version_info <= (3,5): - - 3-5 - - else: - - 3+6 +29 - if sys.version_info <= (3,5): +30 - 3-5 +31 - else: +32 - 3+6 29 + 3+6 -30 | | note: This is an unsafe fix and may change runtime behavior @@ -145,13 +133,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -33 | - - if sys.version_info <= (3, 5): - - 3-5 - - else: - - 3+6 +34 - if sys.version_info <= (3, 5): +35 - 3-5 +36 - else: +37 - 3+6 34 + 3+6 -35 | | note: This is an unsafe fix and may change runtime behavior @@ -166,11 +152,9 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -38 | - - if sys.version_info >= (3, 5): - - pass +39 - if sys.version_info >= (3, 5): +40 - pass 39 + pass -40 | | note: This is an unsafe fix and may change runtime behavior @@ -185,10 +169,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -41 | - - if sys.version_info < (3,0): - - pass -42 | +42 - if sys.version_info < (3,0): +43 - pass | note: This is an unsafe fix and may change runtime behavior @@ -202,11 +184,9 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -45 | if True: - - if sys.version_info < (3,0): - - pass +46 - if sys.version_info < (3,0): +47 - pass 46 + pass -47 | | note: This is an unsafe fix and may change runtime behavior @@ -222,12 +202,10 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -48 | - - if sys.version_info < (3,0): - - pass - - elif False: +49 - if sys.version_info < (3,0): +50 - pass +51 - elif False: 49 + if False: -50 | pass | note: This is an unsafe fix and may change runtime behavior @@ -243,12 +221,10 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -53 | - - if sys.version_info > (3,): - - pass - - elif False: - - pass +54 - if sys.version_info > (3,): +55 - pass +56 - elif False: +57 - pass 54 + pass -55 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_3.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_3.py.snap index 6438bfa260952..6ac4664657210 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_3.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_3.py.snap @@ -13,19 +13,9 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -2 | - - if sys.version_info < (3,0): - - print("py2") - - for item in range(10): - - print(f"PY2-{item}") - - else : - - print("py3") - - for item in range(10): - - print(f"PY3-{item}") 3 + print("py3") 4 + for item in range(10): 5 + print(f"PY3-{item}") -6 | | note: This is an unsafe fix and may change runtime behavior @@ -40,19 +30,9 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -12 | if False: - - if sys.version_info < (3,0): - - print("py2") - - for item in range(10): - - print(f"PY2-{item}") - - else : - - print("py3") - - for item in range(10): - - print(f"PY3-{item}") 13 + print("py3") 14 + for item in range(10): 15 + print(f"PY3-{item}") -16 | | note: This is an unsafe fix and may change runtime behavior @@ -65,9 +45,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -22 | - - if sys.version_info < (3,0): print("PY2!") - - else : print("PY3!") +23 - if sys.version_info < (3,0): print("PY2!") +24 - else : print("PY3!") 23 + print("PY3!") | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_4.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_4.py.snap index 0f7622c733b14..5058b39ecab8a 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_4.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_4.py.snap @@ -11,11 +11,9 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -3 | if True: - - if sys.version_info < (3, 3): - - cmd = [sys.executable, "-m", "test.regrtest"] +4 - if sys.version_info < (3, 3): +5 - cmd = [sys.executable, "-m", "test.regrtest"] 4 + pass -5 | | note: This is an unsafe fix and may change runtime behavior @@ -30,11 +28,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -10 | print() - - elif sys.version_info < (3, 3): - - cmd = [sys.executable, "-m", "test.regrtest"] -11 + -12 | +11 - elif sys.version_info < (3, 3): +12 - cmd = [sys.executable, "-m", "test.regrtest"] | note: This is an unsafe fix and may change runtime behavior @@ -50,10 +45,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -16 | print() - - elif sys.version_info < (3, 3): - - cmd = [sys.executable, "-m", "test.regrtest"] -17 | elif foo: +17 - elif sys.version_info < (3, 3): +18 - cmd = [sys.executable, "-m", "test.regrtest"] | note: This is an unsafe fix and may change runtime behavior @@ -68,11 +61,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -23 | print() - - elif sys.version_info < (3, 3): - - cmd = [sys.executable, "-m", "test.regrtest"] -24 + -25 | +24 - elif sys.version_info < (3, 3): +25 - cmd = [sys.executable, "-m", "test.regrtest"] | note: This is an unsafe fix and may change runtime behavior @@ -87,10 +77,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -26 | - - if sys.version_info < (3, 3): - - cmd = [sys.executable, "-m", "test.regrtest"] -27 | +27 - if sys.version_info < (3, 3): +28 - cmd = [sys.executable, "-m", "test.regrtest"] | note: This is an unsafe fix and may change runtime behavior @@ -106,10 +94,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -31 | print() - - elif sys.version_info < (3, 3): - - cmd = [sys.executable, "-m", "test.regrtest"] -32 | else: +32 - elif sys.version_info < (3, 3): +33 - cmd = [sys.executable, "-m", "test.regrtest"] | note: This is an unsafe fix and may change runtime behavior @@ -125,13 +111,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -36 | - - if sys.version_info < (3, 3): - - cmd = [sys.executable, "-m", "test.regrtest"] - - else: - - cmd = [sys.executable, "-m", "test", "-j0"] +37 - if sys.version_info < (3, 3): +38 - cmd = [sys.executable, "-m", "test.regrtest"] +39 - else: +40 - cmd = [sys.executable, "-m", "test", "-j0"] 37 + cmd = [sys.executable, "-m", "test", "-j0"] -38 | | note: This is an unsafe fix and may change runtime behavior @@ -147,11 +131,9 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -41 | - - if sys.version_info < (3, 3): - - cmd = [sys.executable, "-m", "test.regrtest"] - - elif foo: +42 - if sys.version_info < (3, 3): +43 - cmd = [sys.executable, "-m", "test.regrtest"] +44 - elif foo: 42 + if foo: -43 | cmd = [sys.executable, "-m", "test", "-j0"] | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_5.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_5.py.snap index 0a6a955748af3..cc8b6a32eb2b5 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_5.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP036_5.py.snap @@ -12,22 +12,20 @@ UP036 [*] Version block is outdated for minimum Python version 5 | def a(): | help: Remove outdated version block - | -2 | - - if sys.version_info < (3, 8): - - - - def a(): - - if b: - - print(1) - - elif c: - - print(2) - - return None - - - - else: - - pass -3 + pass -4 | - | + | + 3 - if sys.version_info < (3, 8): + 4 - + 5 - def a(): + 6 - if b: + 7 - print(1) + 8 - elif c: + 9 - print(2) +10 - return None +11 - +12 - else: +13 - pass + 3 + pass + | note: This is an unsafe fix and may change runtime behavior UP036 [*] Version block is outdated for minimum Python version @@ -41,20 +39,6 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -17 | - - if sys.version_info < (3, 8): - - pass - - - - else: - - - - def a(): - - if b: - - print(1) - - elif c: - - print(2) - - else: - - print(3) - - return None 18 + def a(): 19 + if b: 20 + print(1) @@ -63,7 +47,6 @@ help: Remove outdated version block 23 + else: 24 + print(3) 25 + return None -26 | | note: This is an unsafe fix and may change runtime behavior @@ -77,10 +60,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -35 | ## Errors - - if sys.version_info < (3, 12, 0): - - print() -36 | +36 - if sys.version_info < (3, 12, 0): +37 - print() | note: This is an unsafe fix and may change runtime behavior @@ -95,10 +76,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -38 | - - if sys.version_info <= (3, 12, 0): - - print() -39 | +39 - if sys.version_info <= (3, 12, 0): +40 - print() | note: This is an unsafe fix and may change runtime behavior @@ -113,10 +92,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -41 | - - if sys.version_info < (3, 12, 11): - - print() -42 | +42 - if sys.version_info < (3, 12, 11): +43 - print() | note: This is an unsafe fix and may change runtime behavior @@ -131,10 +108,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -44 | - - if sys.version_info < (3, 13, 0): - - print() -45 | +45 - if sys.version_info < (3, 13, 0): +46 - print() | note: This is an unsafe fix and may change runtime behavior @@ -159,10 +134,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -59 | - - if sys.version_info <= (3, 13, 0): - - print() -60 | +60 - if sys.version_info <= (3, 13, 0): +61 - print() | note: This is an unsafe fix and may change runtime behavior @@ -177,10 +150,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -62 | - - if sys.version_info < (3, 13, 37): - - print() -63 | +63 - if sys.version_info < (3, 13, 37): +64 - print() | note: This is an unsafe fix and may change runtime behavior @@ -195,10 +166,8 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -65 | - - if sys.version_info <= (3, 13, 37): - - print() -66 | +66 - if sys.version_info <= (3, 13, 37): +67 - print() | note: This is an unsafe fix and may change runtime behavior @@ -214,13 +183,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -76 | - - if sys.version_info.major >= 3: - - print("3") - - else: - - print("2") +77 - if sys.version_info.major >= 3: +78 - print("3") +79 - else: +80 - print("2") 77 + print("3") -78 | | note: This is an unsafe fix and may change runtime behavior @@ -236,13 +203,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -81 | - - if sys.version_info.major > 3: - - print("3") - - else: - - print("2") +82 - if sys.version_info.major > 3: +83 - print("3") +84 - else: +85 - print("2") 82 + print("2") -83 | | note: This is an unsafe fix and may change runtime behavior @@ -258,13 +223,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -86 | - - if sys.version_info.major <= 3: - - print("3") - - else: - - print("2") +87 - if sys.version_info.major <= 3: +88 - print("3") +89 - else: +90 - print("2") 87 + print("3") -88 | | note: This is an unsafe fix and may change runtime behavior @@ -280,13 +243,11 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -91 | - - if sys.version_info.major < 3: - - print("3") - - else: - - print("2") +92 - if sys.version_info.major < 3: +93 - print("3") +94 - else: +95 - print("2") 92 + print("2") -93 | | note: This is an unsafe fix and may change runtime behavior @@ -301,15 +262,13 @@ UP036 [*] Version block is outdated for minimum Python version 99 | else: | help: Remove outdated version block - | -96 | - - if sys.version_info.major == 3: - - print("3") - - else: - - print("2") -97 + print("3") -98 | - | + | + 97 - if sys.version_info.major == 3: + 98 - print("3") + 99 - else: +100 - print("2") + 97 + print("3") + | note: This is an unsafe fix and may change runtime behavior UP036 [*] Version block is outdated for minimum Python version @@ -324,12 +283,10 @@ UP036 [*] Version block is outdated for minimum Python version | help: Remove outdated version block | -108 | - - if sys.version_info.major > (3, 13): - - print(3) - - else: - - print(2) +109 - if sys.version_info.major > (3, 13): +110 - print(3) +111 - else: +112 - print(2) 109 + print(3) -110 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP037_0.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP037_0.py.snap index a9c1dba916fab..89274e19a8207 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP037_0.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP037_0.py.snap @@ -10,10 +10,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -17 | - - def foo(var: "MyClass") -> "MyClass": +18 - def foo(var: "MyClass") -> "MyClass": 18 + def foo(var: MyClass) -> "MyClass": -19 | x: "MyClass" | UP037 [*] Remove quotes from type annotation @@ -25,10 +23,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -17 | - - def foo(var: "MyClass") -> "MyClass": +18 - def foo(var: "MyClass") -> "MyClass": 18 + def foo(var: "MyClass") -> MyClass: -19 | x: "MyClass" | UP037 [*] Remove quotes from type annotation @@ -39,10 +35,8 @@ UP037 [*] Remove quotes from type annotation | ^^^^^^^^^ help: Remove quotes | -18 | def foo(var: "MyClass") -> "MyClass": - - x: "MyClass" +19 - x: "MyClass" 19 + x: MyClass -20 | | UP037 [*] Remove quotes from type annotation @@ -54,10 +48,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -21 | - - def foo(*, inplace: "bool"): +22 - def foo(*, inplace: "bool"): 22 + def foo(*, inplace: bool): -23 | pass | UP037 [*] Remove quotes from type annotation @@ -69,10 +61,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -25 | - - def foo(*args: "str", **kwargs: "int"): +26 - def foo(*args: "str", **kwargs: "int"): 26 + def foo(*args: str, **kwargs: "int"): -27 | pass | UP037 [*] Remove quotes from type annotation @@ -84,10 +74,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -25 | - - def foo(*args: "str", **kwargs: "int"): +26 - def foo(*args: "str", **kwargs: "int"): 26 + def foo(*args: "str", **kwargs: int): -27 | pass | UP037 [*] Remove quotes from type annotation @@ -100,10 +88,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -29 | - - x: Tuple["MyClass"] +30 - x: Tuple["MyClass"] 30 + x: Tuple[MyClass] -31 | | UP037 [*] Remove quotes from type annotation @@ -115,10 +101,8 @@ UP037 [*] Remove quotes from type annotation | ^^^^^^^^^ help: Remove quotes | -31 | - - x: Callable[["MyClass"], None] +32 - x: Callable[["MyClass"], None] 32 + x: Callable[[MyClass], None] -33 | | UP037 [*] Remove quotes from type annotation @@ -129,10 +113,8 @@ UP037 [*] Remove quotes from type annotation | ^^^^^^^^^ help: Remove quotes | -35 | class Foo(NamedTuple): - - x: "MyClass" +36 - x: "MyClass" 36 + x: MyClass -37 | | UP037 [*] Remove quotes from type annotation @@ -143,10 +125,8 @@ UP037 [*] Remove quotes from type annotation | ^^^^^ help: Remove quotes | -39 | class D(TypedDict): - - E: TypedDict("E", foo="int", total=False) +40 - E: TypedDict("E", foo="int", total=False) 40 + E: TypedDict("E", foo=int, total=False) -41 | | UP037 [*] Remove quotes from type annotation @@ -157,10 +137,8 @@ UP037 [*] Remove quotes from type annotation | ^^^^^ help: Remove quotes | -43 | class D(TypedDict): - - E: TypedDict("E", {"foo": "int"}) +44 - E: TypedDict("E", {"foo": "int"}) 44 + E: TypedDict("E", {"foo": int}) -45 | | UP037 [*] Remove quotes from type annotation @@ -173,10 +151,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -46 | - - x: Annotated["str", "metadata"] +47 - x: Annotated["str", "metadata"] 47 + x: Annotated[str, "metadata"] -48 | | UP037 [*] Remove quotes from type annotation @@ -191,10 +167,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -48 | - - x: Arg("str", "name") +49 - x: Arg("str", "name") 49 + x: Arg(str, "name") -50 | | UP037 [*] Remove quotes from type annotation @@ -209,10 +183,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -50 | - - x: DefaultArg("str", "name") +51 - x: DefaultArg("str", "name") 51 + x: DefaultArg(str, "name") -52 | | UP037 [*] Remove quotes from type annotation @@ -227,10 +199,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -52 | - - x: NamedArg("str", "name") +53 - x: NamedArg("str", "name") 53 + x: NamedArg(str, "name") -54 | | UP037 [*] Remove quotes from type annotation @@ -245,10 +215,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -54 | - - x: DefaultNamedArg("str", "name") +55 - x: DefaultNamedArg("str", "name") 55 + x: DefaultNamedArg(str, "name") -56 | | UP037 [*] Remove quotes from type annotation @@ -263,10 +231,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -56 | - - x: DefaultNamedArg("str", name="name") +57 - x: DefaultNamedArg("str", name="name") 57 + x: DefaultNamedArg(str, name="name") -58 | | UP037 [*] Remove quotes from type annotation @@ -281,10 +247,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -58 | - - x: VarArg("str") +59 - x: VarArg("str") 59 + x: VarArg(str) -60 | | UP037 [*] Remove quotes from type annotation @@ -299,10 +263,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -60 | - - x: List[List[List["MyClass"]]] +61 - x: List[List[List["MyClass"]]] 61 + x: List[List[List[MyClass]]] -62 | | UP037 [*] Remove quotes from type annotation @@ -317,10 +279,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -62 | - - x: NamedTuple("X", [("foo", "int"), ("bar", "str")]) +63 - x: NamedTuple("X", [("foo", "int"), ("bar", "str")]) 63 + x: NamedTuple("X", [("foo", int), ("bar", "str")]) -64 | | UP037 [*] Remove quotes from type annotation @@ -335,10 +295,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -62 | - - x: NamedTuple("X", [("foo", "int"), ("bar", "str")]) +63 - x: NamedTuple("X", [("foo", "int"), ("bar", "str")]) 63 + x: NamedTuple("X", [("foo", "int"), ("bar", str)]) -64 | | UP037 [*] Remove quotes from type annotation @@ -353,10 +311,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -64 | - - x: NamedTuple("X", fields=[("foo", "int"), ("bar", "str")]) +65 - x: NamedTuple("X", fields=[("foo", "int"), ("bar", "str")]) 65 + x: NamedTuple("X", fields=[(foo, "int"), ("bar", "str")]) -66 | | UP037 [*] Remove quotes from type annotation @@ -371,10 +327,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -64 | - - x: NamedTuple("X", fields=[("foo", "int"), ("bar", "str")]) +65 - x: NamedTuple("X", fields=[("foo", "int"), ("bar", "str")]) 65 + x: NamedTuple("X", fields=[("foo", int), ("bar", "str")]) -66 | | UP037 [*] Remove quotes from type annotation @@ -389,10 +343,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -64 | - - x: NamedTuple("X", fields=[("foo", "int"), ("bar", "str")]) +65 - x: NamedTuple("X", fields=[("foo", "int"), ("bar", "str")]) 65 + x: NamedTuple("X", fields=[("foo", "int"), (bar, "str")]) -66 | | UP037 [*] Remove quotes from type annotation @@ -407,10 +359,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -64 | - - x: NamedTuple("X", fields=[("foo", "int"), ("bar", "str")]) +65 - x: NamedTuple("X", fields=[("foo", "int"), ("bar", "str")]) 65 + x: NamedTuple("X", fields=[("foo", "int"), ("bar", str)]) -66 | | UP037 [*] Remove quotes from type annotation @@ -425,10 +375,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -66 | - - x: NamedTuple(typename="X", fields=[("foo", "int")]) +67 - x: NamedTuple(typename="X", fields=[("foo", "int")]) 67 + x: NamedTuple(typename=X, fields=[("foo", "int")]) -68 | | UP037 [*] Remove quotes from type annotation @@ -443,10 +391,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -66 | - - x: NamedTuple(typename="X", fields=[("foo", "int")]) +67 - x: NamedTuple(typename="X", fields=[("foo", "int")]) 67 + x: NamedTuple(typename="X", fields=[(foo, "int")]) -68 | | UP037 [*] Remove quotes from type annotation @@ -461,10 +407,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -66 | - - x: NamedTuple(typename="X", fields=[("foo", "int")]) +67 - x: NamedTuple(typename="X", fields=[("foo", "int")]) 67 + x: NamedTuple(typename="X", fields=[("foo", int)]) -68 | | UP037 [*] Remove quotes from type annotation @@ -478,11 +422,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -111 | # See https://github.com/astral-sh/ruff/issues/15816 - - def f() -> "Literal[0]#": -112 + def f() -> (Literal[0]# -113 + ): -114 | return 0 +112 ~ def f() -> (Literal[0]# +113 ~ ): | UP037 [*] Remove quotes from type annotation @@ -496,11 +437,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -114 | - - def g(x: "Literal['abc']#") -> None: -115 + def g(x: (Literal['abc']# -116 + )) -> None: -117 | return +115 ~ def g(x: (Literal['abc']# +116 ~ )) -> None: | UP037 [*] Remove quotes from type annotation @@ -518,15 +456,11 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -117 | - - def f() -> """Literal[0] -118 + def f() -> (Literal[0] -119 | # -120 | - - """: +118 ~ def f() -> (Literal[0] +119 + # +120 + 121 + -122 + ): -123 | return 0 +122 ~ ): | UP037 [*] Remove quotes from type annotation @@ -539,12 +473,9 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -124 | # https://github.com/astral-sh/ruff/issues/19835 - - def foo(bar: "A\n#"): ... -125 + def foo(bar: (A +125 ~ def foo(bar: (A 126 + # -127 + )): ... -128 | def foo(bar: "A\n#\n"): ... +127 ~ )): ... | UP037 [*] Remove quotes from type annotation @@ -556,10 +487,8 @@ UP037 [*] Remove quotes from type annotation | ^^^^^^^^ help: Remove quotes | -125 | def foo(bar: "A\n#"): ... - - def foo(bar: "A\n#\n"): ... -126 + def foo(bar: (A +126 ~ def foo(bar: (A 127 + # -128 + -129 + )): ... +128 + +129 ~ )): ... | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP037_1.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP037_1.py.snap index 09e59a880d1ef..c286b0b9c1068 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP037_1.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP037_1.py.snap @@ -11,12 +11,10 @@ UP037 [*] Remove quotes from type annotation 10 | print(x) | help: Remove quotes - | -8 | # UP037 - - x: "Tuple[int, int]" = (0, 0) -9 + x: Tuple[int, int] = (0, 0) -10 | print(x) - | + | +9 - x: "Tuple[int, int]" = (0, 0) +9 + x: Tuple[int, int] = (0, 0) + | UP037 [*] Remove quotes from type annotation --> UP037_1.py:14:4 @@ -26,7 +24,6 @@ UP037 [*] Remove quotes from type annotation | ^^^^^^^^^^^^^^^^^ help: Remove quotes | -13 | # OK - - X: "Tuple[int, int]" = (0, 0) +14 - X: "Tuple[int, int]" = (0, 0) 14 + X: Tuple[int, int] = (0, 0) | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP037_2.pyi.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP037_2.pyi.snap index 5ef03783a7fa3..93c9e61fc31a0 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP037_2.pyi.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP037_2.pyi.snap @@ -10,11 +10,8 @@ UP037 [*] Remove quotes from type annotation | ^^^^^^^^^^^^^^^^^^^^^^^ help: Remove quotes | -2 | - - def f(a: Foo['SingleLine # Comment']): ... -3 + def f(a: Foo[(SingleLine # Comment -4 + )]): ... -5 | +3 ~ def f(a: Foo[(SingleLine # Comment +4 ~ )]): ... | UP037 [*] Remove quotes from type annotation @@ -27,13 +24,9 @@ UP037 [*] Remove quotes from type annotation | |____________^ help: Remove quotes | -5 | - - def f(a: Foo['''Bar[ -6 + def f(a: Foo[Bar[ -7 | Multi | - - Line]''']): ... -8 + Line]]): ... -9 | +6 ~ def f(a: Foo[Bar[ +7 + Multi | +8 ~ Line]]): ... | UP037 [*] Remove quotes from type annotation @@ -47,14 +40,10 @@ UP037 [*] Remove quotes from type annotation | |____^ help: Remove quotes | -10 | - - def f(a: Foo['''Bar[ -11 + def f(a: Foo[Bar[ -12 | Multi | -13 | Line # Comment - - ]''']): ... -14 + ]]): ... -15 | +11 ~ def f(a: Foo[Bar[ +12 + Multi | +13 + Line # Comment +14 ~ ]]): ... | UP037 [*] Remove quotes from type annotation @@ -67,14 +56,10 @@ UP037 [*] Remove quotes from type annotation | |_______________________^ help: Remove quotes | -16 | - - def f(a: Foo['''Bar[ -17 + def f(a: Foo[(Bar[ -18 | Multi | - - Line] # Comment''']): ... +17 ~ def f(a: Foo[(Bar[ +18 + Multi | 19 + Line] # Comment -20 + )]): ... -21 | +20 ~ )]): ... | UP037 [*] Remove quotes from type annotation @@ -88,15 +73,11 @@ UP037 [*] Remove quotes from type annotation | |_______________________^ help: Remove quotes | -21 | - - def f(a: Foo[''' -22 + def f(a: Foo[( -23 | Bar[ -24 | Multi | - - Line] # Comment''']): ... +22 ~ def f(a: Foo[( +23 + Bar[ +24 + Multi | 25 + Line] # Comment -26 + )]): ... -27 | +26 ~ )]): ... | UP037 [*] Remove quotes from type annotation @@ -108,12 +89,8 @@ UP037 [*] Remove quotes from type annotation | |_______^ help: Remove quotes | -27 | - - def f(a: '''list[int] - - ''' = []): ... -28 + def f(a: list[int] -29 + = []): ... -30 | +28 ~ def f(a: list[int] +29 ~ = []): ... | UP037 [*] Remove quotes from type annotation @@ -125,12 +102,8 @@ UP037 [*] Remove quotes from type annotation | |____________^ help: Remove quotes | -31 | - - a: '''\\ - - list[int]''' = [42] -32 + a: (\ -33 + list[int]) = [42] -34 | +32 ~ a: (\ +33 ~ list[int]) = [42] | UP037 [*] Remove quotes from type annotation @@ -143,13 +116,9 @@ UP037 [*] Remove quotes from type annotation | |_______^ help: Remove quotes | -35 | - - def f(a: ''' -36 + def f(a: -37 | list[int] - - ''' = []): ... -38 + = []): ... -39 | +36 ~ def f(a: +37 ~ list[int] +38 ~ = []): ... | UP037 [*] Remove quotes from type annotation @@ -165,17 +134,13 @@ UP037 [*] Remove quotes from type annotation | |___________________^ help: Remove quotes | -40 | - - def f(a: Foo[''' -41 + def f(a: Foo[( -42 | Bar -43 | [ -44 | Multi | -45 | Line - - ] # Comment''']): ... +41 ~ def f(a: Foo[( +42 + Bar +43 + [ +44 + Multi | +45 + Line 46 + ] # Comment -47 + )]): ... -48 | +47 ~ )]): ... | UP037 [*] Remove quotes from type annotation @@ -187,9 +152,6 @@ UP037 [*] Remove quotes from type annotation | |________^ help: Remove quotes | -48 | - - a: '''list - - [int]''' = [42] -49 + a: (list -50 + [int]) = [42] +49 ~ a: (list +50 ~ [int]) = [42] | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP037_3.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP037_3.py.snap index f16c938d508b9..6b332084290de 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP037_3.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP037_3.py.snap @@ -13,10 +13,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -14 | class EmptyCell: - - _singleton: ClassVar[Optional["EmptyCell"]] = None +15 - _singleton: ClassVar[Optional["EmptyCell"]] = None 15 + _singleton: ClassVar[Optional[EmptyCell]] = None -16 | # the behavior of _singleton above should match a non-ClassVar | UP037 [*] Remove quotes from type annotation @@ -28,7 +26,6 @@ UP037 [*] Remove quotes from type annotation | ^^^^^^^^^^^ help: Remove quotes | -16 | # the behavior of _singleton above should match a non-ClassVar - - _doubleton: "EmptyCell" +17 - _doubleton: "EmptyCell" 17 + _doubleton: EmptyCell | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP038.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP038.py.snap index ca26fe057e77f..5a1e1d860efee 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP038.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP038.py.snap @@ -10,9 +10,8 @@ UP038 [*] Use `X | Y` in `isinstance` call instead of `(X, Y)` | help: Convert to `X | Y` | - - isinstance(1, (int, float)) # UP038 +1 - isinstance(1, (int, float)) # UP038 1 + isinstance(1, int | float) # UP038 -2 | issubclass("yes", (int, float, str)) # UP038 | note: This is an unsafe fix and may change runtime behavior @@ -27,9 +26,7 @@ UP038 [*] Use `X | Y` in `issubclass` call instead of `(X, Y)` | help: Convert to `X | Y` | -1 | isinstance(1, (int, float)) # UP038 - - issubclass("yes", (int, float, str)) # UP038 +2 - issubclass("yes", (int, float, str)) # UP038 2 + issubclass("yes", int | float | str) # UP038 -3 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP039.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP039.py.snap index 29e0906293c7c..62a61b265fd94 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP039.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP039.py.snap @@ -11,10 +11,8 @@ UP039 [*] Unnecessary parentheses after class definition | help: Remove parentheses | -1 | # Errors - - class A(): +2 - class A(): 2 + class A: -3 | pass | UP039 [*] Unnecessary parentheses after class definition @@ -27,10 +25,8 @@ UP039 [*] Unnecessary parentheses after class definition | help: Remove parentheses | -5 | - - class A() \ +6 - class A() \ 6 + class A \ -7 | : | UP039 [*] Unnecessary parentheses after class definition @@ -43,10 +39,8 @@ UP039 [*] Unnecessary parentheses after class definition | help: Remove parentheses | -11 | class A \ - - (): +12 - (): 12 + : -13 | pass | UP039 [*] Unnecessary parentheses after class definition @@ -59,10 +53,8 @@ UP039 [*] Unnecessary parentheses after class definition | help: Remove parentheses | -16 | @decorator() - - class A(): +17 - class A(): 17 + class A: -18 | pass | UP039 [*] Unnecessary parentheses after class definition @@ -75,10 +67,8 @@ UP039 [*] Unnecessary parentheses after class definition | help: Remove parentheses | -20 | @decorator - - class A(): +21 - class A(): 21 + class A: -22 | pass | UP039 [*] Unnecessary parentheses after class definition @@ -91,10 +81,9 @@ UP039 [*] Unnecessary parentheses after class definition | |_^ help: Remove parentheses | -45 | - - class Foo( - - # text - - ): ... +46 - class Foo( +47 - # text +48 - ): ... 46 + class Foo: ... | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP040.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP040.py.snap index 2baabf904c267..16819f00eb10c 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP040.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP040.py.snap @@ -11,10 +11,8 @@ UP040 [*] Type alias `x` uses `TypeAlias` annotation instead of the `type` keywo | help: Use the `type` keyword | -4 | # UP040 - - x: typing.TypeAlias = int +5 - x: typing.TypeAlias = int 5 + type x = int -6 | x: TypeAlias = int | note: This is an unsafe fix and may change runtime behavior @@ -30,10 +28,8 @@ UP040 [*] Type alias `x` uses `TypeAlias` annotation instead of the `type` keywo | help: Use the `type` keyword | -5 | x: typing.TypeAlias = int - - x: TypeAlias = int +6 - x: TypeAlias = int 6 + type x = int -7 | | note: This is an unsafe fix and may change runtime behavior @@ -49,10 +45,8 @@ UP040 [*] Type alias `x` uses `TypeAlias` annotation instead of the `type` keywo | help: Use the `type` keyword | -9 | T = typing.TypeVar["T"] - - x: typing.TypeAlias = list[T] +10 - x: typing.TypeAlias = list[T] 10 + type x[T] = list[T] -11 | | note: This is an unsafe fix and may change runtime behavior @@ -68,10 +62,8 @@ UP040 [*] Type alias `x` uses `TypeAlias` annotation instead of the `type` keywo | help: Use the `type` keyword | -13 | T = typing.TypeVar("T") - - x: typing.TypeAlias = list[T] +14 - x: typing.TypeAlias = list[T] 14 + type x[T] = list[T] -15 | | note: This is an unsafe fix and may change runtime behavior @@ -87,10 +79,8 @@ UP040 [*] Type alias `x` uses `TypeAlias` annotation instead of the `type` keywo | help: Use the `type` keyword | -17 | T = typing.TypeVar("T", bound=int) - - x: typing.TypeAlias = list[T] +18 - x: typing.TypeAlias = list[T] 18 + type x[T: int] = list[T] -19 | | note: This is an unsafe fix and may change runtime behavior @@ -106,10 +96,8 @@ UP040 [*] Type alias `x` uses `TypeAlias` annotation instead of the `type` keywo | help: Use the `type` keyword | -21 | T = typing.TypeVar("T", int, str) - - x: typing.TypeAlias = list[T] +22 - x: typing.TypeAlias = list[T] 22 + type x[T: (int, str)] = list[T] -23 | | note: This is an unsafe fix and may change runtime behavior @@ -125,10 +113,8 @@ UP040 [*] Type alias `x` uses `TypeAlias` annotation instead of the `type` keywo | help: Use the `type` keyword | -25 | T = typing.TypeVar("T", contravariant=True) - - x: typing.TypeAlias = list[T] +26 - x: typing.TypeAlias = list[T] 26 + type x[T] = list[T] -27 | | note: This is an unsafe fix and may change runtime behavior @@ -144,10 +130,8 @@ UP040 [*] Type alias `x` uses `TypeAlias` annotation instead of the `type` keywo | help: Use the `type` keyword | -29 | T = typing.TypeVar("T", covariant=True) - - x: typing.TypeAlias = list[T] +30 - x: typing.TypeAlias = list[T] 30 + type x[T] = list[T] -31 | | note: This is an unsafe fix and may change runtime behavior @@ -163,10 +147,8 @@ UP040 [*] Type alias `x` uses `TypeAlias` annotation instead of the `type` keywo | help: Use the `type` keyword | -35 | # reference to global variable - - x: typing.TypeAlias = list[T] +36 - x: typing.TypeAlias = list[T] 36 + type x[T] = list[T] -37 | | note: This is an unsafe fix and may change runtime behavior @@ -182,10 +164,8 @@ UP040 [*] Type alias `y` uses `TypeAlias` annotation instead of the `type` keywo | help: Use the `type` keyword | -39 | TCLS = typing.TypeVar["TCLS"] - - y: typing.TypeAlias = list[TCLS] +40 - y: typing.TypeAlias = list[TCLS] 40 + type y[TCLS] = list[TCLS] -41 | | note: This is an unsafe fix and may change runtime behavior @@ -201,10 +181,8 @@ UP040 [*] Type alias `x` uses `TypeAlias` annotation instead of the `type` keywo | help: Use the `type` keyword | -43 | T = typing.TypeVar(*args) - - x: typing.TypeAlias = list[T] +44 - x: typing.TypeAlias = list[T] 44 + type x = list[T] -45 | | note: This is an unsafe fix and may change runtime behavior @@ -217,10 +195,8 @@ UP040 [*] Type alias `Decorator` uses `TypeAlias` annotation instead of the `typ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use the `type` keyword | -56 | T = typing.TypeVar["T"] - - Decorator: TypeAlias = typing.Callable[[T], T] +57 - Decorator: TypeAlias = typing.Callable[[T], T] 57 + type Decorator[T] = typing.Callable[[T], T] -58 | | note: This is an unsafe fix and may change runtime behavior @@ -238,12 +214,10 @@ UP040 [*] Type alias `PositiveList` uses `TypeAliasType` assignment instead of t | help: Use the `type` keyword | -66 | T = TypeVar("T") - - PositiveList = TypeAliasType( - - "PositiveList", list[Annotated[T, Gt(0)]], type_params=(T,) - - ) +67 - PositiveList = TypeAliasType( +68 - "PositiveList", list[Annotated[T, Gt(0)]], type_params=(T,) +69 - ) 67 + type PositiveList[T] = list[Annotated[T, Gt(0)]] -68 | | UP040 [*] Type alias `PositiveList` uses `TypeAliasType` assignment instead of the `type` keyword @@ -260,12 +234,10 @@ UP040 [*] Type alias `PositiveList` uses `TypeAliasType` assignment instead of t | help: Use the `type` keyword | -72 | T = TypeVar("T", bound=SupportGt) - - PositiveList = TypeAliasType( - - "PositiveList", list[Annotated[T, Gt(0)]], type_params=(T,) - - ) +73 - PositiveList = TypeAliasType( +74 - "PositiveList", list[Annotated[T, Gt(0)]], type_params=(T,) +75 - ) 73 + type PositiveList[T: SupportGt] = list[Annotated[T, Gt(0)]] -74 | | UP040 [*] Type alias `Tuple3` uses `TypeAliasType` assignment instead of the `type` keyword @@ -280,10 +252,8 @@ UP040 [*] Type alias `Tuple3` uses `TypeAliasType` assignment instead of the `ty | help: Use the `type` keyword | -80 | T3 = TypeVar("T3") - - Tuple3 = TypeAliasType("Tuple3", tuple[T1, T2, T3], type_params=(T1, T2, T3)) +81 - Tuple3 = TypeAliasType("Tuple3", tuple[T1, T2, T3], type_params=(T1, T2, T3)) 81 + type Tuple3[T1: SupportGt, T2, T3] = tuple[T1, T2, T3] -82 | | UP040 [*] Type alias `PositiveInt` uses `TypeAliasType` assignment instead of the `type` keyword @@ -296,10 +266,8 @@ UP040 [*] Type alias `PositiveInt` uses `TypeAliasType` assignment instead of th | help: Use the `type` keyword | -83 | # No type_params - - PositiveInt = TypeAliasType("PositiveInt", Annotated[int, Gt(0)]) +84 - PositiveInt = TypeAliasType("PositiveInt", Annotated[int, Gt(0)]) 84 + type PositiveInt = Annotated[int, Gt(0)] -85 | PositiveInt = TypeAliasType("PositiveInt", Annotated[int, Gt(0)], type_params=()) | UP040 [*] Type alias `PositiveInt` uses `TypeAliasType` assignment instead of the `type` keyword @@ -314,10 +282,8 @@ UP040 [*] Type alias `PositiveInt` uses `TypeAliasType` assignment instead of th | help: Use the `type` keyword | -84 | PositiveInt = TypeAliasType("PositiveInt", Annotated[int, Gt(0)]) - - PositiveInt = TypeAliasType("PositiveInt", Annotated[int, Gt(0)], type_params=()) +85 - PositiveInt = TypeAliasType("PositiveInt", Annotated[int, Gt(0)], type_params=()) 85 + type PositiveInt = Annotated[int, Gt(0)] -86 | | UP040 [*] Type alias `PositiveList` uses `TypeAliasType` assignment instead of the `type` keyword @@ -334,12 +300,10 @@ UP040 [*] Type alias `PositiveList` uses `TypeAliasType` assignment instead of t | help: Use the `type` keyword | -98 | T = TypeVar("T") - - PositiveList = TypeAliasType( # eaten comment - - "PositiveList", list[Annotated[T, Gt(0)]], type_params=(T,) - - ) -99 + type PositiveList[T] = list[Annotated[T, Gt(0)]] -100 | + 99 - PositiveList = TypeAliasType( # eaten comment +100 - "PositiveList", list[Annotated[T, Gt(0)]], type_params=(T,) +101 - ) + 99 + type PositiveList[T] = list[Annotated[T, Gt(0)]] | note: This is an unsafe fix and may change runtime behavior @@ -353,12 +317,10 @@ UP040 [*] Type alias `PositiveList` uses `TypeAliasType` assignment instead of t | |_^ help: Use the `type` keyword | -103 | T = TypeVar("T") - - PositiveList = TypeAliasType( - - "PositiveList", list[Annotated[T, Gt(0)]], type_params=(T,) - - ) # this comment should be okay +104 - PositiveList = TypeAliasType( +105 - "PositiveList", list[Annotated[T, Gt(0)]], type_params=(T,) +106 - ) # this comment should be okay 104 + type PositiveList[T] = list[Annotated[T, Gt(0)]] # this comment should be okay -105 | | UP040 [*] Type alias `PositiveList` uses `TypeAliasType` assignment instead of the `type` keyword @@ -377,15 +339,9 @@ UP040 [*] Type alias `PositiveList` uses `TypeAliasType` assignment instead of t | help: Use the `type` keyword | -110 | T = TypeVar("T") - - PositiveList = TypeAliasType( - - "PositiveList", list[ 111 + type PositiveList[T] = list[ -112 | Annotated[T, Gt(0)], # preserved comment - - ], type_params=(T,) - - ) +112 + Annotated[T, Gt(0)], # preserved comment 113 + ] -114 | | UP040 [*] Type alias `T` uses `TypeAlias` annotation instead of the `type` keyword @@ -403,10 +359,10 @@ UP040 [*] Type alias `T` uses `TypeAlias` annotation instead of the `type` keywo | help: Use the `type` keyword | -116 | - - T: TypeAlias = ( 117 + type T = ( -118 | int +118 + int +119 + | str +120 + ) | note: This is an unsafe fix and may change runtime behavior @@ -430,9 +386,14 @@ UP040 [*] Type alias `T` uses `TypeAlias` annotation instead of the `type` keywo | help: Use the `type` keyword | -121 | - - T: TypeAlias = ( # comment0 122 + type T = ( # comment0 -123 | # comment1 +123 + # comment1 +124 + int # comment2 +125 + # comment3 +126 + | # comment4 +127 + # comment5 +128 + str # comment6 +129 + # comment7 +130 ~ ) # comment8 | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP040.py__preview_diff.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP040.py__preview_diff.snap index 81fb3d356d626..0dda436efe9da 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP040.py__preview_diff.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP040.py__preview_diff.snap @@ -22,10 +22,8 @@ UP040 [*] Type alias `x` uses `TypeAlias` annotation instead of the `type` keywo | help: Use the `type` keyword | -47 | T = typing.TypeVar("T", default=Any) - - x: typing.TypeAlias = list[T] +48 - x: typing.TypeAlias = list[T] 48 + type x[T = Any] = list[T] -49 | | note: This is an unsafe fix and may change runtime behavior @@ -42,10 +40,8 @@ UP040 [*] Type alias `AnyList` uses `TypeAliasType` assignment instead of the `t | help: Use the `type` keyword | -94 | T = typing.TypeVar("T", default=Any) - - AnyList = TypeAliasType("AnyList", list[T], type_params=(T,)) +95 - AnyList = TypeAliasType("AnyList", list[T], type_params=(T,)) 95 + type AnyList[T = Any] = list[T] -96 | | @@ -58,8 +54,7 @@ UP040 [*] Type alias `DefaultList` uses `TypeAlias` annotation instead of the `t | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use the `type` keyword | -133 | T_default = TypeVar("T_default", default=int) - - DefaultList: TypeAlias = list[T_default] +134 - DefaultList: TypeAlias = list[T_default] 134 + type DefaultList[T_default = int] = list[T_default] | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP040.pyi.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP040.pyi.snap index c37220ce2a159..ffc78266987a0 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP040.pyi.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP040.pyi.snap @@ -12,10 +12,8 @@ UP040 [*] Type alias `x` uses `TypeAlias` annotation instead of the `type` keywo | help: Use the `type` keyword | -5 | # Fixes in type stub files should be safe to apply unlike in regular code where runtime behavior could change - - x: typing.TypeAlias = int +6 - x: typing.TypeAlias = int 6 + type x = int -7 | x: TypeAlias = int | UP040 [*] Type alias `x` uses `TypeAlias` annotation instead of the `type` keyword @@ -27,10 +25,8 @@ UP040 [*] Type alias `x` uses `TypeAlias` annotation instead of the `type` keywo | ^^^^^^^^^^^^^^^^^^ help: Use the `type` keyword | -6 | x: typing.TypeAlias = int - - x: TypeAlias = int +7 - x: TypeAlias = int 7 + type x = int -8 | | UP040 [*] Type alias `x` uses `TypeAlias` annotation instead of the `type` keyword @@ -47,10 +43,10 @@ UP040 [*] Type alias `x` uses `TypeAlias` annotation instead of the `type` keywo | help: Use the `type` keyword | -10 | # comments in the value are preserved - - x: TypeAlias = tuple[ 11 + type x = tuple[ -12 | int, # preserved +12 + int, # preserved +13 + float, +14 + ] | UP040 [*] Type alias `T` uses `TypeAlias` annotation instead of the `type` keyword @@ -70,8 +66,13 @@ UP040 [*] Type alias `T` uses `TypeAlias` annotation instead of the `type` keywo | |_^ help: Use the `type` keyword | -15 | - - T: TypeAlias = ( # comment0 16 + type T = ( # comment0 -17 | # comment1 +17 + # comment1 +18 + int # comment2 +19 + # comment3 +20 + | # comment4 +21 + # comment5 +22 + str # comment6 +23 + # comment7 +24 ~ ) # comment8 | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP041.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP041.py.snap index 5cf0b014d72ad..f7371613ce6e7 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP041.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP041.py.snap @@ -12,10 +12,8 @@ UP041 [*] Replace aliased errors with `TimeoutError` | help: Replace `asyncio.TimeoutError` with builtin `TimeoutError` | -4 | pass - - except asyncio.TimeoutError: +5 - except asyncio.TimeoutError: 5 + except TimeoutError: -6 | pass | UP041 [*] Replace aliased errors with `TimeoutError` @@ -29,10 +27,8 @@ UP041 [*] Replace aliased errors with `TimeoutError` | help: Replace `socket.timeout` with builtin `TimeoutError` | -9 | pass - - except socket.timeout: +10 - except socket.timeout: 10 + except TimeoutError: -11 | pass | UP041 [*] Replace aliased errors with `TimeoutError` @@ -46,10 +42,8 @@ UP041 [*] Replace aliased errors with `TimeoutError` | help: Replace with builtin `TimeoutError` | -16 | pass - - except (asyncio.TimeoutError,): +17 - except (asyncio.TimeoutError,): 17 + except TimeoutError: -18 | pass | UP041 [*] Replace aliased errors with `TimeoutError` @@ -63,10 +57,8 @@ UP041 [*] Replace aliased errors with `TimeoutError` | help: Replace with builtin `TimeoutError` | -21 | pass - - except (socket.timeout,): +22 - except (socket.timeout,): 22 + except TimeoutError: -23 | pass | UP041 [*] Replace aliased errors with `TimeoutError` @@ -80,10 +72,8 @@ UP041 [*] Replace aliased errors with `TimeoutError` | help: Replace with builtin `TimeoutError` | -26 | pass - - except (asyncio.TimeoutError, socket.timeout,): +27 - except (asyncio.TimeoutError, socket.timeout,): 27 + except TimeoutError: -28 | pass | UP041 [*] Replace aliased errors with `TimeoutError` @@ -97,10 +87,8 @@ UP041 [*] Replace aliased errors with `TimeoutError` | help: Replace with builtin `TimeoutError` | -33 | pass - - except (asyncio.TimeoutError, socket.timeout, KeyError, TimeoutError): +34 - except (asyncio.TimeoutError, socket.timeout, KeyError, TimeoutError): 34 + except (KeyError, TimeoutError): -35 | pass | UP041 [*] Replace aliased errors with `TimeoutError` @@ -114,10 +102,8 @@ UP041 [*] Replace aliased errors with `TimeoutError` | help: Replace with builtin `TimeoutError` | -41 | pass - - except (asyncio.TimeoutError, error): +42 - except (asyncio.TimeoutError, error): 42 + except (TimeoutError, error): -43 | pass | UP041 [*] Replace aliased errors with `TimeoutError` @@ -132,11 +118,9 @@ UP041 [*] Replace aliased errors with `TimeoutError` | help: Replace `asyncio.TimeoutError` with builtin `TimeoutError` | -71 | raise ( - - asyncio. - - # text - - TimeoutError +72 - asyncio. +73 - # text +74 - TimeoutError 72 + TimeoutError -73 | ) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP042.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP042.py.snap index dae543a0e8099..e5270fa0f1b37 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP042.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP042.py.snap @@ -8,13 +8,10 @@ UP042 [*] Class A inherits from both `str` and `enum.Enum` | ^ help: Inherit from `enum.StrEnum` | - - from enum import Enum -1 + from enum import Enum, StrEnum +1 ~ from enum import Enum, StrEnum 2 | 3 | - - class A(str, Enum): ... -4 + class A(StrEnum): ... -5 | +4 ~ class A(StrEnum): ... | note: This is an unsafe fix and may change runtime behavior @@ -25,14 +22,11 @@ UP042 [*] Class B inherits from both `str` and `enum.Enum` | ^ help: Inherit from `enum.StrEnum` | - - from enum import Enum -1 + from enum import Enum, StrEnum +1 ~ from enum import Enum, StrEnum 2 | --------------------------------------------------------------------------------- +… 6 | - - class B(Enum, str): ... -7 + class B(StrEnum): ... -8 | +7 ~ class B(StrEnum): ... | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP043.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP043.py.snap index 54685ad479302..cfb176de24e1c 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP043.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP043.py.snap @@ -10,10 +10,8 @@ UP043 [*] Unnecessary default type arguments | help: Remove default type arguments | -3 | - - def func() -> Generator[int, None, None]: +4 - def func() -> Generator[int, None, None]: 4 + def func() -> Generator[int]: -5 | yield 42 | UP043 [*] Unnecessary default type arguments @@ -25,10 +23,8 @@ UP043 [*] Unnecessary default type arguments | help: Remove default type arguments | -7 | - - def func() -> Generator[int, None]: +8 - def func() -> Generator[int, None]: 8 + def func() -> Generator[int]: -9 | yield 42 | UP043 [*] Unnecessary default type arguments @@ -41,10 +37,8 @@ UP043 [*] Unnecessary default type arguments | help: Remove default type arguments | -20 | - - def func() -> Generator[int, int, None]: +21 - def func() -> Generator[int, int, None]: 21 + def func() -> Generator[int, int]: -22 | _ = yield 42 | UP043 [*] Unnecessary default type arguments @@ -56,10 +50,8 @@ UP043 [*] Unnecessary default type arguments | help: Remove default type arguments | -30 | - - async def func() -> AsyncGenerator[int, None]: +31 - async def func() -> AsyncGenerator[int, None]: 31 + async def func() -> AsyncGenerator[int]: -32 | yield 42 | UP043 [*] Unnecessary default type arguments @@ -71,10 +63,8 @@ UP043 [*] Unnecessary default type arguments | help: Remove default type arguments | -46 | - - def func() -> Generator[str, None, None]: +47 - def func() -> Generator[str, None, None]: 47 + def func() -> Generator[str]: -48 | yield "hello" | UP043 [*] Unnecessary default type arguments @@ -86,10 +76,8 @@ UP043 [*] Unnecessary default type arguments | help: Remove default type arguments | -50 | - - async def func() -> AsyncGenerator[str, None]: +51 - async def func() -> AsyncGenerator[str, None]: 51 + async def func() -> AsyncGenerator[str]: -52 | yield "hello" | UP043 [*] Unnecessary default type arguments @@ -105,12 +93,10 @@ UP043 [*] Unnecessary default type arguments | help: Remove default type arguments | -54 | - - async def func() -> AsyncGenerator[ # type: ignore - - str, - - None - - ]: +55 - async def func() -> AsyncGenerator[ # type: ignore +56 - str, +57 - None +58 - ]: 55 + async def func() -> AsyncGenerator[str]: -56 | yield "hello" | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP043.pyi.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP043.pyi.snap index 64e498ba7d3dc..d631e03da89fb 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP043.pyi.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP043.pyi.snap @@ -10,10 +10,8 @@ UP043 [*] Unnecessary default type arguments | help: Remove default type arguments | -3 | - - def func() -> Generator[int, None, None]: +4 - def func() -> Generator[int, None, None]: 4 + def func() -> Generator[int]: -5 | yield 42 | UP043 [*] Unnecessary default type arguments @@ -25,10 +23,8 @@ UP043 [*] Unnecessary default type arguments | help: Remove default type arguments | -7 | - - def func() -> Generator[int, None]: +8 - def func() -> Generator[int, None]: 8 + def func() -> Generator[int]: -9 | yield 42 | UP043 [*] Unnecessary default type arguments @@ -41,10 +37,8 @@ UP043 [*] Unnecessary default type arguments | help: Remove default type arguments | -20 | - - def func() -> Generator[int, int, None]: +21 - def func() -> Generator[int, int, None]: 21 + def func() -> Generator[int, int]: -22 | _ = yield 42 | UP043 [*] Unnecessary default type arguments @@ -56,10 +50,8 @@ UP043 [*] Unnecessary default type arguments | help: Remove default type arguments | -30 | - - async def func() -> AsyncGenerator[int, None]: +31 - async def func() -> AsyncGenerator[int, None]: 31 + async def func() -> AsyncGenerator[int]: -32 | yield 42 | UP043 [*] Unnecessary default type arguments @@ -71,10 +63,8 @@ UP043 [*] Unnecessary default type arguments | help: Remove default type arguments | -46 | - - def func() -> Generator[str, None, None]: +47 - def func() -> Generator[str, None, None]: 47 + def func() -> Generator[str]: -48 | yield "hello" | UP043 [*] Unnecessary default type arguments @@ -86,10 +76,8 @@ UP043 [*] Unnecessary default type arguments | help: Remove default type arguments | -50 | - - async def func() -> AsyncGenerator[str, None]: +51 - async def func() -> AsyncGenerator[str, None]: 51 + async def func() -> AsyncGenerator[str]: -52 | yield "hello" | UP043 [*] Unnecessary default type arguments @@ -105,12 +93,10 @@ UP043 [*] Unnecessary default type arguments | help: Remove default type arguments | -54 | - - async def func() -> AsyncGenerator[ # type: ignore - - str, - - None - - ]: +55 - async def func() -> AsyncGenerator[ # type: ignore +56 - str, +57 - None +58 - ]: 55 + async def func() -> AsyncGenerator[str]: -56 | yield "hello" | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP045_1.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP045_1.py.snap index 55a22140f422b..138c9272710a3 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP045_1.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP045_1.py.snap @@ -10,10 +10,8 @@ UP045 [*] Use `X | None` for type annotations | help: Convert to `X | None` | -4 | - - def f(x: Optional[str]) -> None: +5 - def f(x: Optional[str]) -> None: 5 + def f(x: str | None) -> None: -6 | ... | UP045 [*] Use `X | None` for type annotations @@ -24,12 +22,10 @@ UP045 [*] Use `X | None` for type annotations 10 | ... | help: Convert to `X | None` - | -8 | - - def f(x: typing.Optional[str]) -> None: -9 + def f(x: str | None) -> None: -10 | ... - | + | +9 - def f(x: typing.Optional[str]) -> None: +9 + def f(x: str | None) -> None: + | UP045 [*] Use `X | None` for type annotations --> UP045_1.py:14:8 @@ -41,10 +37,8 @@ UP045 [*] Use `X | None` for type annotations | help: Convert to `X | None` | -13 | def f() -> None: - - x: Optional[str] +14 - x: Optional[str] 14 + x: str | None -15 | x = Optional[str] | UP045 Use `X | None` for type annotations @@ -65,10 +59,8 @@ UP045 [*] Use `X | None` for type annotations | help: Convert to `X | None` | -17 | - - def f(x: list[Optional[int]]) -> None: +18 - def f(x: list[Optional[int]]) -> None: 18 + def f(x: list[int | None]) -> None: -19 | ... | UP045 Use `X | None` for type annotations @@ -111,13 +103,11 @@ UP045 [*] Use `X | None` for type annotations | |_____^ help: Convert to `X | None` | -35 | class ServiceRefOrValue: - - service_specification: Optional[ - - list[ServiceSpecificationRef] - - | list[ServiceSpecification] - - ] = None +36 - service_specification: Optional[ +37 - list[ServiceSpecificationRef] +38 - | list[ServiceSpecification] +39 - ] = None 36 + service_specification: list[ServiceSpecificationRef] | list[ServiceSpecification] | None = None -37 | | UP045 [*] Use `X | None` for type annotations @@ -129,10 +119,8 @@ UP045 [*] Use `X | None` for type annotations | ^^^^^^^^^^^^^ help: Convert to `X | None` | -43 | class ServiceRefOrValue: - - service_specification: Optional[str]is not True = None +44 - service_specification: Optional[str]is not True = None 44 + service_specification: str | None is not True = None -45 | | UP045 Use `X | None` for type annotations @@ -156,10 +144,8 @@ UP045 [*] Use `X | None` for type annotations | help: Convert to `X | None` | -75 | # Nested Optional types should be flattened - - nested_optional: Optional[Optional[str]] = None +76 - nested_optional: Optional[Optional[str]] = None 76 + nested_optional: str | None = None -77 | nested_optional_typing: typing.Optional[Optional[int]] = None | UP045 [*] Use `X | None` for type annotations @@ -174,10 +160,8 @@ UP045 [*] Use `X | None` for type annotations | help: Convert to `X | None` | -75 | # Nested Optional types should be flattened - - nested_optional: Optional[Optional[str]] = None +76 - nested_optional: Optional[Optional[str]] = None 76 + nested_optional: Optional[str | None] = None -77 | nested_optional_typing: typing.Optional[Optional[int]] = None | UP045 [*] Use `X | None` for type annotations @@ -191,10 +175,8 @@ UP045 [*] Use `X | None` for type annotations | help: Convert to `X | None` | -76 | nested_optional: Optional[Optional[str]] = None - - nested_optional_typing: typing.Optional[Optional[int]] = None +77 - nested_optional_typing: typing.Optional[Optional[int]] = None 77 + nested_optional_typing: int | None = None -78 | triple_nested_optional: Optional[Optional[Optional[str]]] = None | UP045 [*] Use `X | None` for type annotations @@ -208,10 +190,8 @@ UP045 [*] Use `X | None` for type annotations | help: Convert to `X | None` | -76 | nested_optional: Optional[Optional[str]] = None - - nested_optional_typing: typing.Optional[Optional[int]] = None +77 - nested_optional_typing: typing.Optional[Optional[int]] = None 77 + nested_optional_typing: typing.Optional[int | None] = None -78 | triple_nested_optional: Optional[Optional[Optional[str]]] = None | UP045 [*] Use `X | None` for type annotations @@ -223,10 +203,8 @@ UP045 [*] Use `X | None` for type annotations | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Convert to `X | None` | -77 | nested_optional_typing: typing.Optional[Optional[int]] = None - - triple_nested_optional: Optional[Optional[Optional[str]]] = None +78 - triple_nested_optional: Optional[Optional[Optional[str]]] = None 78 + triple_nested_optional: str | None = None -79 | | UP045 [*] Use `X | None` for type annotations @@ -238,10 +216,8 @@ UP045 [*] Use `X | None` for type annotations | ^^^^^^^^^^^^^^^^^^^^^^^ help: Convert to `X | None` | -77 | nested_optional_typing: typing.Optional[Optional[int]] = None - - triple_nested_optional: Optional[Optional[Optional[str]]] = None +78 - triple_nested_optional: Optional[Optional[Optional[str]]] = None 78 + triple_nested_optional: Optional[str | None] = None -79 | | UP045 [*] Use `X | None` for type annotations @@ -253,10 +229,8 @@ UP045 [*] Use `X | None` for type annotations | ^^^^^^^^^^^^^ help: Convert to `X | None` | -77 | nested_optional_typing: typing.Optional[Optional[int]] = None - - triple_nested_optional: Optional[Optional[Optional[str]]] = None +78 - triple_nested_optional: Optional[Optional[Optional[str]]] = None 78 + triple_nested_optional: Optional[Optional[str | None]] = None -79 | | UP045 [*] Use `X | None` for type annotations @@ -270,13 +244,11 @@ UP045 [*] Use `X | None` for type annotations | |_^ help: Convert to `X | None` | -80 | - - foo: Optional[ - - int - - # text - - ] = None +81 - foo: Optional[ +82 - int +83 - # text +84 - ] = None 81 + foo: int | None = None -82 | | note: This is an unsafe fix and may change runtime behavior @@ -292,10 +264,8 @@ UP045 [*] Use `X | None` for type annotations | help: Convert to `X | None` | -88 | # Optional[None | X] should not produce None | None - - bar: None | Optional[None | int] = None +89 - bar: None | Optional[None | int] = None 89 + bar: None | int | None = None -90 | bar: Optional[None | int] = None | UP045 [*] Use `X | None` for type annotations @@ -310,10 +280,8 @@ UP045 [*] Use `X | None` for type annotations | help: Convert to `X | None` | -89 | bar: None | Optional[None | int] = None - - bar: Optional[None | int] = None +90 - bar: Optional[None | int] = None 90 + bar: int | None = None -91 | bar: Optional[int | None] = None | UP045 [*] Use `X | None` for type annotations @@ -328,10 +296,8 @@ UP045 [*] Use `X | None` for type annotations | help: Convert to `X | None` | -90 | bar: Optional[None | int] = None - - bar: Optional[int | None] = None +91 - bar: Optional[int | None] = None 91 + bar: int | None = None -92 | bar: Optional[None | int | str] = None | UP045 [*] Use `X | None` for type annotations @@ -345,10 +311,8 @@ UP045 [*] Use `X | None` for type annotations | help: Convert to `X | None` | -91 | bar: Optional[int | None] = None - - bar: Optional[None | int | str] = None +92 - bar: Optional[None | int | str] = None 92 + bar: int | str | None = None -93 | bar: Optional[None | None] = None | UP045 Use `X | None` for type annotations diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP045_2.py_preview_with_fa100_and_future_annotations_py310.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP045_2.py_preview_with_fa100_and_future_annotations_py310.snap index 6b61f19257ba2..a79b21fe60a39 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP045_2.py_preview_with_fa100_and_future_annotations_py310.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP045_2.py_preview_with_fa100_and_future_annotations_py310.snap @@ -10,10 +10,8 @@ UP045 [*] Use `X | None` for type annotations | help: Convert to `X | None` | -4 | - - def f(x: Optional[str]) -> None: +5 - def f(x: Optional[str]) -> None: 5 + def f(x: str | None) -> None: -6 | ... | UP045 [*] Use `X | None` for type annotations @@ -24,9 +22,7 @@ UP045 [*] Use `X | None` for type annotations 10 | ... | help: Convert to `X | None` - | -8 | - - def f(x: typing.Optional[str]) -> None: -9 + def f(x: str | None) -> None: -10 | ... - | + | +9 - def f(x: typing.Optional[str]) -> None: +9 + def f(x: str | None) -> None: + | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP046_0.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP046_0.py.snap index 0dcc52d70435b..a0dfac1f1acc4 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP046_0.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP046_0.py.snap @@ -11,10 +11,8 @@ UP046 [*] Generic class `A` uses `Generic` subclass instead of type parameters | help: Use type parameters | -10 | - - class A(Generic[T]): +11 - class A(Generic[T]): 11 + class A[T: float]: -12 | # Comments in a class body are preserved | note: This is an unsafe fix and may change runtime behavior @@ -27,10 +25,8 @@ UP046 [*] Generic class `B` uses `Generic` subclass instead of type parameters | help: Use type parameters | -15 | - - class B(Generic[*Ts]): +16 - class B(Generic[*Ts]): 16 + class B[*Ts]: -17 | var: tuple[*Ts] | note: This is an unsafe fix and may change runtime behavior @@ -43,10 +39,8 @@ UP046 [*] Generic class `C` uses `Generic` subclass instead of type parameters | help: Use type parameters | -19 | - - class C(Generic[P]): +20 - class C(Generic[P]): 20 + class C[**P]: -21 | var: P | note: This is an unsafe fix and may change runtime behavior @@ -59,10 +53,8 @@ UP046 [*] Generic class `Constrained` uses `Generic` subclass instead of type pa | help: Use type parameters | -23 | - - class Constrained(Generic[S]): +24 - class Constrained(Generic[S]): 24 + class Constrained[S: (str, bytes)]: -25 | var: S | note: This is an unsafe fix and may change runtime behavior @@ -89,10 +81,8 @@ UP046 [*] Generic class `MyStr` uses `Generic` subclass instead of type paramete | help: Use type parameters | -36 | # known TypeVar - - class MyStr(Generic[AnyStr]): +37 - class MyStr(Generic[AnyStr]): 37 + class MyStr[AnyStr: (bytes, str)]: -38 | s: AnyStr | note: This is an unsafe fix and may change runtime behavior @@ -106,10 +96,8 @@ UP046 [*] Generic class `MultipleGenerics` uses `Generic` subclass instead of ty | help: Use type parameters | -40 | - - class MultipleGenerics(Generic[S, T, *Ts, P]): +41 - class MultipleGenerics(Generic[S, T, *Ts, P]): 41 + class MultipleGenerics[S: (str, bytes), T: float, *Ts, **P]: -42 | var: S | note: This is an unsafe fix and may change runtime behavior @@ -122,10 +110,8 @@ UP046 [*] Generic class `MultipleBaseClasses` uses `Generic` subclass instead of | help: Use type parameters | -47 | - - class MultipleBaseClasses(list, Generic[T]): +48 - class MultipleBaseClasses(list, Generic[T]): 48 + class MultipleBaseClasses[T: float](list): -49 | var: T | note: This is an unsafe fix and may change runtime behavior @@ -138,10 +124,8 @@ UP046 [*] Generic class `MoreBaseClasses` uses `Generic` subclass instead of typ | help: Use type parameters | -61 | - - class MoreBaseClasses(Base1, Base2, Base3, Generic[T]): +62 - class MoreBaseClasses(Base1, Base2, Base3, Generic[T]): 62 + class MoreBaseClasses[T: float](Base1, Base2, Base3): -63 | var: T | note: This is an unsafe fix and may change runtime behavior @@ -155,10 +139,8 @@ UP046 [*] Generic class `MultipleBaseAndGenerics` uses `Generic` subclass instea | help: Use type parameters | -65 | - - class MultipleBaseAndGenerics(Base1, Base2, Base3, Generic[S, T, *Ts, P]): +66 - class MultipleBaseAndGenerics(Base1, Base2, Base3, Generic[S, T, *Ts, P]): 66 + class MultipleBaseAndGenerics[S: (str, bytes), T: float, *Ts, **P](Base1, Base2, Base3): -67 | var: S | note: This is an unsafe fix and may change runtime behavior @@ -169,10 +151,8 @@ UP046 [*] Generic class `A` uses `Generic` subclass instead of type parameters | ^^^^^^^^^^ help: Use type parameters | -72 | - - class A(Generic[T]): ... +73 - class A(Generic[T]): ... 73 + class A[T: float]: ... -74 | | note: This is an unsafe fix and may change runtime behavior @@ -185,10 +165,8 @@ UP046 [*] Generic class `B` uses `Generic` subclass instead of type parameters | help: Use type parameters | -75 | - - class B(A[S], Generic[S]): +76 - class B(A[S], Generic[S]): 76 + class B[S: (str, bytes)](A[S]): -77 | var: S | note: This is an unsafe fix and may change runtime behavior @@ -201,10 +179,8 @@ UP046 [*] Generic class `C` uses `Generic` subclass instead of type parameters | help: Use type parameters | -79 | - - class C(A[S], Generic[S, T]): +80 - class C(A[S], Generic[S, T]): 80 + class C[S: (str, bytes), T: float](A[S]): -81 | var: tuple[S, T] | note: This is an unsafe fix and may change runtime behavior @@ -217,10 +193,8 @@ UP046 [*] Generic class `D` uses `Generic` subclass instead of type parameters | help: Use type parameters | -83 | - - class D(A[int], Generic[T]): +84 - class D(A[int], Generic[T]): 84 + class D[T: float](A[int]): -85 | var: T | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP046_0.py__preview_diff.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP046_0.py__preview_diff.snap index f699eb4944c7d..beeab4cd1a83d 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP046_0.py__preview_diff.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP046_0.py__preview_diff.snap @@ -19,10 +19,8 @@ UP046 [*] Generic class `DefaultTypeVar` uses `Generic` subclass instead of type | help: Use type parameters | -128 | - - class DefaultTypeVar(Generic[V]): # -> [V: str = Any] +129 - class DefaultTypeVar(Generic[V]): # -> [V: str = Any] 129 + class DefaultTypeVar[V: str = Any]: # -> [V: str = Any] -130 | var: V | note: This is an unsafe fix and may change runtime behavior @@ -36,9 +34,7 @@ UP046 [*] Generic class `DefaultOnlyTypeVar` uses `Generic` subclass instead of | help: Use type parameters | -136 | - - class DefaultOnlyTypeVar(Generic[W]): # -> [W = int] +137 - class DefaultOnlyTypeVar(Generic[W]): # -> [W = int] 137 + class DefaultOnlyTypeVar[W = int]: # -> [W = int] -138 | var: W | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP047_0.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP047_0.py.snap index ab0cd50aeee44..1f8df0a777fa2 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP047_0.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP047_0.py.snap @@ -10,11 +10,8 @@ UP047 [*] Generic function `f` should use type parameters | help: Use type parameters | -11 | - - def f(t: T) -> T: -12 + def f[T: float](t: T) -> T: -13 | return t - | +12 | def f[T: float](t: T) -> T: + | ++++++++++ note: This is an unsafe fix and may change runtime behavior UP047 [*] Generic function `g` should use type parameters @@ -26,11 +23,8 @@ UP047 [*] Generic function `g` should use type parameters | help: Use type parameters | -15 | - - def g(ts: tuple[*Ts]) -> tuple[*Ts]: -16 + def g[*Ts](ts: tuple[*Ts]) -> tuple[*Ts]: -17 | return ts - | +16 | def g[*Ts](ts: tuple[*Ts]) -> tuple[*Ts]: + | +++++ note: This is an unsafe fix and may change runtime behavior UP047 [*] Generic function `h` should use type parameters @@ -48,11 +42,8 @@ UP047 [*] Generic function `h` should use type parameters | help: Use type parameters | -19 | - - def h( -20 + def h[**P, T: float]( -21 | p: Callable[P, T], - | +20 | def h[**P, T: float]( + | +++++++++++++++ note: This is an unsafe fix and may change runtime behavior UP047 [*] Generic function `i` should use type parameters @@ -64,11 +55,8 @@ UP047 [*] Generic function `i` should use type parameters | help: Use type parameters | -28 | - - def i(s: S) -> S: -29 + def i[S: (str, bytes)](s: S) -> S: -30 | return s - | +29 | def i[S: (str, bytes)](s: S) -> S: + | +++++++++++++++++ note: This is an unsafe fix and may change runtime behavior UP047 [*] Generic function `broken_fix` should use type parameters @@ -82,11 +70,8 @@ UP047 [*] Generic function `broken_fix` should use type parameters | help: Use type parameters | -38 | # checkers - - def broken_fix(okay: T, bad: Something) -> tuple[T, Something]: -39 + def broken_fix[T: float](okay: T, bad: Something) -> tuple[T, Something]: -40 | return (okay, bad) - | +39 | def broken_fix[T: float](okay: T, bad: Something) -> tuple[T, Something]: + | ++++++++++ note: This is an unsafe fix and may change runtime behavior UP047 [*] Generic function `any_str_param` should use type parameters @@ -98,11 +83,8 @@ UP047 [*] Generic function `any_str_param` should use type parameters | help: Use type parameters | -42 | - - def any_str_param(s: AnyStr) -> AnyStr: -43 + def any_str_param[AnyStr: (bytes, str)](s: AnyStr) -> AnyStr: -44 | return s - | +43 | def any_str_param[AnyStr: (bytes, str)](s: AnyStr) -> AnyStr: + | ++++++++++++++++++++++ note: This is an unsafe fix and may change runtime behavior UP047 [*] Generic function `multi_param` should use type parameters @@ -116,9 +98,6 @@ UP047 [*] Generic function `multi_param` should use type parameters | help: Use type parameters | -55 | # TypeVar used in multiple parameter annotations should still be detected - - def multi_param(t: list[T], c: Callable[[T], None]) -> T: -56 + def multi_param[T: float](t: list[T], c: Callable[[T], None]) -> T: -57 | c(t[0]) - | +56 | def multi_param[T: float](t: list[T], c: Callable[[T], None]) -> T: + | ++++++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP047_0.py__preview_diff.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP047_0.py__preview_diff.snap index 21c957071ab40..de8f367bf8fac 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP047_0.py__preview_diff.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP047_0.py__preview_diff.snap @@ -19,9 +19,6 @@ UP047 [*] Generic function `default_var` should use type parameters | help: Use type parameters | -50 | - - def default_var(v: V) -> V: -51 + def default_var[V: str = Any](v: V) -> V: -52 | return v - | +51 | def default_var[V: str = Any](v: V) -> V: + | ++++++++++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP049_0.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP049_0.py.snap index ed2e72fea6aa6..e9cf19b31b9aa 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP049_0.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP049_0.py.snap @@ -11,15 +11,10 @@ UP049 [*] Generic class uses private type parameters | help: Rename type parameter to remove leading underscores | -1 | # simple case, replace _T in signature and body - - class Generic[_T]: - - buf: list[_T] -2 + class Generic[T]: -3 + buf: list[T] +2 ~ class Generic[T]: +3 ~ buf: list[T] 4 | - - def append(self, t: _T): -5 + def append(self, t: T): -6 | self.buf.append(t) +5 ~ def append(self, t: T): | UP049 [*] Generic function uses private type parameters @@ -33,12 +28,8 @@ UP049 [*] Generic function uses private type parameters | help: Rename type parameter to remove leading underscores | -9 | # simple case, replace _T in signature and body - - def second[_T](var: tuple[_T]) -> _T: - - y: _T = var[1] -10 + def second[T](var: tuple[T]) -> T: -11 + y: T = var[1] -12 | return y +10 ~ def second[T](var: tuple[T]) -> T: +11 ~ y: T = var[1] | UP049 [*] Generic function uses private type parameters @@ -53,10 +44,8 @@ UP049 [*] Generic function uses private type parameters | help: Rename type parameter to remove leading underscores | -16 | def many_generics[ - - _T, # first generic +17 - _T, # first generic 17 + T, # first generic -18 | _U, # second generic | UP049 [*] Generic function uses private type parameters @@ -71,10 +60,8 @@ UP049 [*] Generic function uses private type parameters | help: Rename type parameter to remove leading underscores | -17 | _T, # first generic - - _U, # second generic +18 - _U, # second generic 18 + U, # second generic -19 | ](args): | UP049 [*] Generic function uses private type parameters @@ -87,12 +74,8 @@ UP049 [*] Generic function uses private type parameters | help: Rename type parameter to remove leading underscores | -26 | - - def f[_T](v): - - cast("_T", v) -27 + def f[T](v): -28 + cast("T", v) +27 ~ def f[T](v): +28 ~ cast("T", v) 29 | cast("Literal['_T']") - - cast("list[_T]", v) -30 + cast("list[T]", v) +30 ~ cast("list[T]", v) | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP049_1.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP049_1.py.snap index 36991658e00d1..91460110f0588 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP049_1.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP049_1.py.snap @@ -11,12 +11,8 @@ UP049 [*] Generic class uses private type parameters | help: Rename type parameter to remove leading underscores | -1 | # bound - - class Foo[_T: str]: - - var: _T -2 + class Foo[T: str]: -3 + var: T -4 | +2 ~ class Foo[T: str]: +3 ~ var: T | UP049 [*] Generic class uses private type parameters @@ -29,12 +25,8 @@ UP049 [*] Generic class uses private type parameters | help: Rename type parameter to remove leading underscores | -6 | # constraint - - class Foo[_T: (str, bytes)]: - - var: _T -7 + class Foo[T: (str, bytes)]: -8 + var: T -9 | +7 ~ class Foo[T: (str, bytes)]: +8 ~ var: T | UP049 [*] Generic class uses private type parameters @@ -47,12 +39,8 @@ UP049 [*] Generic class uses private type parameters | help: Rename type parameter to remove leading underscores | -11 | # python 3.13+ default - - class Foo[_T = int]: - - var: _T -12 + class Foo[T = int]: -13 + var: T -14 | +12 ~ class Foo[T = int]: +13 ~ var: T | UP049 [*] Generic class uses private type parameters @@ -65,12 +53,8 @@ UP049 [*] Generic class uses private type parameters | help: Rename type parameter to remove leading underscores | -16 | # tuple - - class Foo[*_Ts]: - - var: tuple[*_Ts] -17 + class Foo[*Ts]: -18 + var: tuple[*Ts] -19 | +17 ~ class Foo[*Ts]: +18 ~ var: tuple[*Ts] | UP049 [*] Generic class uses private type parameters @@ -83,12 +67,8 @@ UP049 [*] Generic class uses private type parameters | help: Rename type parameter to remove leading underscores | -21 | # paramspec - - class C[**_P]: - - var: _P -22 + class C[**P]: -23 + var: P -24 | +22 ~ class C[**P]: +23 ~ var: P | UP049 [*] Generic class uses private type parameters @@ -103,13 +83,9 @@ UP049 [*] Generic class uses private type parameters | help: Rename type parameter to remove leading underscores | -30 | # fixed - - class Everything[_T, _U: str, _V: (int, float), *_W, **_X]: -31 + class Everything[T, _U: str, _V: (int, float), *_W, **_X]: +31 ~ class Everything[T, _U: str, _V: (int, float), *_W, **_X]: 32 | @staticmethod - - def transform(t: _T, u: _U, v: _V) -> tuple[*_W] | Callable[_X, _T] | None: -33 + def transform(t: T, u: _U, v: _V) -> tuple[*_W] | Callable[_X, T] | None: -34 | return None +33 ~ def transform(t: T, u: _U, v: _V) -> tuple[*_W] | Callable[_X, T] | None: | UP049 [*] Generic class uses private type parameters @@ -124,13 +100,9 @@ UP049 [*] Generic class uses private type parameters | help: Rename type parameter to remove leading underscores | -30 | # fixed - - class Everything[_T, _U: str, _V: (int, float), *_W, **_X]: -31 + class Everything[_T, U: str, _V: (int, float), *_W, **_X]: +31 ~ class Everything[_T, U: str, _V: (int, float), *_W, **_X]: 32 | @staticmethod - - def transform(t: _T, u: _U, v: _V) -> tuple[*_W] | Callable[_X, _T] | None: -33 + def transform(t: _T, u: U, v: _V) -> tuple[*_W] | Callable[_X, _T] | None: -34 | return None +33 ~ def transform(t: _T, u: U, v: _V) -> tuple[*_W] | Callable[_X, _T] | None: | UP049 [*] Generic class uses private type parameters @@ -145,13 +117,9 @@ UP049 [*] Generic class uses private type parameters | help: Rename type parameter to remove leading underscores | -30 | # fixed - - class Everything[_T, _U: str, _V: (int, float), *_W, **_X]: -31 + class Everything[_T, _U: str, V: (int, float), *_W, **_X]: +31 ~ class Everything[_T, _U: str, V: (int, float), *_W, **_X]: 32 | @staticmethod - - def transform(t: _T, u: _U, v: _V) -> tuple[*_W] | Callable[_X, _T] | None: -33 + def transform(t: _T, u: _U, v: V) -> tuple[*_W] | Callable[_X, _T] | None: -34 | return None +33 ~ def transform(t: _T, u: _U, v: V) -> tuple[*_W] | Callable[_X, _T] | None: | UP049 [*] Generic class uses private type parameters @@ -166,13 +134,9 @@ UP049 [*] Generic class uses private type parameters | help: Rename type parameter to remove leading underscores | -30 | # fixed - - class Everything[_T, _U: str, _V: (int, float), *_W, **_X]: -31 + class Everything[_T, _U: str, _V: (int, float), *W, **_X]: +31 ~ class Everything[_T, _U: str, _V: (int, float), *W, **_X]: 32 | @staticmethod - - def transform(t: _T, u: _U, v: _V) -> tuple[*_W] | Callable[_X, _T] | None: -33 + def transform(t: _T, u: _U, v: _V) -> tuple[*W] | Callable[_X, _T] | None: -34 | return None +33 ~ def transform(t: _T, u: _U, v: _V) -> tuple[*W] | Callable[_X, _T] | None: | UP049 [*] Generic class uses private type parameters @@ -187,13 +151,9 @@ UP049 [*] Generic class uses private type parameters | help: Rename type parameter to remove leading underscores | -30 | # fixed - - class Everything[_T, _U: str, _V: (int, float), *_W, **_X]: -31 + class Everything[_T, _U: str, _V: (int, float), *_W, **X]: +31 ~ class Everything[_T, _U: str, _V: (int, float), *_W, **X]: 32 | @staticmethod - - def transform(t: _T, u: _U, v: _V) -> tuple[*_W] | Callable[_X, _T] | None: -33 + def transform(t: _T, u: _U, v: _V) -> tuple[*_W] | Callable[X, _T] | None: -34 | return None +33 ~ def transform(t: _T, u: _U, v: _V) -> tuple[*_W] | Callable[X, _T] | None: | UP049 Generic class uses private type parameters @@ -251,24 +211,15 @@ UP049 [*] Generic class uses private type parameters | help: Rename type parameter to remove leading underscores | -70 | - - class C[_T]: - - v1 = cast(_T, ...) - - v2 = cast('_T', ...) - - v3 = cast("\u005fT", ...) -71 + class C[T]: -72 + v1 = cast(T, ...) -73 + v2 = cast('T', ...) -74 + v3 = cast(T, ...) +71 ~ class C[T]: +72 ~ v1 = cast(T, ...) +73 ~ v2 = cast('T', ...) +74 ~ v3 = cast(T, ...) 75 | 76 | def _(self): - - v1 = cast(_T, ...) - - v2 = cast('_T', ...) - - v3 = cast("\u005fT", ...) -77 + v1 = cast(T, ...) -78 + v2 = cast('T', ...) -79 + v3 = cast(T, ...) -80 | +77 ~ v1 = cast(T, ...) +78 ~ v2 = cast('T', ...) +79 ~ v3 = cast(T, ...) | note: This is a display-only fix and is likely to be incorrect @@ -281,12 +232,8 @@ UP049 [*] Generic class uses private type parameters | help: Rename type parameter to remove leading underscores | -81 | - - class C[_T]: - - v = cast('Literal[\'foo\'] | _T', ...) -82 + class C[T]: -83 + v = cast(T, ...) -84 | +82 ~ class C[T]: +83 ~ v = cast(T, ...) | note: This is a display-only fix and is likely to be incorrect diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP050.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP050.py.snap index cb05e9f564310..6321993c56694 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP050.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP050.py.snap @@ -10,10 +10,8 @@ UP050 [*] Class `A` uses `metaclass=type`, which is redundant | help: Remove `metaclass=type` | -4 | - - class A(metaclass=type): +5 - class A(metaclass=type): 5 + class A: -6 | ... | UP050 [*] Class `A` uses `metaclass=type`, which is redundant @@ -27,12 +25,10 @@ UP050 [*] Class `A` uses `metaclass=type`, which is redundant | help: Remove `metaclass=type` | -8 | - - class A( - - metaclass=type - - ): -9 + class A: -10 | ... + 9 - class A( +10 - metaclass=type +11 - ): + 9 + class A: | UP050 [*] Class `A` uses `metaclass=type`, which is redundant @@ -46,13 +42,11 @@ UP050 [*] Class `A` uses `metaclass=type`, which is redundant | help: Remove `metaclass=type` | -14 | - - class A( - - metaclass=type - - # - - ): +15 - class A( +16 - metaclass=type +17 - # +18 - ): 15 + class A: -16 | ... | note: This is an unsafe fix and may change runtime behavior @@ -68,13 +62,11 @@ UP050 [*] Class `A` uses `metaclass=type`, which is redundant | help: Remove `metaclass=type` | -21 | - - class A( - - # - - metaclass=type - - ): +22 - class A( +23 - # +24 - metaclass=type +25 - ): 22 + class A: -23 | ... | note: This is an unsafe fix and may change runtime behavior @@ -89,13 +81,11 @@ UP050 [*] Class `A` uses `metaclass=type`, which is redundant | help: Remove `metaclass=type` | -28 | - - class A( - - metaclass=type, - - # - - ): +29 - class A( +30 - metaclass=type, +31 - # +32 - ): 29 + class A: -30 | ... | note: This is an unsafe fix and may change runtime behavior @@ -111,14 +101,12 @@ UP050 [*] Class `A` uses `metaclass=type`, which is redundant | help: Remove `metaclass=type` | -35 | - - class A( - - # - - metaclass=type, - - # - - ): +36 - class A( +37 - # +38 - metaclass=type, +39 - # +40 - ): 36 + class A: -37 | ... | note: This is an unsafe fix and may change runtime behavior @@ -131,10 +119,8 @@ UP050 [*] Class `B` uses `metaclass=type`, which is redundant | help: Remove `metaclass=type` | -43 | - - class B(A, metaclass=type): +44 - class B(A, metaclass=type): 44 + class B(A): -45 | ... | UP050 [*] Class `B` uses `metaclass=type`, which is redundant @@ -149,9 +135,9 @@ UP050 [*] Class `B` uses `metaclass=type`, which is redundant | help: Remove `metaclass=type` | -49 | A, - - metaclass=type, -50 | ): +49 - A, +50 - metaclass=type, +49 + A, | UP050 [*] Class `B` uses `metaclass=type`, which is redundant @@ -166,10 +152,10 @@ UP050 [*] Class `B` uses `metaclass=type`, which is redundant | help: Remove `metaclass=type` | -56 | A, - - # comment - - metaclass=type, -57 | ): +56 - A, +57 - # comment +58 - metaclass=type, +56 + A, | note: This is an unsafe fix and may change runtime behavior @@ -184,13 +170,11 @@ UP050 [*] Class `A` uses `metaclass=type`, which is redundant | help: Remove `metaclass=type` | -67 | - - class A( - - metaclass=type # comment - - , - - ): +68 - class A( +69 - metaclass=type # comment +70 - , +71 - ): 68 + class A: -69 | ... | note: This is an unsafe fix and may change runtime behavior @@ -205,8 +189,6 @@ UP050 [*] Class `A` uses `metaclass=type`, which is redundant | help: Remove `metaclass=type` | -82 | - - class A(metaclass=builtins.type): +83 - class A(metaclass=builtins.type): 83 + class A: -84 | ... | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__add_future_annotation_UP037_0.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__add_future_annotation_UP037_0.py.snap index a9c1dba916fab..89274e19a8207 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__add_future_annotation_UP037_0.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__add_future_annotation_UP037_0.py.snap @@ -10,10 +10,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -17 | - - def foo(var: "MyClass") -> "MyClass": +18 - def foo(var: "MyClass") -> "MyClass": 18 + def foo(var: MyClass) -> "MyClass": -19 | x: "MyClass" | UP037 [*] Remove quotes from type annotation @@ -25,10 +23,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -17 | - - def foo(var: "MyClass") -> "MyClass": +18 - def foo(var: "MyClass") -> "MyClass": 18 + def foo(var: "MyClass") -> MyClass: -19 | x: "MyClass" | UP037 [*] Remove quotes from type annotation @@ -39,10 +35,8 @@ UP037 [*] Remove quotes from type annotation | ^^^^^^^^^ help: Remove quotes | -18 | def foo(var: "MyClass") -> "MyClass": - - x: "MyClass" +19 - x: "MyClass" 19 + x: MyClass -20 | | UP037 [*] Remove quotes from type annotation @@ -54,10 +48,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -21 | - - def foo(*, inplace: "bool"): +22 - def foo(*, inplace: "bool"): 22 + def foo(*, inplace: bool): -23 | pass | UP037 [*] Remove quotes from type annotation @@ -69,10 +61,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -25 | - - def foo(*args: "str", **kwargs: "int"): +26 - def foo(*args: "str", **kwargs: "int"): 26 + def foo(*args: str, **kwargs: "int"): -27 | pass | UP037 [*] Remove quotes from type annotation @@ -84,10 +74,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -25 | - - def foo(*args: "str", **kwargs: "int"): +26 - def foo(*args: "str", **kwargs: "int"): 26 + def foo(*args: "str", **kwargs: int): -27 | pass | UP037 [*] Remove quotes from type annotation @@ -100,10 +88,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -29 | - - x: Tuple["MyClass"] +30 - x: Tuple["MyClass"] 30 + x: Tuple[MyClass] -31 | | UP037 [*] Remove quotes from type annotation @@ -115,10 +101,8 @@ UP037 [*] Remove quotes from type annotation | ^^^^^^^^^ help: Remove quotes | -31 | - - x: Callable[["MyClass"], None] +32 - x: Callable[["MyClass"], None] 32 + x: Callable[[MyClass], None] -33 | | UP037 [*] Remove quotes from type annotation @@ -129,10 +113,8 @@ UP037 [*] Remove quotes from type annotation | ^^^^^^^^^ help: Remove quotes | -35 | class Foo(NamedTuple): - - x: "MyClass" +36 - x: "MyClass" 36 + x: MyClass -37 | | UP037 [*] Remove quotes from type annotation @@ -143,10 +125,8 @@ UP037 [*] Remove quotes from type annotation | ^^^^^ help: Remove quotes | -39 | class D(TypedDict): - - E: TypedDict("E", foo="int", total=False) +40 - E: TypedDict("E", foo="int", total=False) 40 + E: TypedDict("E", foo=int, total=False) -41 | | UP037 [*] Remove quotes from type annotation @@ -157,10 +137,8 @@ UP037 [*] Remove quotes from type annotation | ^^^^^ help: Remove quotes | -43 | class D(TypedDict): - - E: TypedDict("E", {"foo": "int"}) +44 - E: TypedDict("E", {"foo": "int"}) 44 + E: TypedDict("E", {"foo": int}) -45 | | UP037 [*] Remove quotes from type annotation @@ -173,10 +151,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -46 | - - x: Annotated["str", "metadata"] +47 - x: Annotated["str", "metadata"] 47 + x: Annotated[str, "metadata"] -48 | | UP037 [*] Remove quotes from type annotation @@ -191,10 +167,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -48 | - - x: Arg("str", "name") +49 - x: Arg("str", "name") 49 + x: Arg(str, "name") -50 | | UP037 [*] Remove quotes from type annotation @@ -209,10 +183,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -50 | - - x: DefaultArg("str", "name") +51 - x: DefaultArg("str", "name") 51 + x: DefaultArg(str, "name") -52 | | UP037 [*] Remove quotes from type annotation @@ -227,10 +199,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -52 | - - x: NamedArg("str", "name") +53 - x: NamedArg("str", "name") 53 + x: NamedArg(str, "name") -54 | | UP037 [*] Remove quotes from type annotation @@ -245,10 +215,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -54 | - - x: DefaultNamedArg("str", "name") +55 - x: DefaultNamedArg("str", "name") 55 + x: DefaultNamedArg(str, "name") -56 | | UP037 [*] Remove quotes from type annotation @@ -263,10 +231,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -56 | - - x: DefaultNamedArg("str", name="name") +57 - x: DefaultNamedArg("str", name="name") 57 + x: DefaultNamedArg(str, name="name") -58 | | UP037 [*] Remove quotes from type annotation @@ -281,10 +247,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -58 | - - x: VarArg("str") +59 - x: VarArg("str") 59 + x: VarArg(str) -60 | | UP037 [*] Remove quotes from type annotation @@ -299,10 +263,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -60 | - - x: List[List[List["MyClass"]]] +61 - x: List[List[List["MyClass"]]] 61 + x: List[List[List[MyClass]]] -62 | | UP037 [*] Remove quotes from type annotation @@ -317,10 +279,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -62 | - - x: NamedTuple("X", [("foo", "int"), ("bar", "str")]) +63 - x: NamedTuple("X", [("foo", "int"), ("bar", "str")]) 63 + x: NamedTuple("X", [("foo", int), ("bar", "str")]) -64 | | UP037 [*] Remove quotes from type annotation @@ -335,10 +295,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -62 | - - x: NamedTuple("X", [("foo", "int"), ("bar", "str")]) +63 - x: NamedTuple("X", [("foo", "int"), ("bar", "str")]) 63 + x: NamedTuple("X", [("foo", "int"), ("bar", str)]) -64 | | UP037 [*] Remove quotes from type annotation @@ -353,10 +311,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -64 | - - x: NamedTuple("X", fields=[("foo", "int"), ("bar", "str")]) +65 - x: NamedTuple("X", fields=[("foo", "int"), ("bar", "str")]) 65 + x: NamedTuple("X", fields=[(foo, "int"), ("bar", "str")]) -66 | | UP037 [*] Remove quotes from type annotation @@ -371,10 +327,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -64 | - - x: NamedTuple("X", fields=[("foo", "int"), ("bar", "str")]) +65 - x: NamedTuple("X", fields=[("foo", "int"), ("bar", "str")]) 65 + x: NamedTuple("X", fields=[("foo", int), ("bar", "str")]) -66 | | UP037 [*] Remove quotes from type annotation @@ -389,10 +343,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -64 | - - x: NamedTuple("X", fields=[("foo", "int"), ("bar", "str")]) +65 - x: NamedTuple("X", fields=[("foo", "int"), ("bar", "str")]) 65 + x: NamedTuple("X", fields=[("foo", "int"), (bar, "str")]) -66 | | UP037 [*] Remove quotes from type annotation @@ -407,10 +359,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -64 | - - x: NamedTuple("X", fields=[("foo", "int"), ("bar", "str")]) +65 - x: NamedTuple("X", fields=[("foo", "int"), ("bar", "str")]) 65 + x: NamedTuple("X", fields=[("foo", "int"), ("bar", str)]) -66 | | UP037 [*] Remove quotes from type annotation @@ -425,10 +375,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -66 | - - x: NamedTuple(typename="X", fields=[("foo", "int")]) +67 - x: NamedTuple(typename="X", fields=[("foo", "int")]) 67 + x: NamedTuple(typename=X, fields=[("foo", "int")]) -68 | | UP037 [*] Remove quotes from type annotation @@ -443,10 +391,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -66 | - - x: NamedTuple(typename="X", fields=[("foo", "int")]) +67 - x: NamedTuple(typename="X", fields=[("foo", "int")]) 67 + x: NamedTuple(typename="X", fields=[(foo, "int")]) -68 | | UP037 [*] Remove quotes from type annotation @@ -461,10 +407,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -66 | - - x: NamedTuple(typename="X", fields=[("foo", "int")]) +67 - x: NamedTuple(typename="X", fields=[("foo", "int")]) 67 + x: NamedTuple(typename="X", fields=[("foo", int)]) -68 | | UP037 [*] Remove quotes from type annotation @@ -478,11 +422,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -111 | # See https://github.com/astral-sh/ruff/issues/15816 - - def f() -> "Literal[0]#": -112 + def f() -> (Literal[0]# -113 + ): -114 | return 0 +112 ~ def f() -> (Literal[0]# +113 ~ ): | UP037 [*] Remove quotes from type annotation @@ -496,11 +437,8 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -114 | - - def g(x: "Literal['abc']#") -> None: -115 + def g(x: (Literal['abc']# -116 + )) -> None: -117 | return +115 ~ def g(x: (Literal['abc']# +116 ~ )) -> None: | UP037 [*] Remove quotes from type annotation @@ -518,15 +456,11 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -117 | - - def f() -> """Literal[0] -118 + def f() -> (Literal[0] -119 | # -120 | - - """: +118 ~ def f() -> (Literal[0] +119 + # +120 + 121 + -122 + ): -123 | return 0 +122 ~ ): | UP037 [*] Remove quotes from type annotation @@ -539,12 +473,9 @@ UP037 [*] Remove quotes from type annotation | help: Remove quotes | -124 | # https://github.com/astral-sh/ruff/issues/19835 - - def foo(bar: "A\n#"): ... -125 + def foo(bar: (A +125 ~ def foo(bar: (A 126 + # -127 + )): ... -128 | def foo(bar: "A\n#\n"): ... +127 ~ )): ... | UP037 [*] Remove quotes from type annotation @@ -556,10 +487,8 @@ UP037 [*] Remove quotes from type annotation | ^^^^^^^^ help: Remove quotes | -125 | def foo(bar: "A\n#"): ... - - def foo(bar: "A\n#\n"): ... -126 + def foo(bar: (A +126 ~ def foo(bar: (A 127 + # -128 + -129 + )): ... +128 + +129 ~ )): ... | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__add_future_annotation_UP037_1.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__add_future_annotation_UP037_1.py.snap index 09e59a880d1ef..c286b0b9c1068 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__add_future_annotation_UP037_1.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__add_future_annotation_UP037_1.py.snap @@ -11,12 +11,10 @@ UP037 [*] Remove quotes from type annotation 10 | print(x) | help: Remove quotes - | -8 | # UP037 - - x: "Tuple[int, int]" = (0, 0) -9 + x: Tuple[int, int] = (0, 0) -10 | print(x) - | + | +9 - x: "Tuple[int, int]" = (0, 0) +9 + x: Tuple[int, int] = (0, 0) + | UP037 [*] Remove quotes from type annotation --> UP037_1.py:14:4 @@ -26,7 +24,6 @@ UP037 [*] Remove quotes from type annotation | ^^^^^^^^^^^^^^^^^ help: Remove quotes | -13 | # OK - - X: "Tuple[int, int]" = (0, 0) +14 - X: "Tuple[int, int]" = (0, 0) 14 + X: Tuple[int, int] = (0, 0) | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__add_future_annotation_UP037_2.pyi.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__add_future_annotation_UP037_2.pyi.snap index 5ef03783a7fa3..93c9e61fc31a0 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__add_future_annotation_UP037_2.pyi.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__add_future_annotation_UP037_2.pyi.snap @@ -10,11 +10,8 @@ UP037 [*] Remove quotes from type annotation | ^^^^^^^^^^^^^^^^^^^^^^^ help: Remove quotes | -2 | - - def f(a: Foo['SingleLine # Comment']): ... -3 + def f(a: Foo[(SingleLine # Comment -4 + )]): ... -5 | +3 ~ def f(a: Foo[(SingleLine # Comment +4 ~ )]): ... | UP037 [*] Remove quotes from type annotation @@ -27,13 +24,9 @@ UP037 [*] Remove quotes from type annotation | |____________^ help: Remove quotes | -5 | - - def f(a: Foo['''Bar[ -6 + def f(a: Foo[Bar[ -7 | Multi | - - Line]''']): ... -8 + Line]]): ... -9 | +6 ~ def f(a: Foo[Bar[ +7 + Multi | +8 ~ Line]]): ... | UP037 [*] Remove quotes from type annotation @@ -47,14 +40,10 @@ UP037 [*] Remove quotes from type annotation | |____^ help: Remove quotes | -10 | - - def f(a: Foo['''Bar[ -11 + def f(a: Foo[Bar[ -12 | Multi | -13 | Line # Comment - - ]''']): ... -14 + ]]): ... -15 | +11 ~ def f(a: Foo[Bar[ +12 + Multi | +13 + Line # Comment +14 ~ ]]): ... | UP037 [*] Remove quotes from type annotation @@ -67,14 +56,10 @@ UP037 [*] Remove quotes from type annotation | |_______________________^ help: Remove quotes | -16 | - - def f(a: Foo['''Bar[ -17 + def f(a: Foo[(Bar[ -18 | Multi | - - Line] # Comment''']): ... +17 ~ def f(a: Foo[(Bar[ +18 + Multi | 19 + Line] # Comment -20 + )]): ... -21 | +20 ~ )]): ... | UP037 [*] Remove quotes from type annotation @@ -88,15 +73,11 @@ UP037 [*] Remove quotes from type annotation | |_______________________^ help: Remove quotes | -21 | - - def f(a: Foo[''' -22 + def f(a: Foo[( -23 | Bar[ -24 | Multi | - - Line] # Comment''']): ... +22 ~ def f(a: Foo[( +23 + Bar[ +24 + Multi | 25 + Line] # Comment -26 + )]): ... -27 | +26 ~ )]): ... | UP037 [*] Remove quotes from type annotation @@ -108,12 +89,8 @@ UP037 [*] Remove quotes from type annotation | |_______^ help: Remove quotes | -27 | - - def f(a: '''list[int] - - ''' = []): ... -28 + def f(a: list[int] -29 + = []): ... -30 | +28 ~ def f(a: list[int] +29 ~ = []): ... | UP037 [*] Remove quotes from type annotation @@ -125,12 +102,8 @@ UP037 [*] Remove quotes from type annotation | |____________^ help: Remove quotes | -31 | - - a: '''\\ - - list[int]''' = [42] -32 + a: (\ -33 + list[int]) = [42] -34 | +32 ~ a: (\ +33 ~ list[int]) = [42] | UP037 [*] Remove quotes from type annotation @@ -143,13 +116,9 @@ UP037 [*] Remove quotes from type annotation | |_______^ help: Remove quotes | -35 | - - def f(a: ''' -36 + def f(a: -37 | list[int] - - ''' = []): ... -38 + = []): ... -39 | +36 ~ def f(a: +37 ~ list[int] +38 ~ = []): ... | UP037 [*] Remove quotes from type annotation @@ -165,17 +134,13 @@ UP037 [*] Remove quotes from type annotation | |___________________^ help: Remove quotes | -40 | - - def f(a: Foo[''' -41 + def f(a: Foo[( -42 | Bar -43 | [ -44 | Multi | -45 | Line - - ] # Comment''']): ... +41 ~ def f(a: Foo[( +42 + Bar +43 + [ +44 + Multi | +45 + Line 46 + ] # Comment -47 + )]): ... -48 | +47 ~ )]): ... | UP037 [*] Remove quotes from type annotation @@ -187,9 +152,6 @@ UP037 [*] Remove quotes from type annotation | |________^ help: Remove quotes | -48 | - - a: '''list - - [int]''' = [42] -49 + a: (list -50 + [int]) = [42] +49 ~ a: (list +50 ~ [int]) = [42] | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__async_timeout_error_alias_not_applied_py310.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__async_timeout_error_alias_not_applied_py310.snap index f92fb10e5b407..702e018bcaf5f 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__async_timeout_error_alias_not_applied_py310.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__async_timeout_error_alias_not_applied_py310.snap @@ -12,10 +12,8 @@ UP041 [*] Replace aliased errors with `TimeoutError` | help: Replace `socket.timeout` with builtin `TimeoutError` | -9 | pass - - except socket.timeout: +10 - except socket.timeout: 10 + except TimeoutError: -11 | pass | UP041 [*] Replace aliased errors with `TimeoutError` @@ -29,10 +27,8 @@ UP041 [*] Replace aliased errors with `TimeoutError` | help: Replace with builtin `TimeoutError` | -21 | pass - - except (socket.timeout,): +22 - except (socket.timeout,): 22 + except TimeoutError: -23 | pass | UP041 [*] Replace aliased errors with `TimeoutError` @@ -46,10 +42,8 @@ UP041 [*] Replace aliased errors with `TimeoutError` | help: Replace with builtin `TimeoutError` | -26 | pass - - except (asyncio.TimeoutError, socket.timeout,): +27 - except (asyncio.TimeoutError, socket.timeout,): 27 + except (TimeoutError, asyncio.TimeoutError): -28 | pass | UP041 [*] Replace aliased errors with `TimeoutError` @@ -63,8 +57,6 @@ UP041 [*] Replace aliased errors with `TimeoutError` | help: Replace with builtin `TimeoutError` | -33 | pass - - except (asyncio.TimeoutError, socket.timeout, KeyError, TimeoutError): +34 - except (asyncio.TimeoutError, socket.timeout, KeyError, TimeoutError): 34 + except (asyncio.TimeoutError, KeyError, TimeoutError): -35 | pass | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__datetime_utc_alias_py311.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__datetime_utc_alias_py311.snap index 1759a22bd9594..b22ede77e9e5b 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__datetime_utc_alias_py311.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__datetime_utc_alias_py311.snap @@ -10,13 +10,12 @@ UP017 [*] Use `datetime.UTC` alias | ^^^^^^^^^^^^ help: Convert to `datetime.UTC` alias | -1 + from datetime import UTC -2 | def func(): --------------------------------------------------------------------------------- + 1 + from datetime import UTC + 2 | def func(): + 3 | import datetime + … 10 | - - print(timezone.utc) -11 + print(UTC) -12 | +11 ~ print(UTC) | UP017 [*] Use `datetime.UTC` alias @@ -28,13 +27,12 @@ UP017 [*] Use `datetime.UTC` alias | ^^^^^^ help: Convert to `datetime.UTC` alias | -1 + from datetime import UTC -2 | def func(): --------------------------------------------------------------------------------- + 1 + from datetime import UTC + 2 | def func(): + 3 | import datetime + … 16 | - - print(tz.utc) -17 + print(UTC) -18 | +17 ~ print(UTC) | UP017 [*] Use `datetime.UTC` alias @@ -46,10 +44,9 @@ UP017 [*] Use `datetime.UTC` alias | ^^^^^^^^^^^^^^^^^^^^^ help: Convert to `datetime.UTC` alias | +20 ~ import datetime 21 | - - print(datetime.timezone.utc) -22 + print(datetime.UTC) -23 | +22 ~ print(datetime.UTC) | UP017 [*] Use `datetime.UTC` alias @@ -61,10 +58,9 @@ UP017 [*] Use `datetime.UTC` alias | ^^^^^^^^^^^^^^^ help: Convert to `datetime.UTC` alias | +26 ~ import datetime as dt 27 | - - print(dt.timezone.utc) -28 + print(dt.UTC) -29 | +28 ~ print(dt.UTC) | UP017 [*] Use `datetime.UTC` alias @@ -79,11 +75,9 @@ UP017 [*] Use `datetime.UTC` alias | help: Convert to `datetime.UTC` alias | +32 ~ import datetime +33 | 34 | print(( - - datetime - - .timezone # text - - .utc -35 + datetime.UTC -36 | )) +35 ~ datetime.UTC | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__future_annotations_keep_runtime_typing_p310.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__future_annotations_keep_runtime_typing_p310.snap index 408d6ee9cb4df..0c2bb1d0cf19a 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__future_annotations_keep_runtime_typing_p310.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__future_annotations_keep_runtime_typing_p310.snap @@ -11,10 +11,8 @@ UP006 [*] Use `list` instead of `List` for type annotation | help: Replace with `list` | -33 | - - def f(x: int) -> List[int]: +34 - def f(x: int) -> List[int]: 34 + def f(x: int) -> list[int]: -35 | y = List[int]() | UP006 [*] Use `list` instead of `List` for type annotation @@ -28,10 +26,8 @@ UP006 [*] Use `list` instead of `List` for type annotation | help: Replace with `list` | -34 | def f(x: int) -> List[int]: - - y = List[int]() +35 - y = List[int]() 35 + y = list[int]() -36 | y.append(x) | UP006 [*] Use `list` instead of `List` for type annotation @@ -43,8 +39,7 @@ UP006 [*] Use `list` instead of `List` for type annotation | ^^^^ help: Replace with `list` | -41 | - - MyList: TypeAlias = Union[List[int], List[str]] +42 - MyList: TypeAlias = Union[List[int], List[str]] 42 + MyList: TypeAlias = Union[list[int], List[str]] | @@ -57,7 +52,6 @@ UP006 [*] Use `list` instead of `List` for type annotation | ^^^^ help: Replace with `list` | -41 | - - MyList: TypeAlias = Union[List[int], List[str]] +42 - MyList: TypeAlias = Union[List[int], List[str]] 42 + MyList: TypeAlias = Union[List[int], list[str]] | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__future_annotations_pep_585_p37.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__future_annotations_pep_585_p37.snap index 43694179d59ee..90f692c7ac2a3 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__future_annotations_pep_585_p37.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__future_annotations_pep_585_p37.snap @@ -11,9 +11,7 @@ UP006 [*] Use `list` instead of `List` for type annotation | help: Replace with `list` | -33 | - - def f(x: int) -> List[int]: +34 - def f(x: int) -> List[int]: 34 + def f(x: int) -> list[int]: -35 | y = List[int]() | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__future_annotations_pep_585_py310.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__future_annotations_pep_585_py310.snap index 408d6ee9cb4df..0c2bb1d0cf19a 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__future_annotations_pep_585_py310.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__future_annotations_pep_585_py310.snap @@ -11,10 +11,8 @@ UP006 [*] Use `list` instead of `List` for type annotation | help: Replace with `list` | -33 | - - def f(x: int) -> List[int]: +34 - def f(x: int) -> List[int]: 34 + def f(x: int) -> list[int]: -35 | y = List[int]() | UP006 [*] Use `list` instead of `List` for type annotation @@ -28,10 +26,8 @@ UP006 [*] Use `list` instead of `List` for type annotation | help: Replace with `list` | -34 | def f(x: int) -> List[int]: - - y = List[int]() +35 - y = List[int]() 35 + y = list[int]() -36 | y.append(x) | UP006 [*] Use `list` instead of `List` for type annotation @@ -43,8 +39,7 @@ UP006 [*] Use `list` instead of `List` for type annotation | ^^^^ help: Replace with `list` | -41 | - - MyList: TypeAlias = Union[List[int], List[str]] +42 - MyList: TypeAlias = Union[List[int], List[str]] 42 + MyList: TypeAlias = Union[list[int], List[str]] | @@ -57,7 +52,6 @@ UP006 [*] Use `list` instead of `List` for type annotation | ^^^^ help: Replace with `list` | -41 | - - MyList: TypeAlias = Union[List[int], List[str]] +42 - MyList: TypeAlias = Union[List[int], List[str]] 42 + MyList: TypeAlias = Union[List[int], list[str]] | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__future_annotations_pep_604_p37.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__future_annotations_pep_604_p37.snap index e429ccb53758e..033479a270a40 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__future_annotations_pep_604_p37.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__future_annotations_pep_604_p37.snap @@ -11,9 +11,7 @@ UP045 [*] Use `X | None` for type annotations | help: Convert to `X | None` | -39 | - - x: Optional[int] = None +40 - x: Optional[int] = None 40 + x: int | None = None -41 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__future_annotations_pep_604_py310.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__future_annotations_pep_604_py310.snap index f1291f2cf3ec7..7f024dd0fcefc 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__future_annotations_pep_604_py310.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__future_annotations_pep_604_py310.snap @@ -11,10 +11,8 @@ UP045 [*] Use `X | None` for type annotations | help: Convert to `X | None` | -39 | - - x: Optional[int] = None +40 - x: Optional[int] = None 40 + x: int | None = None -41 | | UP007 [*] Use `X | Y` for type annotations @@ -26,7 +24,6 @@ UP007 [*] Use `X | Y` for type annotations | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Convert to `X | Y` | -41 | - - MyList: TypeAlias = Union[List[int], List[str]] +42 - MyList: TypeAlias = Union[List[int], List[str]] 42 + MyList: TypeAlias = List[int] | List[str] | diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_UP006_4.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_UP006_4.py.snap index 2e113af09e911..0731b90df19bc 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_UP006_4.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_UP006_4.py.snap @@ -20,7 +20,6 @@ FA100 [*] Add `from __future__ import annotations` to simplify `typing.List` help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import typing | note: This is an unsafe fix and may change runtime behavior @@ -35,7 +34,6 @@ FA100 [*] Add `from __future__ import annotations` to simplify `typing.List` help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import typing | note: This is an unsafe fix and may change runtime behavior @@ -56,9 +54,7 @@ help: Replace with `list` 3 | from typing import List 4 | 5 | - - def f(x: typing.List[str]) -> None: -6 + def f(x: list[str]) -> None: -7 | ... +6 ~ def f(x: list[str]) -> None: | note: This is an unsafe fix and may change runtime behavior @@ -72,12 +68,11 @@ UP006 [*] Use `list` instead of `List` for type annotation | help: Replace with `list` | -1 + from __future__ import annotations -2 | import typing --------------------------------------------------------------------------------- -9 | - - def g(x: List[str]) -> None: -10 + def g(x: list[str]) -> None: -11 | ... + 1 + from __future__ import annotations + 2 | import typing + 3 | from typing import List + … + 9 | +10 ~ def g(x: list[str]) -> None: | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_UP007_2.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_UP007_2.py.snap index 92913febad789..b7e9ab72f731d 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_UP007_2.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_UP007_2.py.snap @@ -20,7 +20,6 @@ FA100 [*] Add `from __future__ import annotations` to simplify `typing.Union` help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import typing | note: This is an unsafe fix and may change runtime behavior @@ -35,7 +34,6 @@ FA100 [*] Add `from __future__ import annotations` to simplify `typing.Union` help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import typing | note: This is an unsafe fix and may change runtime behavior @@ -50,7 +48,6 @@ FA100 [*] Add `from __future__ import annotations` to simplify `typing.Union` help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import typing | note: This is an unsafe fix and may change runtime behavior @@ -71,9 +68,7 @@ help: Convert to `X | Y` 3 | from typing import Union 4 | 5 | - - def f(x: Union[str, int, Union[float, bytes]]) -> None: -6 + def f(x: str | int | Union[float, bytes]) -> None: -7 | ... +6 ~ def f(x: str | int | Union[float, bytes]) -> None: | note: This is an unsafe fix and may change runtime behavior @@ -92,9 +87,7 @@ help: Convert to `X | Y` 3 | from typing import Union 4 | 5 | - - def f(x: Union[str, int, Union[float, bytes]]) -> None: -6 + def f(x: Union[str, int, float | bytes]) -> None: -7 | ... +6 ~ def f(x: Union[str, int, float | bytes]) -> None: | note: This is an unsafe fix and may change runtime behavior @@ -108,12 +101,11 @@ UP007 [*] Use `X | Y` for type annotations | help: Convert to `X | Y` | -1 + from __future__ import annotations -2 | import typing --------------------------------------------------------------------------------- -9 | - - def f(x: typing.Union[str, int]) -> None: -10 + def f(x: str | int) -> None: -11 | ... + 1 + from __future__ import annotations + 2 | import typing + 3 | from typing import Union + … + 9 | +10 ~ def f(x: str | int) -> None: | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_UP045_2.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_UP045_2.py.snap index e73ca3fbe89a6..864d87bc6f12a 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_UP045_2.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_UP045_2.py.snap @@ -20,7 +20,6 @@ FA100 [*] Add `from __future__ import annotations` to simplify `typing.Optional` help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import typing | note: This is an unsafe fix and may change runtime behavior @@ -35,7 +34,6 @@ FA100 [*] Add `from __future__ import annotations` to simplify `typing.Optional` help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import typing | note: This is an unsafe fix and may change runtime behavior @@ -56,9 +54,7 @@ help: Convert to `X | None` 3 | from typing import Optional 4 | 5 | - - def f(x: Optional[str]) -> None: -6 + def f(x: str | None) -> None: -7 | ... +6 ~ def f(x: str | None) -> None: | note: This is an unsafe fix and may change runtime behavior @@ -72,12 +68,11 @@ UP045 [*] Use `X | None` for type annotations | help: Convert to `X | None` | -1 + from __future__ import annotations -2 | import typing --------------------------------------------------------------------------------- -9 | - - def f(x: typing.Optional[str]) -> None: -10 + def f(x: str | None) -> None: -11 | ... + 1 + from __future__ import annotations + 2 | import typing + 3 | from typing import Optional + … + 9 | +10 ~ def f(x: str | None) -> None: | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_no_future_annotations_UP006_4.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_no_future_annotations_UP006_4.py.snap index 317262682e88f..d908369c9fa74 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_no_future_annotations_UP006_4.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_no_future_annotations_UP006_4.py.snap @@ -20,7 +20,6 @@ FA100 [*] Add `from __future__ import annotations` to simplify `typing.List` help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import typing | note: This is an unsafe fix and may change runtime behavior @@ -35,6 +34,5 @@ FA100 [*] Add `from __future__ import annotations` to simplify `typing.List` help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import typing | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_no_future_annotations_UP007_2.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_no_future_annotations_UP007_2.py.snap index e0facc57cb258..4c393ebd8631f 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_no_future_annotations_UP007_2.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_no_future_annotations_UP007_2.py.snap @@ -20,7 +20,6 @@ FA100 [*] Add `from __future__ import annotations` to simplify `typing.Union` help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import typing | note: This is an unsafe fix and may change runtime behavior @@ -35,7 +34,6 @@ FA100 [*] Add `from __future__ import annotations` to simplify `typing.Union` help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import typing | note: This is an unsafe fix and may change runtime behavior @@ -50,6 +48,5 @@ FA100 [*] Add `from __future__ import annotations` to simplify `typing.Union` help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import typing | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_no_future_annotations_UP045_2.py.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_no_future_annotations_UP045_2.py.snap index f1b2c2a67475b..5431cc54e763c 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_no_future_annotations_UP045_2.py.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__preview_with_fa100_no_future_annotations_UP045_2.py.snap @@ -20,7 +20,6 @@ FA100 [*] Add `from __future__ import annotations` to simplify `typing.Optional` help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import typing | note: This is an unsafe fix and may change runtime behavior @@ -35,6 +34,5 @@ FA100 [*] Add `from __future__ import annotations` to simplify `typing.Optional` help: Add `from __future__ import annotations` | 1 + from __future__ import annotations -2 | import typing | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__unpack_pep_646_py311.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__unpack_pep_646_py311.snap index 582a0b18d588e..4b3e28a91b8f8 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__unpack_pep_646_py311.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__unpack_pep_646_py311.snap @@ -10,10 +10,8 @@ UP044 [*] Use `*` for unpacking | help: Convert to `*` for unpacking | -5 | - - class C(Generic[Unpack[Shape]]): +6 - class C(Generic[Unpack[Shape]]): 6 + class C(Generic[*Shape]): -7 | pass | note: This is an unsafe fix and may change runtime behavior @@ -26,10 +24,8 @@ UP044 [*] Use `*` for unpacking | help: Convert to `*` for unpacking | -9 | - - class D(Generic[Unpack[Shape]]): +10 - class D(Generic[Unpack[Shape]]): 10 + class D(Generic[*Shape]): -11 | pass | note: This is an unsafe fix and may change runtime behavior @@ -42,10 +38,8 @@ UP044 [*] Use `*` for unpacking | help: Convert to `*` for unpacking | -13 | - - def f(*args: Unpack[tuple[int, ...]]): +14 - def f(*args: Unpack[tuple[int, ...]]): 14 + def f(*args: *tuple[int, ...]): -15 | pass | note: This is an unsafe fix and may change runtime behavior @@ -58,10 +52,8 @@ UP044 [*] Use `*` for unpacking | help: Convert to `*` for unpacking | -17 | - - def f(*args: Unpack[other.Type]): +18 - def f(*args: Unpack[other.Type]): 18 + def f(*args: *other.Type): -19 | pass | note: This is an unsafe fix and may change runtime behavior @@ -74,9 +66,7 @@ UP044 [*] Use `*` for unpacking | help: Convert to `*` for unpacking | -21 | - - def f(*args: Generic[int, Unpack[int]]): +22 - def f(*args: Generic[int, Unpack[int]]): 22 + def f(*args: Generic[int, *int]): -23 | pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__up045_future_annotations_py39.snap b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__up045_future_annotations_py39.snap index c198cf100214b..f1d171c9a6e2a 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__up045_future_annotations_py39.snap +++ b/crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__up045_future_annotations_py39.snap @@ -11,10 +11,8 @@ UP045 [*] Use `X | None` for type annotations | help: Convert to `X | None` | -9 | - - x: Optional[str] # UP045 +10 - x: Optional[str] # UP045 10 + x: str | None # UP045 -11 | x: "Optional[str]" # UP045 | note: This is an unsafe fix and may change runtime behavior @@ -29,10 +27,8 @@ UP045 [*] Use `X | None` for type annotations | help: Convert to `X | None` | -10 | x: Optional[str] # UP045 - - x: "Optional[str]" # UP045 +11 - x: "Optional[str]" # UP045 11 + x: "str | None" # UP045 -12 | cast("Optional[str]", None) # UP045 | note: This is an unsafe fix and may change runtime behavior @@ -48,10 +44,8 @@ UP045 [*] Use `X | None` for type annotations | help: Convert to `X | None` | -11 | x: "Optional[str]" # UP045 - - cast("Optional[str]", None) # UP045 +12 - cast("Optional[str]", None) # UP045 12 + cast("str | None", None) # UP045 -13 | cast(Optional[str], None) # okay, str | None is a runtime error | note: This is an unsafe fix and may change runtime behavior @@ -66,9 +60,7 @@ UP045 [*] Use `X | None` for type annotations | help: Convert to `X | None` | -13 | cast(Optional[str], None) # okay, str | None is a runtime error - - x: TypeAlias = "Optional[str]" # UP045 +14 - x: TypeAlias = "Optional[str]" # UP045 14 + x: TypeAlias = "str | None" # UP045 -15 | x: TypeAlias = Optional[str] # okay | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB101_FURB101_0.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB101_FURB101_0.py.snap index 26150ea92b5c6..51fe99e6cefd5 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB101_FURB101_0.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB101_FURB101_0.py.snap @@ -11,14 +11,12 @@ FURB101 [*] `open` and `read` should be replaced by `Path("file.txt").read_text( | help: Replace with `Path("file.txt").read_text()` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 12 | # FURB101 - - with open("file.txt") as f: - - x = f.read() 13 + x = pathlib.Path("file.txt").read_text() -14 | | FURB101 [*] `open` and `read` should be replaced by `Path("file.txt").read_bytes()` @@ -31,14 +29,12 @@ FURB101 [*] `open` and `read` should be replaced by `Path("file.txt").read_bytes | help: Replace with `Path("file.txt").read_bytes()` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 16 | # FURB101 - - with open("file.txt", "rb") as f: - - x = f.read() 17 + x = pathlib.Path("file.txt").read_bytes() -18 | | FURB101 [*] `open` and `read` should be replaced by `Path("file.txt").read_bytes()` @@ -51,14 +47,12 @@ FURB101 [*] `open` and `read` should be replaced by `Path("file.txt").read_bytes | help: Replace with `Path("file.txt").read_bytes()` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 20 | # FURB101 - - with open("file.txt", mode="rb") as f: - - x = f.read() 21 + x = pathlib.Path("file.txt").read_bytes() -22 | | FURB101 [*] `open` and `read` should be replaced by `Path("file.txt").read_text(encoding="utf8")` @@ -71,14 +65,12 @@ FURB101 [*] `open` and `read` should be replaced by `Path("file.txt").read_text( | help: Replace with `Path("file.txt").read_text(encoding="utf8")` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 24 | # FURB101 - - with open("file.txt", encoding="utf8") as f: - - x = f.read() 25 + x = pathlib.Path("file.txt").read_text(encoding="utf8") -26 | | FURB101 [*] `open` and `read` should be replaced by `Path("file.txt").read_text(errors="ignore")` @@ -91,14 +83,12 @@ FURB101 [*] `open` and `read` should be replaced by `Path("file.txt").read_text( | help: Replace with `Path("file.txt").read_text(errors="ignore")` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 28 | # FURB101 - - with open("file.txt", errors="ignore") as f: - - x = f.read() 29 + x = pathlib.Path("file.txt").read_text(errors="ignore") -30 | | FURB101 [*] `open` and `read` should be replaced by `Path("file.txt").read_text()` @@ -111,14 +101,12 @@ FURB101 [*] `open` and `read` should be replaced by `Path("file.txt").read_text( | help: Replace with `Path("file.txt").read_text()` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 32 | # FURB101 - - with open("file.txt", mode="r") as f: # noqa: FURB120 - - x = f.read() 33 + x = pathlib.Path("file.txt").read_text() -34 | | note: This is an unsafe fix and may change runtime behavior @@ -176,14 +164,12 @@ FURB101 [*] `open` and `read` should be replaced by `Path("file.txt").read_text( | help: Replace with `Path("file.txt").read_text(newline="\r\n")` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 85 | # FURB101 (newline is supported in read_text on Python 3.13+) - - with open("file.txt", newline="\r\n") as f: - - x = f.read() 86 + x = pathlib.Path("file.txt").read_text(newline="\r\n") -87 | | FURB101 [*] `open` and `read` should be replaced by `Path("file.txt").read_text(newline="b")` @@ -196,14 +182,12 @@ FURB101 [*] `open` and `read` should be replaced by `Path("file.txt").read_text( | help: Replace with `Path("file.txt").read_text(newline="b")` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 89 | # FURB101 (dont mistake "newline" for "mode") - - with open("file.txt", newline="b") as f: - - x = f.read() 90 + x = pathlib.Path("file.txt").read_text(newline="b") -91 | | FURB101 [*] `open` and `read` should be replaced by `Path("file.txt").read_text(encoding="utf-8")` @@ -216,14 +200,12 @@ FURB101 [*] `open` and `read` should be replaced by `Path("file.txt").read_text( | help: Replace with `Path("file.txt").read_text(encoding="utf-8")` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 130 | # FURB101 - - with open("file.txt", encoding="utf-8") as f: - - contents: str = f.read() 131 + contents: str = pathlib.Path("file.txt").read_text(encoding="utf-8") -132 | | FURB101 `open` and `read` should be replaced by `Path("file.txt").read_text(encoding="utf-8")` diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB101_FURB101_1.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB101_FURB101_1.py.snap index 71fe1afeb6ce5..7a1e28e130176 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB101_FURB101_1.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB101_FURB101_1.py.snap @@ -12,11 +12,9 @@ FURB101 [*] `Path.open()` followed by `read()` can be replaced by `Path("file.tx | help: Replace with `Path("file.txt").read_text()` | +2 ~ from pathlib import Path 3 | - - with Path("file.txt").open() as f: - - contents = f.read() 4 + contents = Path("file.txt").read_text() -5 | | FURB101 [*] `Path.open()` followed by `read()` can be replaced by `Path("file.txt").read_text()` @@ -30,8 +28,9 @@ FURB101 [*] `Path.open()` followed by `read()` can be replaced by `Path("file.tx | help: Replace with `Path("file.txt").read_text()` | +2 ~ from pathlib import Path +3 | +… 6 | - - with Path("file.txt").open("r") as f: - - contents = f.read() 7 + contents = Path("file.txt").read_text() | diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB101_FURB101_2.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB101_FURB101_2.py.snap index 2334db7612a95..2723fdb048972 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB101_FURB101_2.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB101_FURB101_2.py.snap @@ -12,12 +12,8 @@ FURB101 [*] `open` and `read` should be replaced by `Path("file.txt").read_text( | help: Replace with `Path("file.txt").read_text(encoding="utf-8")` | -1 | # FURB101 - - with open("file.txt", encoding="utf-8") as f: - - _ = f.read() 2 + import pathlib -3 + _ = pathlib.Path("file.txt").read_text(encoding="utf-8") -4 | f = object() +3 ~ _ = pathlib.Path("file.txt").read_text(encoding="utf-8") | FURB101 [*] `open` and `read` should be replaced by `Path("config.yaml").read_text(encoding="utf-8")` @@ -30,13 +26,10 @@ FURB101 [*] `open` and `read` should be replaced by `Path("config.yaml").read_te | help: Replace with `Path("config.yaml").read_text(encoding="utf-8")` | -1 | # FURB101 -2 + import pathlib -3 | with open("file.txt", encoding="utf-8") as f: --------------------------------------------------------------------------------- + 2 + import pathlib + 3 | with open("file.txt", encoding="utf-8") as f: + 4 | _ = f.read() + … 13 | # Rebinding in a later `with ... as config_file` should not suppress this one. - - with open("config.yaml", encoding="utf-8") as config_file: - - config_raw = config_file.read() 14 + config_raw = pathlib.Path("config.yaml").read_text(encoding="utf-8") -15 | | diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB103_FURB103_0.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB103_FURB103_0.py.snap index beeb4adf142da..b26a4fb14967d 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB103_FURB103_0.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB103_FURB103_0.py.snap @@ -11,14 +11,12 @@ FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_tex | help: Replace with `Path("file.txt").write_text("test")` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 12 | # FURB103 - - with open("file.txt", "w") as f: - - f.write("test") 13 + pathlib.Path("file.txt").write_text("test") -14 | | FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_bytes(foobar)` @@ -31,14 +29,12 @@ FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_byt | help: Replace with `Path("file.txt").write_bytes(foobar)` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 16 | # FURB103 - - with open("file.txt", "wb") as f: - - f.write(foobar) 17 + pathlib.Path("file.txt").write_bytes(foobar) -18 | | FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_bytes(b"abc")` @@ -51,14 +47,12 @@ FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_byt | help: Replace with `Path("file.txt").write_bytes(b"abc")` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 20 | # FURB103 - - with open("file.txt", mode="wb") as f: - - f.write(b"abc") 21 + pathlib.Path("file.txt").write_bytes(b"abc") -22 | | FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_text(foobar, encoding="utf8")` @@ -71,14 +65,12 @@ FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_tex | help: Replace with `Path("file.txt").write_text(foobar, encoding="utf8")` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 24 | # FURB103 - - with open("file.txt", "w", encoding="utf8") as f: - - f.write(foobar) 25 + pathlib.Path("file.txt").write_text(foobar, encoding="utf8") -26 | | FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_text(foobar, errors="ignore")` @@ -91,14 +83,12 @@ FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_tex | help: Replace with `Path("file.txt").write_text(foobar, errors="ignore")` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 28 | # FURB103 - - with open("file.txt", "w", errors="ignore") as f: - - f.write(foobar) 29 + pathlib.Path("file.txt").write_text(foobar, errors="ignore") -30 | | FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_text(foobar)` @@ -111,14 +101,12 @@ FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_tex | help: Replace with `Path("file.txt").write_text(foobar)` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 32 | # FURB103 - - with open("file.txt", mode="w") as f: - - f.write(foobar) 33 + pathlib.Path("file.txt").write_text(foobar) -34 | | FURB103 `open` and `write` should be replaced by `Path(foo()).write_bytes(bar())` @@ -175,14 +163,12 @@ FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_tex | help: Replace with `Path("file.txt").write_text(foobar, newline="\r\n")` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 58 | # FURB103 - - with open("file.txt", "w", newline="\r\n") as f: - - f.write(foobar) 59 + pathlib.Path("file.txt").write_text(foobar, newline="\r\n") -60 | | FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_text(foobar, newline="\r\n")` @@ -195,15 +181,11 @@ FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_tex | help: Replace with `Path("file.txt").write_text(foobar, newline="\r\n")` | -62 | import builtins 63 + import pathlib -64 | +64 + 65 | 66 | # FURB103 - - with builtins.open("file.txt", "w", newline="\r\n") as f: - - f.write(foobar) 67 + pathlib.Path("file.txt").write_text(foobar, newline="\r\n") -68 | | FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_text(foobar, newline="\r\n")` @@ -216,15 +198,11 @@ FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_tex | help: Replace with `Path("file.txt").write_text(foobar, newline="\r\n")` | -70 | from builtins import open as o 71 + import pathlib -72 | +72 + 73 | 74 | # FURB103 - - with o("file.txt", "w", newline="\r\n") as f: - - f.write(foobar) 75 + pathlib.Path("file.txt").write_text(foobar, newline="\r\n") -76 | | FURB103 [*] `open` and `write` should be replaced by `Path("test.json")....` @@ -238,15 +216,11 @@ FURB103 [*] `open` and `write` should be replaced by `Path("test.json")....` | help: Replace with `Path("test.json")....` | -150 | import json 151 + import pathlib -152 | +152 + 153 | data = {"price": 100} 154 | - - with open("test.json", "wb") as f: - - f.write(json.dumps(data, indent=4).encode("utf-8")) 155 + pathlib.Path("test.json").write_bytes(json.dumps(data, indent=4).encode("utf-8")) -156 | | FURB103 [*] `open` and `write` should be replaced by `Path("tmp_path/pyproject.toml")....` @@ -260,13 +234,15 @@ FURB103 [*] `open` and `write` should be replaced by `Path("tmp_path/pyproject.t | help: Replace with `Path("tmp_path/pyproject.toml")....` | -150 | import json 151 + import pathlib -152 | --------------------------------------------------------------------------------- +152 + +153 | data = {"price": 100} + … 158 | # See: https://github.com/astral-sh/ruff/issues/21381 - - with open("tmp_path/pyproject.toml", "w") as f: - - f.write(dedent( 159 + pathlib.Path("tmp_path/pyproject.toml").write_text(dedent( -160 | """ +160 + """ +161 + [project] +162 + other = 1.234 +163 + """, +164 + )) | diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB103_FURB103_1.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB103_FURB103_1.py.snap index 0688ca51385f9..d765fc7370090 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB103_FURB103_1.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB103_FURB103_1.py.snap @@ -12,11 +12,9 @@ FURB103 [*] `Path.open()` followed by `write()` can be replaced by `Path("file.t | help: Replace with `Path("file.txt").write_text("test")` | +1 ~ from pathlib import Path 2 | - - with Path("file.txt").open("w") as f: - - f.write("test") 3 + Path("file.txt").write_text("test") -4 | | FURB103 [*] `Path.open()` followed by `write()` can be replaced by `Path("file.txt").write_bytes(b"test")` @@ -30,11 +28,11 @@ FURB103 [*] `Path.open()` followed by `write()` can be replaced by `Path("file.t | help: Replace with `Path("file.txt").write_bytes(b"test")` | +1 ~ from pathlib import Path +2 | +… 5 | - - with Path("file.txt").open("wb") as f: - - f.write(b"test") 6 + Path("file.txt").write_bytes(b"test") -7 | | FURB103 [*] `Path.open()` followed by `write()` can be replaced by `Path("file.txt").write_text("test")` @@ -47,13 +45,13 @@ FURB103 [*] `Path.open()` followed by `write()` can be replaced by `Path("file.t 10 | f.write("test") | help: Replace with `Path("file.txt").write_text("test")` - | -8 | - - with Path("file.txt").open(mode="w") as f: - - f.write("test") -9 + Path("file.txt").write_text("test") -10 | - | + | +1 ~ from pathlib import Path +2 | +… +8 | +9 + Path("file.txt").write_text("test") + | FURB103 [*] `Path.open()` followed by `write()` can be replaced by `Path("file.txt").write_text("test", encoding="utf8")` --> FURB103_1.py:12:6 @@ -66,11 +64,11 @@ FURB103 [*] `Path.open()` followed by `write()` can be replaced by `Path("file.t | help: Replace with `Path("file.txt").write_text("test", encoding="utf8")` | + 1 ~ from pathlib import Path + 2 | + … 11 | - - with Path("file.txt").open("w", encoding="utf8") as f: - - f.write("test") 12 + Path("file.txt").write_text("test", encoding="utf8") -13 | | FURB103 [*] `Path.open()` followed by `write()` can be replaced by `Path("file.txt").write_text("test", errors="ignore")` @@ -84,11 +82,11 @@ FURB103 [*] `Path.open()` followed by `write()` can be replaced by `Path("file.t | help: Replace with `Path("file.txt").write_text("test", errors="ignore")` | + 1 ~ from pathlib import Path + 2 | + … 14 | - - with Path("file.txt").open("w", errors="ignore") as f: - - f.write("test") 15 + Path("file.txt").write_text("test", errors="ignore") -16 | | FURB103 [*] `Path.open()` followed by `write()` can be replaced by `Path(foo()).write_text("test")` @@ -102,11 +100,11 @@ FURB103 [*] `Path.open()` followed by `write()` can be replaced by `Path(foo()). | help: Replace with `Path(foo()).write_text("test")` | + 1 ~ from pathlib import Path + 2 | + … 17 | - - with Path(foo()).open("w") as f: - - f.write("test") 18 + Path(foo()).write_text("test") -19 | | FURB103 [*] `Path.open()` followed by `write()` can be replaced by `p.write_text("test")` @@ -119,11 +117,11 @@ FURB103 [*] `Path.open()` followed by `write()` can be replaced by `p.write_text | help: Replace with `p.write_text("test")` | + 1 ~ from pathlib import Path + 2 | + … 21 | p = Path("file.txt") - - with p.open("w") as f: - - f.write("test") 22 + p.write_text("test") -23 | | FURB103 [*] `Path.open()` followed by `write()` can be replaced by `Path("foo", "bar", "baz").write_text("test")` @@ -137,8 +135,9 @@ FURB103 [*] `Path.open()` followed by `write()` can be replaced by `Path("foo", | help: Replace with `Path("foo", "bar", "baz").write_text("test")` | + 1 ~ from pathlib import Path + 2 | + … 24 | - - with Path("foo", "bar", "baz").open("w") as f: - - f.write("test") 25 + Path("foo", "bar", "baz").write_text("test") | diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB103_FURB103_2.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB103_FURB103_2.py.snap index 1a0ac6a5fb1c4..e6256bdbb2838 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB103_FURB103_2.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB103_FURB103_2.py.snap @@ -13,12 +13,8 @@ FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_tex | help: Replace with `Path("file.txt").write_text("\n", encoding="utf-8")` | -2 | # should trigger - - with open("file.txt", "w", encoding="utf-8") as f: - - f.write("\n") 3 + import pathlib -4 + pathlib.Path("file.txt").write_text("\n", encoding="utf-8") -5 | f = object() +4 ~ pathlib.Path("file.txt").write_text("\n", encoding="utf-8") | FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_text("\n")` @@ -33,15 +29,12 @@ FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_tex | help: Replace with `Path("file.txt").write_text("\n")` | -2 | # should trigger -3 + import pathlib -4 | with open("file.txt", "w", encoding="utf-8") as f: --------------------------------------------------------------------------------- + 3 + import pathlib + 4 | with open("file.txt", "w", encoding="utf-8") as f: + 5 | f.write("\n") + … 16 | # should trigger - - with open("file.txt", "w") as f: - - f.write("\n") -17 + pathlib.Path("file.txt").write_text("\n") -18 | return (f.name for _ in [0]) +17 ~ pathlib.Path("file.txt").write_text("\n") | FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_text("\n")` @@ -56,13 +49,10 @@ FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_tex | help: Replace with `Path("file.txt").write_text("\n")` | -2 | # should trigger -3 + import pathlib -4 | with open("file.txt", "w", encoding="utf-8") as f: --------------------------------------------------------------------------------- + 3 + import pathlib + 4 | with open("file.txt", "w", encoding="utf-8") as f: + 5 | f.write("\n") + … 23 | # should trigger - - with open("file.txt", "w") as f: - - f.write("\n") -24 + pathlib.Path("file.txt").write_text("\n") -25 | g = {f.name for _ in [0]} +24 ~ pathlib.Path("file.txt").write_text("\n") | diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB105_FURB105.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB105_FURB105.py.snap index 3b5583ab03894..fd8c2dc61fde4 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB105_FURB105.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB105_FURB105.py.snap @@ -13,10 +13,8 @@ FURB105 [*] Unnecessary empty string passed to `print` | help: Remove empty string | -2 | - - print("") +3 - print("") 3 + print() -4 | print("", sep=",") | FURB105 [*] Unnecessary empty string and separator passed to `print` @@ -30,10 +28,8 @@ FURB105 [*] Unnecessary empty string and separator passed to `print` | help: Remove empty string and separator | -3 | print("") - - print("", sep=",") +4 - print("", sep=",") 4 + print() -5 | print("", end="bar") | FURB105 [*] Unnecessary empty string passed to `print` @@ -48,10 +44,8 @@ FURB105 [*] Unnecessary empty string passed to `print` | help: Remove empty string | -4 | print("", sep=",") - - print("", end="bar") +5 - print("", end="bar") 5 + print(end="bar") -6 | print("", sep=",", end="bar") | FURB105 [*] Unnecessary empty string and separator passed to `print` @@ -66,10 +60,8 @@ FURB105 [*] Unnecessary empty string and separator passed to `print` | help: Remove empty string and separator | -5 | print("", end="bar") - - print("", sep=",", end="bar") +6 - print("", sep=",", end="bar") 6 + print(end="bar") -7 | print(sep="") | FURB105 [*] Unnecessary separator passed to `print` @@ -84,10 +76,8 @@ FURB105 [*] Unnecessary separator passed to `print` | help: Remove separator | -6 | print("", sep=",", end="bar") - - print(sep="") +7 - print(sep="") 7 + print() -8 | print("", sep="") | FURB105 [*] Unnecessary empty string and separator passed to `print` @@ -102,10 +92,8 @@ FURB105 [*] Unnecessary empty string and separator passed to `print` | help: Remove empty string and separator | -7 | print(sep="") - - print("", sep="") +8 - print("", sep="") 8 + print() -9 | print("", "", sep="") | FURB105 [*] Unnecessary empty string and separator passed to `print` @@ -119,12 +107,10 @@ FURB105 [*] Unnecessary empty string and separator passed to `print` 11 | print("", "", sep="", end="bar") | help: Remove empty string and separator - | -8 | print("", sep="") - - print("", "", sep="") -9 + print() -10 | print("", "", sep="", end="") - | + | +9 - print("", "", sep="") +9 + print() + | FURB105 [*] Unnecessary empty string and separator passed to `print` --> FURB105.py:10:1 @@ -138,10 +124,8 @@ FURB105 [*] Unnecessary empty string and separator passed to `print` | help: Remove empty string and separator | -9 | print("", "", sep="") - - print("", "", sep="", end="") +10 - print("", "", sep="", end="") 10 + print(end="") -11 | print("", "", sep="", end="bar") | FURB105 [*] Unnecessary empty string and separator passed to `print` @@ -156,10 +140,8 @@ FURB105 [*] Unnecessary empty string and separator passed to `print` | help: Remove empty string and separator | -10 | print("", "", sep="", end="") - - print("", "", sep="", end="bar") +11 - print("", "", sep="", end="bar") 11 + print(end="bar") -12 | print("", sep="", end="bar") | FURB105 [*] Unnecessary empty string and separator passed to `print` @@ -174,10 +156,8 @@ FURB105 [*] Unnecessary empty string and separator passed to `print` | help: Remove empty string and separator | -11 | print("", "", sep="", end="bar") - - print("", sep="", end="bar") +12 - print("", sep="", end="bar") 12 + print(end="bar") -13 | print(sep="", end="bar") | FURB105 [*] Unnecessary separator passed to `print` @@ -192,10 +172,8 @@ FURB105 [*] Unnecessary separator passed to `print` | help: Remove separator | -12 | print("", sep="", end="bar") - - print(sep="", end="bar") +13 - print(sep="", end="bar") 13 + print(end="bar") -14 | print("", "foo", sep="") | FURB105 [*] Unnecessary empty string and separator passed to `print` @@ -210,10 +188,8 @@ FURB105 [*] Unnecessary empty string and separator passed to `print` | help: Remove empty string and separator | -13 | print(sep="", end="bar") - - print("", "foo", sep="") +14 - print("", "foo", sep="") 14 + print("foo") -15 | print("foo", "", sep="") | FURB105 [*] Unnecessary empty string and separator passed to `print` @@ -228,10 +204,8 @@ FURB105 [*] Unnecessary empty string and separator passed to `print` | help: Remove empty string and separator | -14 | print("", "foo", sep="") - - print("foo", "", sep="") +15 - print("foo", "", sep="") 15 + print("foo") -16 | print("foo", "", "bar", sep="") | FURB105 [*] Unnecessary empty string passed to `print` @@ -246,10 +220,8 @@ FURB105 [*] Unnecessary empty string passed to `print` | help: Remove empty string | -15 | print("foo", "", sep="") - - print("foo", "", "bar", sep="") +16 - print("foo", "", "bar", sep="") 16 + print("foo", "bar", sep="") -17 | print("", *args) | FURB105 [*] Unnecessary empty string passed to `print` @@ -264,10 +236,8 @@ FURB105 [*] Unnecessary empty string passed to `print` | help: Remove empty string | -17 | print("", *args) - - print("", *args, sep="") +18 - print("", *args, sep="") 18 + print(*args, sep="") -19 | print("", **kwargs) | FURB105 [*] Unnecessary empty string passed to `print` @@ -282,10 +252,8 @@ FURB105 [*] Unnecessary empty string passed to `print` | help: Remove empty string | -18 | print("", *args, sep="") - - print("", **kwargs) +19 - print("", **kwargs) 19 + print(**kwargs) -20 | print(sep="\t") | FURB105 [*] Unnecessary separator passed to `print` @@ -300,10 +268,8 @@ FURB105 [*] Unnecessary separator passed to `print` | help: Remove separator | -19 | print("", **kwargs) - - print(sep="\t") +20 - print(sep="\t") 20 + print() -21 | print(sep=print(1)) | FURB105 [*] Unnecessary separator passed to `print` @@ -318,10 +284,8 @@ FURB105 [*] Unnecessary separator passed to `print` | help: Remove separator | -20 | print(sep="\t") - - print(sep=print(1)) +21 - print(sep=print(1)) 21 + print() -22 | print(f"") | note: This is an unsafe fix and may change runtime behavior @@ -337,10 +301,8 @@ FURB105 [*] Unnecessary empty string passed to `print` | help: Remove empty string | -21 | print(sep=print(1)) - - print(f"") +22 - print(f"") 22 + print() -23 | print(f"", sep=",") | FURB105 [*] Unnecessary empty string and separator passed to `print` @@ -355,10 +317,8 @@ FURB105 [*] Unnecessary empty string and separator passed to `print` | help: Remove empty string and separator | -22 | print(f"") - - print(f"", sep=",") +23 - print(f"", sep=",") 23 + print() -24 | print(f"", end="bar") | FURB105 [*] Unnecessary empty string passed to `print` @@ -372,10 +332,8 @@ FURB105 [*] Unnecessary empty string passed to `print` | help: Remove empty string | -23 | print(f"", sep=",") - - print(f"", end="bar") +24 - print(f"", end="bar") 24 + print(end="bar") -25 | print(1, sep=None) | FURB105 [*] Unnecessary separator passed to `print` @@ -390,10 +348,8 @@ FURB105 [*] Unnecessary separator passed to `print` | help: Remove separator | -24 | print(f"", end="bar") - - print(1, sep=None) +25 - print(1, sep=None) 25 + print(1) -26 | | FURB105 [*] Unnecessary separator passed to `print` @@ -407,10 +363,8 @@ FURB105 [*] Unnecessary separator passed to `print` | help: Remove separator | -27 | def p(sep): - - print(1, sep=sep) +28 - print(1, sep=sep) 28 + print(1) -29 | | note: This is an unsafe fix and may change runtime behavior @@ -424,11 +378,10 @@ FURB105 [*] Unnecessary empty string passed to `print` | |_^ help: Remove empty string | -45 | - - print( - - # text - - "" - - ) +46 - print( +47 - # text +48 - "" +49 - ) 46 + print() | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB110_FURB110.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB110_FURB110.py.snap index 3501e0947e3cb..eb0d19f7cce7a 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB110_FURB110.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB110_FURB110.py.snap @@ -11,9 +11,8 @@ FURB110 [*] Replace ternary `if` expression with `or` operator | help: Replace with `or` operator | - - z = x if x else y # FURB110 +1 - z = x if x else y # FURB110 1 + z = x or y # FURB110 -2 | | FURB110 [*] Replace ternary `if` expression with `or` operator @@ -30,11 +29,9 @@ FURB110 [*] Replace ternary `if` expression with `or` operator | help: Replace with `or` operator | -2 | - - z = x \ - - if x else y # FURB110 +3 - z = x \ +4 - if x else y # FURB110 3 + z = x or y # FURB110 -4 | | FURB110 [*] Replace ternary `if` expression with `or` operator @@ -52,12 +49,10 @@ FURB110 [*] Replace ternary `if` expression with `or` operator | help: Replace with `or` operator | -5 | - - z = x if x \ - - else \ - - y # FURB110 +6 - z = x if x \ +7 - else \ +8 - y # FURB110 6 + z = x or y # FURB110 -7 | | FURB110 [*] Replace ternary `if` expression with `or` operator @@ -72,10 +67,8 @@ FURB110 [*] Replace ternary `if` expression with `or` operator | help: Replace with `or` operator | -9 | - - z = x() if x() else y() # FURB110 +10 - z = x() if x() else y() # FURB110 10 + z = x() or y() # FURB110 -11 | | note: This is an unsafe fix and may change runtime behavior @@ -97,14 +90,13 @@ FURB110 [*] Replace ternary `if` expression with `or` operator | help: Replace with `or` operator | -12 | # FURB110 - - z = x if ( -13 + z = ( -14 | # Test for x. -15 | x - - ) else ( +13 ~ z = ( +14 + # Test for x. +15 + x 16 + ) or ( -17 | # Test for y. +17 + # Test for y. +18 + y +19 + ) | note: This is an unsafe fix and may change runtime behavior @@ -125,14 +117,13 @@ FURB110 [*] Replace ternary `if` expression with `or` operator | help: Replace with `or` operator | -22 | z = ( - - x if ( -23 + ( -24 | # Test for x. -25 | x - - ) else ( +23 ~ ( +24 + # Test for x. +25 + x 26 + ) or ( -27 | # Test for y. +27 + # Test for y. +28 + y +29 + ) | note: This is an unsafe fix and may change runtime behavior @@ -152,15 +143,13 @@ FURB110 [*] Replace ternary `if` expression with `or` operator | help: Replace with `or` operator | -33 | z = ( - - x if - - # If true, use x. - - x - - # Otherwise, use y. - - else - - y +34 - x if +35 - # If true, use x. +36 - x +37 - # Otherwise, use y. +38 - else +39 - y 34 + x or y -35 | ) | note: This is an unsafe fix and may change runtime behavior @@ -179,15 +168,9 @@ FURB110 [*] Replace ternary `if` expression with `or` operator | help: Replace with `or` operator | -43 | z = ( - - x - - if x - - else y -44 + x or (y -45 | if y > 0 - - else None +44 ~ x or (y +45 + if y > 0 46 + else None) -47 | ) | FURB110 [*] Replace ternary `if` expression with `or` operator @@ -203,12 +186,10 @@ FURB110 [*] Replace ternary `if` expression with `or` operator | help: Replace with `or` operator | -52 | z = ( - - x - - if x - - # text - - else y +53 - x +54 - if x +55 - # text +56 - else y 53 + x or y -54 | ) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB113_FURB113.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB113_FURB113.py.snap index 346998d67ea50..aa03a16e23f5f 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB113_FURB113.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB113_FURB113.py.snap @@ -12,11 +12,9 @@ FURB113 [*] Use `nums.extend((1, 2))` instead of repeatedly calling `nums.append | help: Replace with `nums.extend((1, 2))` | -22 | # FURB113 - - nums.append(1) - - nums.append(2) +23 - nums.append(1) +24 - nums.append(2) 23 + nums.extend((1, 2)) -24 | pass | note: This is an unsafe fix and may change runtime behavior @@ -31,11 +29,9 @@ FURB113 [*] Use `nums3.extend((1, 2))` instead of repeatedly calling `nums3.appe | help: Replace with `nums3.extend((1, 2))` | -28 | # FURB113 - - nums3.append(1) - - nums3.append(2) +29 - nums3.append(1) +30 - nums3.append(2) 29 + nums3.extend((1, 2)) -30 | pass | note: This is an unsafe fix and may change runtime behavior @@ -50,11 +46,9 @@ FURB113 [*] Use `nums4.extend((1, 2))` instead of repeatedly calling `nums4.appe | help: Replace with `nums4.extend((1, 2))` | -34 | # FURB113 - - nums4.append(1) - - nums4.append(2) +35 - nums4.append(1) +36 - nums4.append(2) 35 + nums4.extend((1, 2)) -36 | pass | note: This is an unsafe fix and may change runtime behavior @@ -116,11 +110,9 @@ FURB113 [*] Use `nums4.extend((1, 2))` instead of repeatedly calling `nums4.appe | help: Replace with `nums4.extend((1, 2))` | -55 | # FURB113 - - nums4.append(1) - - nums4.append(2) +56 - nums4.append(1) +57 - nums4.append(2) 56 + nums4.extend((1, 2)) -57 | nums3.append(2) | note: This is an unsafe fix and may change runtime behavior @@ -134,12 +126,10 @@ FURB113 [*] Use `nums.extend((1, 2, 3))` instead of repeatedly calling `nums.app | |______________^ help: Replace with `nums.extend((1, 2, 3))` | -61 | # FURB113 - - nums.append(1) - - nums.append(2) - - nums.append(3) +62 - nums.append(1) +63 - nums.append(2) +64 - nums.append(3) 62 + nums.extend((1, 2, 3)) -63 | | note: This is an unsafe fix and may change runtime behavior @@ -153,11 +143,9 @@ FURB113 [*] Use `nums.extend((1, 2))` instead of repeatedly calling `nums.append | |__________________^ help: Replace with `nums.extend((1, 2))` | -68 | # FURB113 - - nums.append(1) - - nums.append(2) +69 - nums.append(1) +70 - nums.append(2) 69 + nums.extend((1, 2)) -70 | | note: This is an unsafe fix and may change runtime behavior @@ -173,11 +161,9 @@ FURB113 [*] Use `nums.extend((1, 2))` instead of repeatedly calling `nums.append | help: Replace with `nums.extend((1, 2))` | -74 | # FURB113 - - nums.append(1) - - nums.append(2) +75 - nums.append(1) +76 - nums.append(2) 75 + nums.extend((1, 2)) -76 | pass | note: This is an unsafe fix and may change runtime behavior @@ -203,11 +189,9 @@ FURB113 [*] Use `x.extend((1, 2))` instead of repeatedly calling `x.append()` | |_______________^ help: Replace with `x.extend((1, 2))` | -89 | # FURB113 - - x.append(1) - - x.append(2) +90 - x.append(1) +91 - x.append(2) 90 + x.extend((1, 2)) -91 | | note: This is an unsafe fix and may change runtime behavior @@ -221,11 +205,9 @@ FURB113 [*] Use `x.extend((1, 2))` instead of repeatedly calling `x.append()` | |_______________^ help: Replace with `x.extend((1, 2))` | -95 | # FURB113 - - x.append(1) - - x.append(2) +96 - x.append(1) +97 - x.append(2) 96 + x.extend((1, 2)) -97 | | note: This is an unsafe fix and may change runtime behavior @@ -239,11 +221,9 @@ FURB113 [*] Use `x.extend((1, 2))` instead of repeatedly calling `x.append()` | |_______________^ help: Replace with `x.extend((1, 2))` | -101 | # FURB113 - - x.append(1) - - x.append(2) +102 - x.append(1) +103 - x.append(2) 102 + x.extend((1, 2)) -103 | | note: This is an unsafe fix and may change runtime behavior @@ -257,11 +237,9 @@ FURB113 [*] Use `x.extend((1, 2))` instead of repeatedly calling `x.append()` | |_______________^ help: Replace with `x.extend((1, 2))` | -107 | # FURB113 - - x.append(1) - - x.append(2) +108 - x.append(1) +109 - x.append(2) 108 + x.extend((1, 2)) -109 | | note: This is an unsafe fix and may change runtime behavior @@ -287,11 +265,9 @@ FURB113 [*] Use `x.extend((1, 2))` instead of repeatedly calling `x.append()` | |_______________^ help: Replace with `x.extend((1, 2))` | -121 | # FURB113 - - x.append(1) - - x.append(2) +122 - x.append(1) +123 - x.append(2) 122 + x.extend((1, 2)) -123 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB116_FURB116.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB116_FURB116.py.snap index fe95ed16e7fd5..71e3ac164a5f1 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB116_FURB116.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB116_FURB116.py.snap @@ -12,12 +12,10 @@ FURB116 [*] Replace `oct` call with `f"{num:o}"` 11 | print(bin(num)[2:]) # FURB116 | help: Replace with `f"{num:o}"` - | -8 | - - print(oct(num)[2:]) # FURB116 -9 + print(f"{num:o}") # FURB116 -10 | print(hex(num)[2:]) # FURB116 - | + | +9 - print(oct(num)[2:]) # FURB116 +9 + print(f"{num:o}") # FURB116 + | note: This is a display-only fix and is likely to be incorrect FURB116 [*] Replace `hex` call with `f"{num:x}"` @@ -30,10 +28,8 @@ FURB116 [*] Replace `hex` call with `f"{num:x}"` | help: Replace with `f"{num:x}"` | -9 | print(oct(num)[2:]) # FURB116 - - print(hex(num)[2:]) # FURB116 +10 - print(hex(num)[2:]) # FURB116 10 + print(f"{num:x}") # FURB116 -11 | print(bin(num)[2:]) # FURB116 | note: This is a display-only fix and is likely to be incorrect @@ -49,10 +45,8 @@ FURB116 [*] Replace `bin` call with `f"{num:b}"` | help: Replace with `f"{num:b}"` | -10 | print(hex(num)[2:]) # FURB116 - - print(bin(num)[2:]) # FURB116 +11 - print(bin(num)[2:]) # FURB116 11 + print(f"{num:b}") # FURB116 -12 | | note: This is a display-only fix and is likely to be incorrect @@ -68,10 +62,8 @@ FURB116 [*] Replace `oct` call with `f"{1337:o}"` | help: Replace with `f"{1337:o}"` | -12 | - - print(oct(1337)[2:]) # FURB116 +13 - print(oct(1337)[2:]) # FURB116 13 + print(f"{1337:o}") # FURB116 -14 | print(hex(1337)[2:]) # FURB116 | FURB116 [*] Replace `hex` call with `f"{1337:x}"` @@ -85,10 +77,8 @@ FURB116 [*] Replace `hex` call with `f"{1337:x}"` | help: Replace with `f"{1337:x}"` | -13 | print(oct(1337)[2:]) # FURB116 - - print(hex(1337)[2:]) # FURB116 +14 - print(hex(1337)[2:]) # FURB116 14 + print(f"{1337:x}") # FURB116 -15 | print(bin(1337)[2:]) # FURB116 | FURB116 [*] Replace `bin` call with `f"{1337:b}"` @@ -102,10 +92,8 @@ FURB116 [*] Replace `bin` call with `f"{1337:b}"` | help: Replace with `f"{1337:b}"` | -14 | print(hex(1337)[2:]) # FURB116 - - print(bin(1337)[2:]) # FURB116 +15 - print(bin(1337)[2:]) # FURB116 15 + print(f"{1337:b}") # FURB116 -16 | print(bin(+1337)[2:]) # FURB116 | FURB116 [*] Replace `bin` call with `f"{+1337:b}"` @@ -120,10 +108,8 @@ FURB116 [*] Replace `bin` call with `f"{+1337:b}"` | help: Replace with `f"{+1337:b}"` | -15 | print(bin(1337)[2:]) # FURB116 - - print(bin(+1337)[2:]) # FURB116 +16 - print(bin(+1337)[2:]) # FURB116 16 + print(f"{+1337:b}") # FURB116 -17 | | FURB116 Replace `bin` call with f-string @@ -160,10 +146,8 @@ FURB116 [*] Replace `bin` call with `f"{d:b}"` | help: Replace with `f"{d:b}"` | -31 | # autofix is display-only - - print(bin(d)[2:]) +32 - print(bin(d)[2:]) 32 + print(f"{d:b}") -33 | # no autofix for Python 3.11 and earlier, as it introduces a syntax error | note: This is a display-only fix and is likely to be incorrect @@ -179,10 +163,8 @@ FURB116 [*] Replace `bin` call with `f"{len("xyz").numerator:b}"` | help: Replace with `f"{len("xyz").numerator:b}"` | -33 | # no autofix for Python 3.11 and earlier, as it introduces a syntax error - - print(bin(len("xyz").numerator)[2:]) +34 - print(bin(len("xyz").numerator)[2:]) 34 + print(f"{len("xyz").numerator:b}") -35 | | note: This is a display-only fix and is likely to be incorrect @@ -197,10 +179,8 @@ FURB116 [*] Replace `bin` call with `f"{ {0: 1}[0].numerator:b}"` | help: Replace with `f"{ {0: 1}[0].numerator:b}"` | -36 | # autofix is display-only - - print(bin({0: 1}[0].numerator)[2:]) +37 - print(bin({0: 1}[0].numerator)[2:]) 37 + print(f"{ {0: 1}[0].numerator:b}") -38 | # no autofix for Python 3.11 and earlier, as it introduces a syntax error | note: This is a display-only fix and is likely to be incorrect @@ -216,10 +196,8 @@ FURB116 [*] Replace `bin` call with `f"{ord("\\").numerator:b}"` | help: Replace with `f"{ord("\\").numerator:b}"` | -38 | # no autofix for Python 3.11 and earlier, as it introduces a syntax error - - print(bin(ord("\\").numerator)[2:]) +39 - print(bin(ord("\\").numerator)[2:]) 39 + print(f"{ord("\\").numerator:b}") -40 | print(hex(sys | note: This is a display-only fix and is likely to be incorrect @@ -237,12 +215,8 @@ FURB116 [*] Replace `hex` call with f-string | help: Replace with f-string | -39 | print(bin(ord("\\").numerator)[2:]) - - print(hex(sys - - .maxunicode)[2:]) -40 + print(f"{sys -41 + .maxunicode:x}") -42 | +40 ~ print(f"{sys +41 ~ .maxunicode:x}") | note: This is a display-only fix and is likely to be incorrect @@ -254,10 +228,8 @@ FURB116 [*] Replace `bin` call with `f"{-1:b}"` | ^^^^^^^^^^^ help: Replace with `f"{-1:b}"` | -43 | # for negatives numbers autofix is display-only - - print(bin(-1)[2:]) +44 - print(bin(-1)[2:]) 44 + print(f"{-1:b}") -45 | | note: This is a display-only fix and is likely to be incorrect @@ -274,12 +246,10 @@ FURB116 [*] Replace `bin` call with `f"{1337:b}"` | help: Replace with `f"{1337:b}"` | -47 | print( - - bin( - - 1337 - - # text - - )[2:] +48 - bin( +49 - 1337 +50 - # text +51 - )[2:] 48 + f"{1337:b}" -49 | ) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB118_FURB118.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB118_FURB118.py.snap index 306415bd82ed8..626fb0ed255e7 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB118_FURB118.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB118_FURB118.py.snap @@ -12,11 +12,8 @@ FURB118 [*] Use `operator.invert` instead of defining a lambda | help: Replace with `operator.invert` | -1 | # Errors. - - op_bitnot = lambda x: ~x 2 + import operator -3 + op_bitnot = operator.invert -4 | op_not = lambda x: not x +3 ~ op_bitnot = operator.invert | note: This is an unsafe fix and may change runtime behavior @@ -32,12 +29,9 @@ FURB118 [*] Use `operator.not_` instead of defining a lambda | help: Replace with `operator.not_` | -1 | # Errors. 2 + import operator 3 | op_bitnot = lambda x: ~x - - op_not = lambda x: not x -4 + op_not = operator.not_ -5 | op_pos = lambda x: +x +4 ~ op_not = operator.not_ | note: This is an unsafe fix and may change runtime behavior @@ -52,13 +46,10 @@ FURB118 [*] Use `operator.pos` instead of defining a lambda | help: Replace with `operator.pos` | -1 | # Errors. 2 + import operator 3 | op_bitnot = lambda x: ~x 4 | op_not = lambda x: not x - - op_pos = lambda x: +x -5 + op_pos = operator.pos -6 | op_neg = lambda x: -x +5 ~ op_pos = operator.pos | note: This is an unsafe fix and may change runtime behavior @@ -74,14 +65,11 @@ FURB118 [*] Use `operator.neg` instead of defining a lambda | help: Replace with `operator.neg` | -1 | # Errors. 2 + import operator 3 | op_bitnot = lambda x: ~x 4 | op_not = lambda x: not x 5 | op_pos = lambda x: +x - - op_neg = lambda x: -x -6 + op_neg = operator.neg -7 | +6 ~ op_neg = operator.neg | note: This is an unsafe fix and may change runtime behavior @@ -97,14 +85,12 @@ FURB118 [*] Use `operator.add` instead of defining a lambda | help: Replace with `operator.add` | -1 | # Errors. 2 + import operator 3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- +4 | op_not = lambda x: not x +… 7 | - - op_add = lambda x, y: x + y -8 + op_add = operator.add -9 | op_sub = lambda x, y: x - y +8 ~ op_add = operator.add | note: This is an unsafe fix and may change runtime behavior @@ -118,16 +104,14 @@ FURB118 [*] Use `operator.sub` instead of defining a lambda 10 | op_matmutl = lambda x, y: x @ y | help: Replace with `operator.sub` - | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- -8 | op_add = lambda x, y: x + y - - op_sub = lambda x, y: x - y -9 + op_sub = operator.sub -10 | op_mult = lambda x, y: x * y - | + | +2 + import operator +3 | op_bitnot = lambda x: ~x +4 | op_not = lambda x: not x +… +8 | op_add = lambda x, y: x + y +9 ~ op_sub = operator.sub + | note: This is an unsafe fix and may change runtime behavior FURB118 [*] Use `operator.mul` instead of defining a lambda @@ -142,14 +126,12 @@ FURB118 [*] Use `operator.mul` instead of defining a lambda | help: Replace with `operator.mul` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- -9 | op_sub = lambda x, y: x - y - - op_mult = lambda x, y: x * y -10 + op_mult = operator.mul -11 | op_matmutl = lambda x, y: x @ y + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … + 9 | op_sub = lambda x, y: x - y +10 ~ op_mult = operator.mul | note: This is an unsafe fix and may change runtime behavior @@ -165,14 +147,12 @@ FURB118 [*] Use `operator.matmul` instead of defining a lambda | help: Replace with `operator.matmul` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 10 | op_mult = lambda x, y: x * y - - op_matmutl = lambda x, y: x @ y -11 + op_matmutl = operator.matmul -12 | op_truediv = lambda x, y: x / y +11 ~ op_matmutl = operator.matmul | note: This is an unsafe fix and may change runtime behavior @@ -188,14 +168,12 @@ FURB118 [*] Use `operator.truediv` instead of defining a lambda | help: Replace with `operator.truediv` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 11 | op_matmutl = lambda x, y: x @ y - - op_truediv = lambda x, y: x / y -12 + op_truediv = operator.truediv -13 | op_mod = lambda x, y: x % y +12 ~ op_truediv = operator.truediv | note: This is an unsafe fix and may change runtime behavior @@ -211,14 +189,12 @@ FURB118 [*] Use `operator.mod` instead of defining a lambda | help: Replace with `operator.mod` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 12 | op_truediv = lambda x, y: x / y - - op_mod = lambda x, y: x % y -13 + op_mod = operator.mod -14 | op_pow = lambda x, y: x ** y +13 ~ op_mod = operator.mod | note: This is an unsafe fix and may change runtime behavior @@ -234,14 +210,12 @@ FURB118 [*] Use `operator.pow` instead of defining a lambda | help: Replace with `operator.pow` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 13 | op_mod = lambda x, y: x % y - - op_pow = lambda x, y: x ** y -14 + op_pow = operator.pow -15 | op_lshift = lambda x, y: x << y +14 ~ op_pow = operator.pow | note: This is an unsafe fix and may change runtime behavior @@ -257,14 +231,12 @@ FURB118 [*] Use `operator.lshift` instead of defining a lambda | help: Replace with `operator.lshift` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 14 | op_pow = lambda x, y: x ** y - - op_lshift = lambda x, y: x << y -15 + op_lshift = operator.lshift -16 | op_rshift = lambda x, y: x >> y +15 ~ op_lshift = operator.lshift | note: This is an unsafe fix and may change runtime behavior @@ -280,14 +252,12 @@ FURB118 [*] Use `operator.rshift` instead of defining a lambda | help: Replace with `operator.rshift` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 15 | op_lshift = lambda x, y: x << y - - op_rshift = lambda x, y: x >> y -16 + op_rshift = operator.rshift -17 | op_bitor = lambda x, y: x | y +16 ~ op_rshift = operator.rshift | note: This is an unsafe fix and may change runtime behavior @@ -303,14 +273,12 @@ FURB118 [*] Use `operator.or_` instead of defining a lambda | help: Replace with `operator.or_` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 16 | op_rshift = lambda x, y: x >> y - - op_bitor = lambda x, y: x | y -17 + op_bitor = operator.or_ -18 | op_xor = lambda x, y: x ^ y +17 ~ op_bitor = operator.or_ | note: This is an unsafe fix and may change runtime behavior @@ -326,14 +294,12 @@ FURB118 [*] Use `operator.xor` instead of defining a lambda | help: Replace with `operator.xor` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 17 | op_bitor = lambda x, y: x | y - - op_xor = lambda x, y: x ^ y -18 + op_xor = operator.xor -19 | op_bitand = lambda x, y: x & y +18 ~ op_xor = operator.xor | note: This is an unsafe fix and may change runtime behavior @@ -348,14 +314,12 @@ FURB118 [*] Use `operator.and_` instead of defining a lambda | help: Replace with `operator.and_` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 18 | op_xor = lambda x, y: x ^ y - - op_bitand = lambda x, y: x & y -19 + op_bitand = operator.and_ -20 | op_floordiv = lambda x, y: x // y +19 ~ op_bitand = operator.and_ | note: This is an unsafe fix and may change runtime behavior @@ -371,14 +335,12 @@ FURB118 [*] Use `operator.floordiv` instead of defining a lambda | help: Replace with `operator.floordiv` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 19 | op_bitand = lambda x, y: x & y - - op_floordiv = lambda x, y: x // y -20 + op_floordiv = operator.floordiv -21 | +20 ~ op_floordiv = operator.floordiv | note: This is an unsafe fix and may change runtime behavior @@ -394,14 +356,12 @@ FURB118 [*] Use `operator.eq` instead of defining a lambda | help: Replace with `operator.eq` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 21 | - - op_eq = lambda x, y: x == y -22 + op_eq = operator.eq -23 | op_ne = lambda x, y: x != y +22 ~ op_eq = operator.eq | note: This is an unsafe fix and may change runtime behavior @@ -416,14 +376,12 @@ FURB118 [*] Use `operator.ne` instead of defining a lambda | help: Replace with `operator.ne` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 22 | op_eq = lambda x, y: x == y - - op_ne = lambda x, y: x != y -23 + op_ne = operator.ne -24 | op_lt = lambda x, y: x < y +23 ~ op_ne = operator.ne | note: This is an unsafe fix and may change runtime behavior @@ -439,14 +397,12 @@ FURB118 [*] Use `operator.lt` instead of defining a lambda | help: Replace with `operator.lt` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 23 | op_ne = lambda x, y: x != y - - op_lt = lambda x, y: x < y -24 + op_lt = operator.lt -25 | op_lte = lambda x, y: x <= y +24 ~ op_lt = operator.lt | note: This is an unsafe fix and may change runtime behavior @@ -462,14 +418,12 @@ FURB118 [*] Use `operator.le` instead of defining a lambda | help: Replace with `operator.le` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 24 | op_lt = lambda x, y: x < y - - op_lte = lambda x, y: x <= y -25 + op_lte = operator.le -26 | op_gt = lambda x, y: x > y +25 ~ op_lte = operator.le | note: This is an unsafe fix and may change runtime behavior @@ -485,14 +439,12 @@ FURB118 [*] Use `operator.gt` instead of defining a lambda | help: Replace with `operator.gt` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 25 | op_lte = lambda x, y: x <= y - - op_gt = lambda x, y: x > y -26 + op_gt = operator.gt -27 | op_gte = lambda x, y: x >= y +26 ~ op_gt = operator.gt | note: This is an unsafe fix and may change runtime behavior @@ -508,14 +460,12 @@ FURB118 [*] Use `operator.ge` instead of defining a lambda | help: Replace with `operator.ge` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 26 | op_gt = lambda x, y: x > y - - op_gte = lambda x, y: x >= y -27 + op_gte = operator.ge -28 | op_is = lambda x, y: x is y +27 ~ op_gte = operator.ge | note: This is an unsafe fix and may change runtime behavior @@ -531,14 +481,12 @@ FURB118 [*] Use `operator.is_` instead of defining a lambda | help: Replace with `operator.is_` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 27 | op_gte = lambda x, y: x >= y - - op_is = lambda x, y: x is y -28 + op_is = operator.is_ -29 | op_isnot = lambda x, y: x is not y +28 ~ op_is = operator.is_ | note: This is an unsafe fix and may change runtime behavior @@ -554,14 +502,12 @@ FURB118 [*] Use `operator.is_not` instead of defining a lambda | help: Replace with `operator.is_not` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 28 | op_is = lambda x, y: x is y - - op_isnot = lambda x, y: x is not y -29 + op_isnot = operator.is_not -30 | op_in = lambda x, y: y in x +29 ~ op_isnot = operator.is_not | note: This is an unsafe fix and may change runtime behavior @@ -577,14 +523,12 @@ FURB118 [*] Use `operator.contains` instead of defining a lambda | help: Replace with `operator.contains` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 29 | op_isnot = lambda x, y: x is not y - - op_in = lambda x, y: y in x -30 + op_in = operator.contains -31 | op_itemgetter = lambda x: x[0] +30 ~ op_in = operator.contains | note: This is an unsafe fix and may change runtime behavior @@ -600,14 +544,12 @@ FURB118 [*] Use `operator.itemgetter(0)` instead of defining a lambda | help: Replace with `operator.itemgetter(0)` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 30 | op_in = lambda x, y: y in x - - op_itemgetter = lambda x: x[0] -31 + op_itemgetter = operator.itemgetter(0) -32 | op_itemgetter = lambda x: (x[0], x[1], x[2]) +31 ~ op_itemgetter = operator.itemgetter(0) | note: This is an unsafe fix and may change runtime behavior @@ -623,14 +565,12 @@ FURB118 [*] Use `operator.itemgetter(0, 1, 2)` instead of defining a lambda | help: Replace with `operator.itemgetter(0, 1, 2)` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 31 | op_itemgetter = lambda x: x[0] - - op_itemgetter = lambda x: (x[0], x[1], x[2]) -32 + op_itemgetter = operator.itemgetter(0, 1, 2) -33 | op_itemgetter = lambda x: (x[1:], x[2]) +32 ~ op_itemgetter = operator.itemgetter(0, 1, 2) | note: This is an unsafe fix and may change runtime behavior @@ -646,14 +586,12 @@ FURB118 [*] Use `operator.itemgetter(slice(1, None), 2)` instead of defining a l | help: Replace with `operator.itemgetter(slice(1, None), 2)` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 32 | op_itemgetter = lambda x: (x[0], x[1], x[2]) - - op_itemgetter = lambda x: (x[1:], x[2]) -33 + op_itemgetter = operator.itemgetter(slice(1, None), 2) -34 | op_itemgetter = lambda x: x[:] +33 ~ op_itemgetter = operator.itemgetter(slice(1, None), 2) | note: This is an unsafe fix and may change runtime behavior @@ -669,14 +607,12 @@ FURB118 [*] Use `operator.itemgetter(slice(None))` instead of defining a lambda | help: Replace with `operator.itemgetter(slice(None))` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 33 | op_itemgetter = lambda x: (x[1:], x[2]) - - op_itemgetter = lambda x: x[:] -34 + op_itemgetter = operator.itemgetter(slice(None)) -35 | op_itemgetter = lambda x: x[0, 1] +34 ~ op_itemgetter = operator.itemgetter(slice(None)) | note: This is an unsafe fix and may change runtime behavior @@ -691,14 +627,12 @@ FURB118 [*] Use `operator.itemgetter((0, 1))` instead of defining a lambda | help: Replace with `operator.itemgetter((0, 1))` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 34 | op_itemgetter = lambda x: x[:] - - op_itemgetter = lambda x: x[0, 1] -35 + op_itemgetter = operator.itemgetter((0, 1)) -36 | op_itemgetter = lambda x: x[(0, 1)] +35 ~ op_itemgetter = operator.itemgetter((0, 1)) | note: This is an unsafe fix and may change runtime behavior @@ -711,14 +645,12 @@ FURB118 [*] Use `operator.itemgetter((0, 1))` instead of defining a lambda | ^^^^^^^^^^^^^^^^^^^ help: Replace with `operator.itemgetter((0, 1))` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 35 | op_itemgetter = lambda x: x[0, 1] - - op_itemgetter = lambda x: x[(0, 1)] -36 + op_itemgetter = operator.itemgetter((0, 1)) -37 | +36 ~ op_itemgetter = operator.itemgetter((0, 1)) | note: This is an unsafe fix and may change runtime behavior @@ -750,14 +682,12 @@ FURB118 [*] Use `operator.itemgetter((slice(None), 1))` instead of defining a la | help: Replace with `operator.itemgetter((slice(None), 1))` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 88 | # See https://github.com/astral-sh/ruff/issues/13508 - - op_itemgetter = lambda x: x[:, 1] -89 + op_itemgetter = operator.itemgetter((slice(None), 1)) -90 | op_itemgetter = lambda x: x[1, :] +89 ~ op_itemgetter = operator.itemgetter((slice(None), 1)) | note: This is an unsafe fix and may change runtime behavior @@ -773,14 +703,12 @@ FURB118 [*] Use `operator.itemgetter((1, slice(None)))` instead of defining a la | help: Replace with `operator.itemgetter((1, slice(None)))` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 89 | op_itemgetter = lambda x: x[:, 1] - - op_itemgetter = lambda x: x[1, :] -90 + op_itemgetter = operator.itemgetter((1, slice(None))) -91 | +90 ~ op_itemgetter = operator.itemgetter((1, slice(None))) | note: This is an unsafe fix and may change runtime behavior @@ -795,14 +723,12 @@ FURB118 [*] Use `operator.itemgetter((1, slice(None)))` instead of defining a la | help: Replace with `operator.itemgetter((1, slice(None)))` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 92 | # With a slice, trivia is dropped - - op_itemgetter = lambda x: x[1, :] -93 + op_itemgetter = operator.itemgetter((1, slice(None))) -94 | +93 ~ op_itemgetter = operator.itemgetter((1, slice(None))) | note: This is an unsafe fix and may change runtime behavior @@ -814,14 +740,12 @@ FURB118 [*] Use `operator.itemgetter((1, 2))` instead of defining a lam | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `operator.itemgetter((1, 2))` | -1 | # Errors. -2 + import operator -3 | op_bitnot = lambda x: ~x --------------------------------------------------------------------------------- + 2 + import operator + 3 | op_bitnot = lambda x: ~x + 4 | op_not = lambda x: not x + … 95 | # Without a slice, trivia is retained - - op_itemgetter = lambda x: x[1, 2] -96 + op_itemgetter = operator.itemgetter((1, 2)) -97 | +96 ~ op_itemgetter = operator.itemgetter((1, 2)) | note: This is an unsafe fix and may change runtime behavior @@ -837,14 +761,12 @@ FURB118 [*] Use `operator.itemgetter(slice(-2, None))` instead of defining a lam | help: Replace with `operator.itemgetter(slice(-2, None))` | -113 | from typing import final, override, no_type_check 114 + import operator -115 | --------------------------------------------------------------------------------- +115 + +116 | + … 129 | [ - - (lambda x: x[-2:], "foo"), -130 + (operator.itemgetter(slice(-2, None)), "foo"), -131 | (lambda x: x[-5:-3], "bar"), +130 ~ (operator.itemgetter(slice(-2, None)), "foo"), | note: This is an unsafe fix and may change runtime behavior @@ -860,13 +782,11 @@ FURB118 [*] Use `operator.itemgetter(slice(-5, -3))` instead of defining a lambd | help: Replace with `operator.itemgetter(slice(-5, -3))` | -113 | from typing import final, override, no_type_check 114 + import operator -115 | --------------------------------------------------------------------------------- +115 + +116 | + … 130 | (lambda x: x[-2:], "foo"), - - (lambda x: x[-5:-3], "bar"), -131 + (operator.itemgetter(slice(-5, -3)), "bar"), -132 | ], +131 ~ (operator.itemgetter(slice(-5, -3)), "bar"), | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB122_FURB122.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB122_FURB122.py.snap index 126ca055740d0..c2017c65d72bb 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB122_FURB122.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB122_FURB122.py.snap @@ -11,11 +11,9 @@ FURB122 [*] Use of `f.write` in a for loop | |_________________________^ help: Replace with `f.writelines` | -9 | with open("file", "w") as f: - - for line in lines: - - f.write(line) +10 - for line in lines: +11 - f.write(line) 10 + f.writelines(lines) -11 | | FURB122 [*] Use of `f.write` in a for loop @@ -28,11 +26,9 @@ FURB122 [*] Use of `f.write` in a for loop | |_______________________________^ help: Replace with `f.writelines` | -16 | with Path("file").open("w") as f: - - for line in lines: - - f.write(other_line) +17 - for line in lines: +18 - f.write(other_line) 17 + f.writelines(other_line for line in lines) -18 | | FURB122 [*] Use of `f.write` in a for loop @@ -45,11 +41,9 @@ FURB122 [*] Use of `f.write` in a for loop | |_________________________^ help: Replace with `f.writelines` | -22 | with Path("file").open("w") as f: - - for line in lines: - - f.write(line) +23 - for line in lines: +24 - f.write(line) 23 + f.writelines(lines) -24 | | FURB122 [*] Use of `f.write` in a for loop @@ -62,11 +56,9 @@ FURB122 [*] Use of `f.write` in a for loop | |__________________________________^ help: Replace with `f.writelines` | -28 | with Path("file").open("wb") as f: - - for line in lines: - - f.write(line.encode()) +29 - for line in lines: +30 - f.write(line.encode()) 29 + f.writelines(line.encode() for line in lines) -30 | | FURB122 [*] Use of `f.write` in a for loop @@ -79,11 +71,9 @@ FURB122 [*] Use of `f.write` in a for loop | |_________________________________^ help: Replace with `f.writelines` | -34 | with Path("file").open("w") as f: - - for line in lines: - - f.write(line.upper()) +35 - for line in lines: +36 - f.write(line.upper()) 35 + f.writelines(line.upper() for line in lines) -36 | | FURB122 [*] Use of `f.write` in a for loop @@ -96,11 +86,9 @@ FURB122 [*] Use of `f.write` in a for loop | |_________________________^ help: Replace with `f.writelines` | -42 | - - for line in lines: - - f.write(line) +43 - for line in lines: +44 - f.write(line) 43 + f.writelines(lines) -44 | | FURB122 [*] Use of `f.write` in a for loop @@ -114,12 +102,10 @@ FURB122 [*] Use of `f.write` in a for loop | |_________________________^ help: Replace with `f.writelines` | -49 | with open("file","w") as f: - - for line in lines: - - # a really important comment - - f.write(line) +50 - for line in lines: +51 - # a really important comment +52 - f.write(line) 50 + f.writelines(lines) -51 | | note: This is an unsafe fix and may change runtime behavior @@ -133,11 +119,9 @@ FURB122 [*] Use of `f.write` in a for loop | |_______________________^ help: Replace with `f.writelines` | -56 | with open("file", "w") as f: - - for () in a: - - f.write(()) +57 - for () in a: +58 - f.write(()) 57 + f.writelines(() for () in a) -58 | | FURB122 [*] Use of `f.write` in a for loop @@ -150,11 +134,9 @@ FURB122 [*] Use of `f.write` in a for loop | |___________________________^ help: Replace with `f.writelines` | -62 | with open("file", "w") as f: - - for a, b, c in d: - - f.write((a, b)) +63 - for a, b, c in d: +64 - f.write((a, b)) 63 + f.writelines((a, b) for a, b, c in d) -64 | | FURB122 [*] Use of `f.write` in a for loop @@ -167,11 +149,9 @@ FURB122 [*] Use of `f.write` in a for loop | |_______________________^ help: Replace with `f.writelines` | -68 | with open("file", "w") as f: - - for [(), [a.b], (c,)] in d: - - f.write(()) +69 - for [(), [a.b], (c,)] in d: +70 - f.write(()) 69 + f.writelines(() for [(), [a.b], (c,)] in d) -70 | | FURB122 [*] Use of `f.write` in a for loop @@ -184,11 +164,9 @@ FURB122 [*] Use of `f.write` in a for loop | |_______________________^ help: Replace with `f.writelines` | -74 | with open("file", "w") as f: - - for [([([a[b]],)],), [], (c[d],)] in e: - - f.write(()) +75 - for [([([a[b]],)],), [], (c[d],)] in e: +76 - f.write(()) 75 + f.writelines(() for [([([a[b]],)],), [], (c[d],)] in e) -76 | | FURB122 [*] Use of `f.write` in a for loop @@ -204,11 +182,9 @@ FURB122 [*] Use of `f.write` in a for loop | help: Replace with `f.writelines` | -81 | with open("file", "w") as f: - - for char in "a", "b": - - f.write(char) +82 - for char in "a", "b": +83 - f.write(char) 82 + f.writelines(("a", "b")) -83 | | FURB122 [*] Use of `f.write` in a for loop @@ -224,11 +200,9 @@ FURB122 [*] Use of `f.write` in a for loop | help: Replace with `f.writelines` | -87 | with open("file", "w") as f: - - for char in "a", "b": - - f.write(f"{char}") +88 - for char in "a", "b": +89 - f.write(f"{char}") 88 + f.writelines(f"{char}" for char in ("a", "b")) -89 | | FURB122 [*] Use of `f.write` in a for loop @@ -244,15 +218,10 @@ FURB122 [*] Use of `f.write` in a for loop | |______________________________^ help: Replace with `f.writelines` | -92 | with open("file", "w") as f: - - for char in ( -93 + f.writelines(f"{char}" for char in ( -94 | "a", # Comment -95 | "b" - - ): - - f.write(f"{char}") +93 ~ f.writelines(f"{char}" for char in ( +94 + "a", # Comment +95 + "b" 96 + )) -97 | | note: This is an unsafe fix and may change runtime behavior @@ -266,11 +235,9 @@ FURB122 [*] Use of `f.write` in a for loop | |_____________________________^ help: Replace with `f.writelines` | -182 | with Path("file.txt").open("w", encoding="utf-8") as f: - - for l in lambda: 0: - - f.write(f"[{l}]") +183 - for l in lambda: 0: +184 - f.write(f"[{l}]") 183 + f.writelines(f"[{l}]" for l in (lambda: 0)) -184 | | FURB122 [*] Use of `f.write` in a for loop @@ -283,11 +250,9 @@ FURB122 [*] Use of `f.write` in a for loop | |_____________________________^ help: Replace with `f.writelines` | -188 | with Path("file.txt").open("w", encoding="utf-8") as f: - - for l in (1,) if True else (2,): - - f.write(f"[{l}]") +189 - for l in (1,) if True else (2,): +190 - f.write(f"[{l}]") 189 + f.writelines(f"[{l}]" for l in ((1,) if True else (2,))) -190 | | FURB122 [*] Use of `f.write` in a for loop @@ -300,11 +265,9 @@ FURB122 [*] Use of `f.write` in a for loop | |_________________________^ help: Replace with `f.writelines` | -195 | with open("file", "w") as f: - - for line in lambda: 0: - - f.write(line) +196 - for line in lambda: 0: +197 - f.write(line) 196 + f.writelines(lambda: 0) -197 | | FURB122 [*] Use of `f.write` in a for loop @@ -317,11 +280,9 @@ FURB122 [*] Use of `f.write` in a for loop | |_________________________^ help: Replace with `f.writelines` | -201 | with open("file", "w") as f: - - for line in (1,) if True else (2,): - - f.write(line) +202 - for line in (1,) if True else (2,): +203 - f.write(line) 202 + f.writelines((1,) if True else (2,)) -203 | | FURB122 [*] Use of `f.write` in a for loop @@ -334,11 +295,9 @@ FURB122 [*] Use of `f.write` in a for loop | |______________________________^ help: Replace with `f.writelines` | -208 | with open("file", "w") as f: - - for line in (lambda: 0): - - f.write(f"{line}") +209 - for line in (lambda: 0): +210 - f.write(f"{line}") 209 + f.writelines(f"{line}" for line in (lambda: 0)) -210 | | FURB122 [*] Use of `f.write` in a for loop @@ -351,8 +310,7 @@ FURB122 [*] Use of `f.write` in a for loop | |______________________________^ help: Replace with `f.writelines` | -214 | with open("file", "w") as f: - - for line in ((1,) if True else (2,)): - - f.write(f"{line}") +215 - for line in ((1,) if True else (2,)): +216 - f.write(f"{line}") 215 + f.writelines(f"{line}" for line in ((1,) if True else (2,))) | diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB129_FURB129.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB129_FURB129.py.snap index 8adcea8b87a99..d28bb50a89973 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB129_FURB129.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB129_FURB129.py.snap @@ -13,10 +13,8 @@ FURB129 [*] Instead of calling `readlines()`, iterate over file object directly | help: Remove `readlines()` | -6 | with open("FURB129.py") as f: - - for _line in f.readlines(): +7 - for _line in f.readlines(): 7 + for _line in f: -8 | pass | FURB129 [*] Instead of calling `readlines()`, iterate over file object directly @@ -30,12 +28,10 @@ FURB129 [*] Instead of calling `readlines()`, iterate over file object directly 11 | c = {line.lower(): line.upper() for line in f.readlines()} | help: Remove `readlines()` - | -8 | pass - - a = [line.lower() for line in f.readlines()] -9 + a = [line.lower() for line in f] -10 | b = {line.upper() for line in f.readlines()} - | + | +9 - a = [line.lower() for line in f.readlines()] +9 + a = [line.lower() for line in f] + | FURB129 [*] Instead of calling `readlines()`, iterate over file object directly --> FURB129.py:10:35 @@ -48,10 +44,8 @@ FURB129 [*] Instead of calling `readlines()`, iterate over file object directly | help: Remove `readlines()` | -9 | a = [line.lower() for line in f.readlines()] - - b = {line.upper() for line in f.readlines()} +10 - b = {line.upper() for line in f.readlines()} 10 + b = {line.upper() for line in f} -11 | c = {line.lower(): line.upper() for line in f.readlines()} | FURB129 [*] Instead of calling `readlines()`, iterate over file object directly @@ -66,10 +60,8 @@ FURB129 [*] Instead of calling `readlines()`, iterate over file object directly | help: Remove `readlines()` | -10 | b = {line.upper() for line in f.readlines()} - - c = {line.lower(): line.upper() for line in f.readlines()} +11 - c = {line.lower(): line.upper() for line in f.readlines()} 11 + c = {line.lower(): line.upper() for line in f} -12 | | FURB129 [*] Instead of calling `readlines()`, iterate over file object directly @@ -82,10 +74,8 @@ FURB129 [*] Instead of calling `readlines()`, iterate over file object directly | help: Remove `readlines()` | -13 | with Path("FURB129.py").open() as f: - - for _line in f.readlines(): +14 - for _line in f.readlines(): 14 + for _line in f: -15 | pass | FURB129 [*] Instead of calling `readlines()`, iterate over file object directly @@ -99,10 +89,8 @@ FURB129 [*] Instead of calling `readlines()`, iterate over file object directly | help: Remove `readlines()` | -16 | - - for _line in open("FURB129.py").readlines(): +17 - for _line in open("FURB129.py").readlines(): 17 + for _line in open("FURB129.py"): -18 | pass | FURB129 [*] Instead of calling `readlines()`, iterate over file object directly @@ -116,10 +104,8 @@ FURB129 [*] Instead of calling `readlines()`, iterate over file object directly | help: Remove `readlines()` | -19 | - - for _line in Path("FURB129.py").open().readlines(): +20 - for _line in Path("FURB129.py").open().readlines(): 20 + for _line in Path("FURB129.py").open(): -21 | pass | FURB129 [*] Instead of calling `readlines()`, iterate over file object directly @@ -134,10 +120,8 @@ FURB129 [*] Instead of calling `readlines()`, iterate over file object directly | help: Remove `readlines()` | -25 | f = Path("FURB129.py").open() - - for _line in f.readlines(): +26 - for _line in f.readlines(): 26 + for _line in f: -27 | pass | FURB129 [*] Instead of calling `readlines()`, iterate over file object directly @@ -150,10 +134,8 @@ FURB129 [*] Instead of calling `readlines()`, iterate over file object directly | help: Remove `readlines()` | -31 | def func(f: io.BytesIO): - - for _line in f.readlines(): +32 - for _line in f.readlines(): 32 + for _line in f: -33 | pass | FURB129 [*] Instead of calling `readlines()`, iterate over file object directly @@ -168,10 +150,8 @@ FURB129 [*] Instead of calling `readlines()`, iterate over file object directly | help: Remove `readlines()` | -37 | with (open("FURB129.py") as f, foo as bar): - - for _line in f.readlines(): +38 - for _line in f.readlines(): 38 + for _line in f: -39 | pass | FURB129 [*] Instead of calling `readlines()`, iterate over file object directly @@ -184,10 +164,8 @@ FURB129 [*] Instead of calling `readlines()`, iterate over file object directly | help: Remove `readlines()` | -46 | with builtins.open("FURB129.py") as f: - - for line in f.readlines(): +47 - for line in f.readlines(): 47 + for line in f: -48 | pass | FURB129 [*] Instead of calling `readlines()`, iterate over file object directly @@ -200,10 +178,8 @@ FURB129 [*] Instead of calling `readlines()`, iterate over file object directly | help: Remove `readlines()` | -53 | with o("FURB129.py") as f: - - for line in f.readlines(): +54 - for line in f.readlines(): 54 + for line in f: -55 | pass | FURB129 [*] Instead of calling `readlines()`, iterate over file object directly @@ -217,10 +193,8 @@ FURB129 [*] Instead of calling `readlines()`, iterate over file object directly | help: Remove `readlines()` | -92 | with open("furb129.py") as f: - - for line in (f).readlines(): +93 - for line in (f).readlines(): 93 + for line in (f): -94 | pass | FURB129 [*] Instead of calling `readlines()`, iterate over file object directly @@ -231,10 +205,8 @@ FURB129 [*] Instead of calling `readlines()`, iterate over file object directly | ^^^^^^^^^^^^^^^ help: Remove `readlines()` | -96 | with open("furb129.py") as f: - - [line for line in (f).readlines()] +97 - [line for line in (f).readlines()] 97 + [line for line in (f)] -98 | | FURB129 [*] Instead of calling `readlines()`, iterate over file object directly @@ -248,10 +220,8 @@ FURB129 [*] Instead of calling `readlines()`, iterate over file object directly | help: Remove `readlines()` | -100 | with open("furb129.py") as f: - - for line in (((f))).readlines(): +101 - for line in (((f))).readlines(): 101 + for line in (((f))): -102 | pass | FURB129 [*] Instead of calling `readlines()`, iterate over file object directly @@ -265,10 +235,8 @@ FURB129 [*] Instead of calling `readlines()`, iterate over file object directly | help: Remove `readlines()` | -102 | pass - - for line in(f).readlines(): +103 - for line in(f).readlines(): 103 + for line in(f): -104 | pass | FURB129 [*] Instead of calling `readlines()`, iterate over file object directly @@ -282,10 +250,8 @@ FURB129 [*] Instead of calling `readlines()`, iterate over file object directly | help: Remove `readlines()` | -106 | # Test case for issue #17683 (missing space before keyword) - - print([line for line in f.readlines()if True]) +107 - print([line for line in f.readlines()if True]) 107 + print([line for line in f if True]) -108 | | FURB129 [*] Instead of calling `readlines()`, iterate over file object directly @@ -302,11 +268,9 @@ FURB129 [*] Instead of calling `readlines()`, iterate over file object directly | help: Remove `readlines()` | -111 | for line in ( # 1 - - fp. # 3 # 2 - - readlines( # 4 - - ) # 5 +112 - fp. # 3 # 2 +113 - readlines( # 4 +114 - ) # 5 112 + fp # 5 -113 | ): | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB131_FURB131.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB131_FURB131.py.snap index eed82175cc202..f4fd9b3d8f80e 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB131_FURB131.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB131_FURB131.py.snap @@ -9,10 +9,8 @@ FURB131 [*] Prefer `clear` over deleting a full slice | ^^^^^^^^^^^ help: Replace with `clear()` | -10 | # FURB131 - - del nums[:] +11 - del nums[:] 11 + nums.clear() -12 | | note: This is an unsafe fix and may change runtime behavior @@ -24,10 +22,8 @@ FURB131 [*] Prefer `clear` over deleting a full slice | ^^^^^^^^^^^^ help: Replace with `clear()` | -14 | # FURB131 - - del names[:] +15 - del names[:] 15 + names.clear() -16 | | note: This is an unsafe fix and may change runtime behavior @@ -56,10 +52,8 @@ FURB131 [*] Prefer `clear` over deleting a full slice | ^^^^^^^^ help: Replace with `clear()` | -27 | # FURB131 - - del x[:] +28 - del x[:] 28 + x.clear() -29 | | note: This is an unsafe fix and may change runtime behavior @@ -72,10 +66,8 @@ FURB131 [*] Prefer `clear` over deleting a full slice | ^^^^^^^^ help: Replace with `clear()` | -32 | # FURB131 - - del x[:] +33 - del x[:] 33 + x.clear() -34 | | note: This is an unsafe fix and may change runtime behavior @@ -88,10 +80,8 @@ FURB131 [*] Prefer `clear` over deleting a full slice | ^^^^^^^^ help: Replace with `clear()` | -37 | # FURB131 - - del x[:] +38 - del x[:] 38 + x.clear() -39 | | note: This is an unsafe fix and may change runtime behavior @@ -104,10 +94,8 @@ FURB131 [*] Prefer `clear` over deleting a full slice | ^^^^^^^^ help: Replace with `clear()` | -42 | # FURB131 - - del x[:] +43 - del x[:] 43 + x.clear() -44 | | note: This is an unsafe fix and may change runtime behavior @@ -123,10 +111,8 @@ FURB131 [*] Prefer `clear` over deleting a full slice | help: Replace with `clear()` | -47 | # FURB131 - - del x[:] +48 - del x[:] 48 + x.clear() -49 | | note: This is an unsafe fix and may change runtime behavior @@ -142,9 +128,7 @@ FURB131 [*] Prefer `clear` over deleting a full slice | help: Replace with `clear()` | -57 | # FURB131 - - del sneaky[:] +58 - del sneaky[:] 58 + sneaky.clear() -59 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB132_FURB132.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB132_FURB132.py.snap index e7e76f38b713b..a665a5365da87 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB132_FURB132.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB132_FURB132.py.snap @@ -10,11 +10,9 @@ FURB132 [*] Use `s.discard("x")` instead of check and `remove` | |_________________^ help: Replace with `s.discard("x")` | -11 | # FURB132 - - if "x" in s: - - s.remove("x") +12 - if "x" in s: +13 - s.remove("x") 12 + s.discard("x") -13 | | note: This is an unsafe fix and may change runtime behavior @@ -27,11 +25,9 @@ FURB132 [*] Use `s3.discard("x")` instead of check and `remove` | |__________________^ help: Replace with `s3.discard("x")` | -21 | # FURB132 - - if "x" in s3: - - s3.remove("x") +22 - if "x" in s3: +23 - s3.remove("x") 22 + s3.discard("x") -23 | | note: This is an unsafe fix and may change runtime behavior @@ -45,11 +41,9 @@ FURB132 [*] Use `s.discard(var)` instead of check and `remove` | |_________________^ help: Replace with `s.discard(var)` | -27 | # FURB132 - - if var in s: - - s.remove(var) +28 - if var in s: +29 - s.remove(var) 28 + s.discard(var) -29 | | note: This is an unsafe fix and may change runtime behavior @@ -61,10 +55,8 @@ FURB132 [*] Use `s.discard(f"{var}:{var}")` instead of check and `remove` | |____________________________^ help: Replace with `s.discard(f"{var}:{var}")` | -31 | - - if f"{var}:{var}" in s: - - s.remove(f"{var}:{var}") +32 - if f"{var}:{var}" in s: +33 - s.remove(f"{var}:{var}") 32 + s.discard(f"{var}:{var}") -33 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB136_FURB136.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB136_FURB136.py.snap index 64b885d1734a5..b78bad5f5402e 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB136_FURB136.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB136_FURB136.py.snap @@ -13,10 +13,8 @@ FURB136 [*] Replace `x if x > y else y` with `max(y, x)` | help: Replace with `max(y, x)` | -3 | - - x if x > y else y # FURB136 +4 - x if x > y else y # FURB136 4 + max(y, x) # FURB136 -5 | | FURB136 [*] Replace `x if x >= y else y` with `max(x, y)` @@ -31,10 +29,8 @@ FURB136 [*] Replace `x if x >= y else y` with `max(x, y)` | help: Replace with `max(x, y)` | -5 | - - x if x >= y else y # FURB136 +6 - x if x >= y else y # FURB136 6 + max(x, y) # FURB136 -7 | | FURB136 [*] Replace `x if x < y else y` with `min(y, x)` @@ -49,10 +45,8 @@ FURB136 [*] Replace `x if x < y else y` with `min(y, x)` | help: Replace with `min(y, x)` | -7 | - - x if x < y else y # FURB136 +8 - x if x < y else y # FURB136 8 + min(y, x) # FURB136 -9 | | FURB136 [*] Replace `x if x <= y else y` with `min(x, y)` @@ -67,10 +61,8 @@ FURB136 [*] Replace `x if x <= y else y` with `min(x, y)` | help: Replace with `min(x, y)` | -9 | - - x if x <= y else y # FURB136 +10 - x if x <= y else y # FURB136 10 + min(x, y) # FURB136 -11 | | FURB136 [*] Replace `y if x > y else x` with `min(x, y)` @@ -85,10 +77,8 @@ FURB136 [*] Replace `y if x > y else x` with `min(x, y)` | help: Replace with `min(x, y)` | -11 | - - y if x > y else x # FURB136 +12 - y if x > y else x # FURB136 12 + min(x, y) # FURB136 -13 | | FURB136 [*] Replace `y if x >= y else x` with `min(y, x)` @@ -103,10 +93,8 @@ FURB136 [*] Replace `y if x >= y else x` with `min(y, x)` | help: Replace with `min(y, x)` | -13 | - - y if x >= y else x # FURB136 +14 - y if x >= y else x # FURB136 14 + min(y, x) # FURB136 -15 | | FURB136 [*] Replace `y if x < y else x` with `max(x, y)` @@ -121,10 +109,8 @@ FURB136 [*] Replace `y if x < y else x` with `max(x, y)` | help: Replace with `max(x, y)` | -15 | - - y if x < y else x # FURB136 +16 - y if x < y else x # FURB136 16 + max(x, y) # FURB136 -17 | | FURB136 [*] Replace `y if x <= y else x` with `max(y, x)` @@ -139,10 +125,8 @@ FURB136 [*] Replace `y if x <= y else x` with `max(y, x)` | help: Replace with `max(y, x)` | -17 | - - y if x <= y else x # FURB136 +18 - y if x <= y else x # FURB136 18 + max(y, x) # FURB136 -19 | | FURB136 [*] Replace `if` expression with `max(y, x)` @@ -157,13 +141,11 @@ FURB136 [*] Replace `if` expression with `max(y, x)` | |________^ help: Replace with `max(y, x)` | -21 | - - x if ( - - x - - > y - - ) else y # FURB136 +22 - x if ( +23 - x +24 - > y +25 - ) else y # FURB136 22 + max(y, x) # FURB136 -23 | | FURB136 [*] Replace `if` expression with `max(y, x)` @@ -179,12 +161,10 @@ FURB136 [*] Replace `if` expression with `max(y, x)` | help: Replace with `max(y, x)` | -28 | highest_score = ( - - x - - # text - - if x > y - - else y +29 - x +30 - # text +31 - if x > y +32 - else y 29 + max(y, x) -30 | ) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB140_FURB140.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB140_FURB140.py.snap index 85c6cb9a1318a..1324ce5106f89 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB140_FURB140.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB140_FURB140.py.snap @@ -14,11 +14,10 @@ help: Replace with `itertools.starmap` | 1 + from itertools import starmap 2 | def zipped(): --------------------------------------------------------------------------------- +3 | return zip([1, 2, 3], "ABC") +… 7 | # FURB140 - - [print(x, y) for x, y in zipped()] 8 + list(starmap(print, zipped())) -9 | | FURB140 [*] Use `itertools.starmap` instead of the generator @@ -32,13 +31,12 @@ FURB140 [*] Use `itertools.starmap` instead of the generator | help: Replace with `itertools.starmap` | -1 + from itertools import starmap -2 | def zipped(): --------------------------------------------------------------------------------- + 1 + from itertools import starmap + 2 | def zipped(): + 3 | return zip([1, 2, 3], "ABC") + … 10 | # FURB140 - - (print(x, y) for x, y in zipped()) 11 + starmap(print, zipped()) -12 | | FURB140 [*] Use `itertools.starmap` instead of the generator @@ -49,13 +47,12 @@ FURB140 [*] Use `itertools.starmap` instead of the generator | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `itertools.starmap` | -1 + from itertools import starmap -2 | def zipped(): --------------------------------------------------------------------------------- + 1 + from itertools import starmap + 2 | def zipped(): + 3 | return zip([1, 2, 3], "ABC") + … 13 | # FURB140 - - {print(x, y) for x, y in zipped()} 14 + set(starmap(print, zipped())) -15 | | FURB140 [*] Use `itertools.starmap` instead of the generator @@ -69,10 +66,10 @@ FURB140 [*] Use `itertools.starmap` instead of the generator | help: Replace with `itertools.starmap` | +16 ~ from itertools import starmap as sm +17 | 18 | # FURB140 - - [print(x, y) for x, y in zipped()] 19 + list(sm(print, zipped())) -20 | | FURB140 [*] Use `itertools.starmap` instead of the generator @@ -86,10 +83,11 @@ FURB140 [*] Use `itertools.starmap` instead of the generator | help: Replace with `itertools.starmap` | +16 ~ from itertools import starmap as sm +17 | + … 21 | # FURB140 - - (print(x, y) for x, y in zipped()) 22 + sm(print, zipped()) -23 | | FURB140 [*] Use `itertools.starmap` instead of the generator @@ -103,10 +101,11 @@ FURB140 [*] Use `itertools.starmap` instead of the generator | help: Replace with `itertools.starmap` | +16 ~ from itertools import starmap as sm +17 | + … 24 | # FURB140 - - {print(x, y) for x, y in zipped()} 25 + set(sm(print, zipped())) -26 | | FURB140 [*] Use `itertools.starmap` instead of the generator @@ -121,10 +120,11 @@ FURB140 [*] Use `itertools.starmap` instead of the generator | help: Replace with `itertools.starmap` | +16 ~ from itertools import starmap as sm +17 | + … 28 | # See https://github.com/astral-sh/ruff/issues/7636 - - [foo(*t) for t in [(85, 60), (100, 80)]] 29 + list(sm(foo, [(85, 60), (100, 80)])) -30 | (foo(*t) for t in [(85, 60), (100, 80)]) | FURB140 [*] Use `itertools.starmap` instead of the generator @@ -138,10 +138,11 @@ FURB140 [*] Use `itertools.starmap` instead of the generator | help: Replace with `itertools.starmap` | +16 ~ from itertools import starmap as sm +17 | + … 29 | [foo(*t) for t in [(85, 60), (100, 80)]] - - (foo(*t) for t in [(85, 60), (100, 80)]) 30 + sm(foo, [(85, 60), (100, 80)]) -31 | {foo(*t) for t in [(85, 60), (100, 80)]} | FURB140 [*] Use `itertools.starmap` instead of the generator @@ -156,10 +157,11 @@ FURB140 [*] Use `itertools.starmap` instead of the generator | help: Replace with `itertools.starmap` | +16 ~ from itertools import starmap as sm +17 | + … 30 | (foo(*t) for t in [(85, 60), (100, 80)]) - - {foo(*t) for t in [(85, 60), (100, 80)]} 31 + set(sm(foo, [(85, 60), (100, 80)])) -32 | | FURB140 [*] Use `itertools.starmap` instead of the generator @@ -176,13 +178,10 @@ FURB140 [*] Use `itertools.starmap` instead of the generator | help: Replace with `itertools.starmap` | +16 ~ from itertools import starmap as sm +17 | + … 61 | all( - - predicate(a, b) - - # text - - for a, b - - # text - - in some_iterable -62 + sm(predicate, some_iterable) -63 | ) +62 ~ sm(predicate, some_iterable) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB142_FURB142.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB142_FURB142.py.snap index 3ed7c5780d55e..6ad76edbd9c6d 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB142_FURB142.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB142_FURB142.py.snap @@ -14,11 +14,9 @@ FURB142 [*] Use of `set.add()` in a for loop | help: Replace with `.update()` | -4 | - - for x in [1, 2, 3]: - - s.add(x) +5 - for x in [1, 2, 3]: +6 - s.add(x) 5 + s.update([1, 2, 3]) -6 | | FURB142 [*] Use of `set.add()` in a for loop @@ -34,11 +32,9 @@ FURB142 [*] Use of `set.add()` in a for loop | help: Replace with `.update()` | -7 | - - for x in {1, 2, 3}: - - s.add(x) +8 - for x in {1, 2, 3}: +9 - s.add(x) 8 + s.update({1, 2, 3}) -9 | | FURB142 [*] Use of `set.add()` in a for loop @@ -54,11 +50,9 @@ FURB142 [*] Use of `set.add()` in a for loop | help: Replace with `.update()` | -10 | - - for x in (1, 2, 3): - - s.add(x) +11 - for x in (1, 2, 3): +12 - s.add(x) 11 + s.update((1, 2, 3)) -12 | | FURB142 [*] Use of `set.discard()` in a for loop @@ -74,11 +68,9 @@ FURB142 [*] Use of `set.discard()` in a for loop | help: Replace with `.difference_update()` | -13 | - - for x in (1, 2, 3): - - s.discard(x) +14 - for x in (1, 2, 3): +15 - s.discard(x) 14 + s.difference_update((1, 2, 3)) -15 | | FURB142 [*] Use of `set.add()` in a for loop @@ -94,11 +86,9 @@ FURB142 [*] Use of `set.add()` in a for loop | help: Replace with `.update()` | -16 | - - for x in (1, 2, 3): - - s.add(x + 1) +17 - for x in (1, 2, 3): +18 - s.add(x + 1) 17 + s.update(x + 1 for x in (1, 2, 3)) -18 | | FURB142 [*] Use of `set.add()` in a for loop @@ -114,11 +104,9 @@ FURB142 [*] Use of `set.add()` in a for loop | help: Replace with `.update()` | -19 | - - for x, y in ((1, 2), (3, 4)): - - s.add((x, y)) +20 - for x, y in ((1, 2), (3, 4)): +21 - s.add((x, y)) 20 + s.update((x, y) for x, y in ((1, 2), (3, 4))) -21 | | FURB142 [*] Use of `set.add()` in a for loop @@ -134,11 +122,9 @@ FURB142 [*] Use of `set.add()` in a for loop | help: Replace with `.update()` | -24 | - - for x in (1, 2, 3): - - s.add(num) +25 - for x in (1, 2, 3): +26 - s.add(num) 25 + s.update(num for x in (1, 2, 3)) -26 | | FURB142 [*] Use of `set.add()` in a for loop @@ -154,11 +140,9 @@ FURB142 [*] Use of `set.add()` in a for loop | help: Replace with `.update()` | -27 | - - for x in (1, 2, 3): - - s.add((num, x)) +28 - for x in (1, 2, 3): +29 - s.add((num, x)) 28 + s.update((num, x) for x in (1, 2, 3)) -29 | | FURB142 [*] Use of `set.add()` in a for loop @@ -174,11 +158,9 @@ FURB142 [*] Use of `set.add()` in a for loop | help: Replace with `.update()` | -30 | - - for x in (1, 2, 3): - - s.add(x + num) +31 - for x in (1, 2, 3): +32 - s.add(x + num) 31 + s.update(x + num for x in (1, 2, 3)) -32 | | FURB142 [*] Use of `set.add()` in a for loop @@ -193,11 +175,9 @@ FURB142 [*] Use of `set.add()` in a for loop | help: Replace with `.update()` | -34 | # https://github.com/astral-sh/ruff/issues/15936 - - for x in 1, 2, 3: - - s.add(x) +35 - for x in 1, 2, 3: +36 - s.add(x) 35 + s.update((1, 2, 3)) -36 | | FURB142 [*] Use of `set.add()` in a for loop @@ -213,11 +193,9 @@ FURB142 [*] Use of `set.add()` in a for loop | help: Replace with `.update()` | -37 | - - for x in 1, 2, 3: - - s.add(f"{x}") +38 - for x in 1, 2, 3: +39 - s.add(f"{x}") 38 + s.update(f"{x}" for x in (1, 2, 3)) -39 | | FURB142 [*] Use of `set.add()` in a for loop @@ -233,15 +211,10 @@ FURB142 [*] Use of `set.add()` in a for loop | |_________________^ help: Replace with `.update()` | -40 | - - for x in ( 41 + s.update(f"{x}" for x in ( -42 | 1, # Comment -43 | 2, 3 - - ): - - s.add(f"{x}") +42 + 1, # Comment +43 + 2, 3 44 + )) -45 | | note: This is an unsafe fix and may change runtime behavior @@ -258,11 +231,9 @@ FURB142 [*] Use of `set.discard()` in a for loop | help: Replace with `.difference_update()` | -82 | - - for x in lambda: 0: - - s.discard(-x) +83 - for x in lambda: 0: +84 - s.discard(-x) 83 + s.difference_update(-x for x in (lambda: 0)) -84 | | FURB142 [*] Use of `set.add()` in a for loop @@ -278,11 +249,9 @@ FURB142 [*] Use of `set.add()` in a for loop | help: Replace with `.update()` | -85 | - - for x in (1,) if True else (2,): - - s.add(-x) +86 - for x in (1,) if True else (2,): +87 - s.add(-x) 86 + s.update(-x for x in ((1,) if True else (2,))) -87 | | FURB142 [*] Use of `set.discard()` in a for loop @@ -297,11 +266,9 @@ FURB142 [*] Use of `set.discard()` in a for loop | help: Replace with `.difference_update()` | -89 | # don't add extra parens - - for x in (lambda: 0): - - s.discard(-x) +90 - for x in (lambda: 0): +91 - s.discard(-x) 90 + s.difference_update(-x for x in (lambda: 0)) -91 | | FURB142 [*] Use of `set.add()` in a for loop @@ -317,11 +284,9 @@ FURB142 [*] Use of `set.add()` in a for loop | help: Replace with `.update()` | -92 | - - for x in ((1,) if True else (2,)): - - s.add(-x) +93 - for x in ((1,) if True else (2,)): +94 - s.add(-x) 93 + s.update(-x for x in ((1,) if True else (2,))) -94 | | FURB142 [*] Use of `set.discard()` in a for loop @@ -336,11 +301,9 @@ FURB142 [*] Use of `set.discard()` in a for loop | help: Replace with `.difference_update()` | -96 | # don't add parens directly in function call - - for x in lambda: 0: - - s.discard(x) +97 - for x in lambda: 0: +98 - s.discard(x) 97 + s.difference_update(lambda: 0) -98 | | FURB142 [*] Use of `set.add()` in a for loop @@ -356,11 +319,9 @@ FURB142 [*] Use of `set.add()` in a for loop | help: Replace with `.update()` | -99 | - - for x in (1,) if True else (2,): - - s.add(x) +100 - for x in (1,) if True else (2,): +101 - s.add(x) 100 + s.update((1,) if True else (2,)) -101 | | FURB142 [*] Use of `set.add()` in a for loop @@ -375,11 +336,9 @@ FURB142 [*] Use of `set.add()` in a for loop | help: Replace with `.update()` | -103 | # https://github.com/astral-sh/ruff/issues/21098 - - for x in ("abc", "def"): - - s.add(c for c in x) +104 - for x in ("abc", "def"): +105 - s.add(c for c in x) 104 + s.update((c for c in x) for x in ("abc", "def")) -105 | | FURB142 [*] Use of `set.add()` in a for loop @@ -391,8 +350,7 @@ FURB142 [*] Use of `set.add()` in a for loop | |_________________________^ help: Replace with `.update()` | -107 | # don't add extra parens for already parenthesized generators - - for x in ("abc", "def"): - - s.add((c for c in x)) +108 - for x in ("abc", "def"): +109 - s.add((c for c in x)) 108 + s.update((c for c in x) for x in ("abc", "def")) | diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB145_FURB145.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB145_FURB145.py.snap index e0386246b4b32..ca79958db204d 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB145_FURB145.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB145_FURB145.py.snap @@ -12,10 +12,8 @@ FURB145 [*] Prefer `copy` method over slicing | help: Replace with `copy()` | -3 | # Errors. - - a = l[:] +4 - a = l[:] 4 + a = l.copy() -5 | b, c = 1, l[:] | FURB145 [*] Prefer `copy` method over slicing @@ -30,10 +28,8 @@ FURB145 [*] Prefer `copy` method over slicing | help: Replace with `copy()` | -4 | a = l[:] - - b, c = 1, l[:] +5 - b, c = 1, l[:] 5 + b, c = 1, l.copy() -6 | d, e = l[:], 1 | FURB145 [*] Prefer `copy` method over slicing @@ -48,10 +44,8 @@ FURB145 [*] Prefer `copy` method over slicing | help: Replace with `copy()` | -5 | b, c = 1, l[:] - - d, e = l[:], 1 +6 - d, e = l[:], 1 6 + d, e = l.copy(), 1 -7 | m = l[::] | FURB145 [*] Prefer `copy` method over slicing @@ -66,10 +60,8 @@ FURB145 [*] Prefer `copy` method over slicing | help: Replace with `copy()` | -6 | d, e = l[:], 1 - - m = l[::] +7 - m = l[::] 7 + m = l.copy() -8 | l[:] | FURB145 [*] Prefer `copy` method over slicing @@ -83,10 +75,8 @@ FURB145 [*] Prefer `copy` method over slicing | help: Replace with `copy()` | -7 | m = l[::] - - l[:] +8 - l[:] 8 + l.copy() -9 | print(l[:]) | FURB145 [*] Prefer `copy` method over slicing @@ -100,12 +90,10 @@ FURB145 [*] Prefer `copy` method over slicing 11 | # False negatives. | help: Replace with `copy()` - | -8 | l[:] - - print(l[:]) -9 + print(l.copy()) -10 | - | + | +9 - print(l[:]) +9 + print(l.copy()) + | FURB145 [*] Prefer `copy` method over slicing --> FURB145.py:24:5 @@ -118,11 +106,10 @@ FURB145 [*] Prefer `copy` method over slicing | |_^ help: Replace with `copy()` | -23 | - - b = l[ - - # text - - : - - ] +24 - b = l[ +25 - # text +26 - : +27 - ] 24 + b = l.copy() | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB148_FURB148.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB148_FURB148.py.snap index 6213d7a4b7b7c..7ea3e3a6d3298 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB148_FURB148.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB148_FURB148.py.snap @@ -11,10 +11,8 @@ FURB148 [*] `enumerate` value is unused, use `for x in range(len(y))` instead | help: Replace with `range(len(...))` | -13 | # Errors - - for index, _ in enumerate(books): +14 - for index, _ in enumerate(books): 14 + for index in range(len(books)): -15 | print(index) | note: This is an unsafe fix and may change runtime behavior @@ -29,10 +27,8 @@ FURB148 [*] `enumerate` value is unused, use `for x in range(len(y))` instead | help: Replace with `range(len(...))` | -16 | - - for index, _ in enumerate(books, start=0): +17 - for index, _ in enumerate(books, start=0): 17 + for index in range(len(books)): -18 | print(index) | note: This is an unsafe fix and may change runtime behavior @@ -47,10 +43,8 @@ FURB148 [*] `enumerate` value is unused, use `for x in range(len(y))` instead | help: Replace with `range(len(...))` | -19 | - - for index, _ in enumerate(books, 0): +20 - for index, _ in enumerate(books, 0): 20 + for index in range(len(books)): -21 | print(index) | note: This is an unsafe fix and may change runtime behavior @@ -109,10 +103,8 @@ FURB148 [*] `enumerate` index is unused, use `for x in y` instead | help: Remove `enumerate` | -34 | - - for _, book in enumerate(books): +35 - for _, book in enumerate(books): 35 + for book in books: -36 | print(book) | note: This is an unsafe fix and may change runtime behavior @@ -127,10 +119,8 @@ FURB148 [*] `enumerate` index is unused, use `for x in y` instead | help: Remove `enumerate` | -37 | - - for _, book in enumerate(books, start=0): +38 - for _, book in enumerate(books, start=0): 38 + for book in books: -39 | print(book) | note: This is an unsafe fix and may change runtime behavior @@ -145,10 +135,8 @@ FURB148 [*] `enumerate` index is unused, use `for x in y` instead | help: Remove `enumerate` | -40 | - - for _, book in enumerate(books, 0): +41 - for _, book in enumerate(books, 0): 41 + for book in books: -42 | print(book) | note: This is an unsafe fix and may change runtime behavior @@ -163,10 +151,8 @@ FURB148 [*] `enumerate` index is unused, use `for x in y` instead | help: Remove `enumerate` | -43 | - - for _, book in enumerate(books, start=1): +44 - for _, book in enumerate(books, start=1): 44 + for book in books: -45 | print(book) | note: This is an unsafe fix and may change runtime behavior @@ -181,10 +167,8 @@ FURB148 [*] `enumerate` index is unused, use `for x in y` instead | help: Remove `enumerate` | -46 | - - for _, book in enumerate(books, 1): +47 - for _, book in enumerate(books, 1): 47 + for book in books: -48 | print(book) | note: This is an unsafe fix and may change runtime behavior @@ -199,10 +183,8 @@ FURB148 [*] `enumerate` index is unused, use `for x in y` instead | help: Remove `enumerate` | -49 | - - for _, book in enumerate(books, start=x): +50 - for _, book in enumerate(books, start=x): 50 + for book in books: -51 | print(book) | note: This is an unsafe fix and may change runtime behavior @@ -217,10 +199,8 @@ FURB148 [*] `enumerate` index is unused, use `for x in y` instead | help: Remove `enumerate` | -52 | - - for _, book in enumerate(books, x): +53 - for _, book in enumerate(books, x): 53 + for book in books: -54 | print(book) | note: This is an unsafe fix and may change runtime behavior @@ -235,10 +215,8 @@ FURB148 [*] `enumerate` value is unused, use `for x in range(len(y))` instead | help: Replace with `range(len(...))` | -55 | - - for index, (_, _) in enumerate(books): +56 - for index, (_, _) in enumerate(books): 56 + for index in range(len(books)): -57 | print(index) | note: This is an unsafe fix and may change runtime behavior @@ -253,10 +231,8 @@ FURB148 [*] `enumerate` index is unused, use `for x in y` instead | help: Remove `enumerate` | -58 | - - for (_, _), book in enumerate(books): +59 - for (_, _), book in enumerate(books): 59 + for book in books: -60 | print(book) | note: This is an unsafe fix and may change runtime behavior @@ -271,10 +247,8 @@ FURB148 [*] `enumerate` value is unused, use `for x in range(len(y))` instead | help: Replace with `range(len(...))` | -61 | - - for(index, _)in enumerate(books): +62 - for(index, _)in enumerate(books): 62 + for index in range(len(books)): -63 | print(index) | note: This is an unsafe fix and may change runtime behavior @@ -289,10 +263,8 @@ FURB148 [*] `enumerate` value is unused, use `for x in range(len(y))` instead | help: Replace with `range(len(...))` | -64 | - - for(index), _ in enumerate(books): +65 - for(index), _ in enumerate(books): 65 + for index in range(len(books)): -66 | print(index) | note: This is an unsafe fix and may change runtime behavior @@ -307,10 +279,8 @@ FURB148 [*] `enumerate` value is unused, use `for x in range(len(y))` instead | help: Replace with `range(len(...))` | -67 | - - for index, _ in enumerate(books_and_authors): +68 - for index, _ in enumerate(books_and_authors): 68 + for index in range(len(books_and_authors)): -69 | print(index) | note: This is an unsafe fix and may change runtime behavior @@ -325,10 +295,8 @@ FURB148 [*] `enumerate` index is unused, use `for x in y` instead | help: Remove `enumerate` | -70 | - - for _, book in enumerate(books_and_authors): +71 - for _, book in enumerate(books_and_authors): 71 + for book in books_and_authors: -72 | print(book) | note: This is an unsafe fix and may change runtime behavior @@ -343,10 +311,8 @@ FURB148 [*] `enumerate` value is unused, use `for x in range(len(y))` instead | help: Replace with `range(len(...))` | -73 | - - for index, _ in enumerate(books_set): +74 - for index, _ in enumerate(books_set): 74 + for index in range(len(books_set)): -75 | print(index) | note: This is an unsafe fix and may change runtime behavior @@ -361,10 +327,8 @@ FURB148 [*] `enumerate` index is unused, use `for x in y` instead | help: Remove `enumerate` | -76 | - - for _, book in enumerate(books_set): +77 - for _, book in enumerate(books_set): 77 + for book in books_set: -78 | print(book) | note: This is an unsafe fix and may change runtime behavior @@ -379,10 +343,8 @@ FURB148 [*] `enumerate` value is unused, use `for x in range(len(y))` instead | help: Replace with `range(len(...))` | -79 | - - for index, _ in enumerate(books_tuple): +80 - for index, _ in enumerate(books_tuple): 80 + for index in range(len(books_tuple)): -81 | print(index) | note: This is an unsafe fix and may change runtime behavior @@ -397,9 +359,7 @@ FURB148 [*] `enumerate` index is unused, use `for x in y` instead | help: Remove `enumerate` | -82 | - - for _, book in enumerate(books_tuple): +83 - for _, book in enumerate(books_tuple): 83 + for book in books_tuple: -84 | print(book) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB152_FURB152.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB152_FURB152.py.snap index e8285f3b8929c..a88d2fb0cfbd0 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB152_FURB152.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB152_FURB152.py.snap @@ -16,9 +16,7 @@ help: Use `math.pi` 1 + import math 2 | r = 3.1 # OK 3 | - - A = 3.14 * r ** 2 # FURB152 -4 + A = math.pi * r ** 2 # FURB152 -5 | +4 ~ A = math.pi * r ** 2 # FURB152 | FURB152 [*] Replace `6.28` with `math.tau` @@ -38,9 +36,7 @@ help: Use `math.tau` 3 | 4 | A = 3.14 * r ** 2 # FURB152 5 | - - C = 6.28 * r # FURB152 -6 + C = math.tau * r # FURB152 -7 | +6 ~ C = math.tau * r # FURB152 | FURB152 [*] Replace `2.71` with `math.e` @@ -57,11 +53,10 @@ help: Use `math.e` | 1 + import math 2 | r = 3.1 # OK --------------------------------------------------------------------------------- +3 | +… 7 | - - e = 2.71 # FURB152 -8 + e = math.e # FURB152 -9 | +8 ~ e = math.e # FURB152 | FURB152 [*] Replace `3.141` with `math.pi` @@ -76,13 +71,12 @@ FURB152 [*] Replace `3.141` with `math.pi` | help: Use `math.pi` | -1 + import math -2 | r = 3.1 # OK --------------------------------------------------------------------------------- + 1 + import math + 2 | r = 3.1 # OK + 3 | + … 11 | - - r = 3.141 # FURB152 -12 + r = math.pi # FURB152 -13 | +12 ~ r = math.pi # FURB152 | FURB152 [*] Replace `3.142` with `math.pi` @@ -97,13 +91,12 @@ FURB152 [*] Replace `3.142` with `math.pi` | help: Use `math.pi` | -1 + import math -2 | r = 3.1 # OK --------------------------------------------------------------------------------- + 1 + import math + 2 | r = 3.1 # OK + 3 | + … 13 | - - r = 3.142 # FURB152 -14 + r = math.pi # FURB152 -15 | +14 ~ r = math.pi # FURB152 | FURB152 [*] Replace `3.1415` with `math.pi` @@ -118,13 +111,12 @@ FURB152 [*] Replace `3.1415` with `math.pi` | help: Use `math.pi` | -1 + import math -2 | r = 3.1 # OK --------------------------------------------------------------------------------- + 1 + import math + 2 | r = 3.1 # OK + 3 | + … 15 | - - r = 3.1415 # FURB152 -16 + r = math.pi # FURB152 -17 | +16 ~ r = math.pi # FURB152 | FURB152 [*] Replace `3.1416` with `math.pi` @@ -139,13 +131,12 @@ FURB152 [*] Replace `3.1416` with `math.pi` | help: Use `math.pi` | -1 + import math -2 | r = 3.1 # OK --------------------------------------------------------------------------------- + 1 + import math + 2 | r = 3.1 # OK + 3 | + … 17 | - - r = 3.1416 # FURB152 -18 + r = math.pi # FURB152 -19 | +18 ~ r = math.pi # FURB152 | FURB152 [*] Replace `3.141592` with `math.pi` @@ -160,13 +151,12 @@ FURB152 [*] Replace `3.141592` with `math.pi` | help: Use `math.pi` | -1 + import math -2 | r = 3.1 # OK --------------------------------------------------------------------------------- + 1 + import math + 2 | r = 3.1 # OK + 3 | + … 19 | - - r = 3.141592 # FURB152 -20 + r = math.pi # FURB152 -21 | +20 ~ r = math.pi # FURB152 | FURB152 [*] Replace `3.141593` with `math.pi` @@ -181,13 +171,12 @@ FURB152 [*] Replace `3.141593` with `math.pi` | help: Use `math.pi` | -1 + import math -2 | r = 3.1 # OK --------------------------------------------------------------------------------- + 1 + import math + 2 | r = 3.1 # OK + 3 | + … 21 | - - r = 3.141593 # FURB152 -22 + r = math.pi # FURB152 -23 | +22 ~ r = math.pi # FURB152 | FURB152 [*] Replace `3.14159265` with `math.pi` @@ -202,13 +191,12 @@ FURB152 [*] Replace `3.14159265` with `math.pi` | help: Use `math.pi` | -1 + import math -2 | r = 3.1 # OK --------------------------------------------------------------------------------- + 1 + import math + 2 | r = 3.1 # OK + 3 | + … 23 | - - r = 3.14159265 # FURB152 -24 + r = math.pi # FURB152 -25 | +24 ~ r = math.pi # FURB152 | FURB152 [*] Replace `3.141592653589793238462643383279` with `math.pi` @@ -223,13 +211,12 @@ FURB152 [*] Replace `3.141592653589793238462643383279` with `math.pi` | help: Use `math.pi` | -1 + import math -2 | r = 3.1 # OK --------------------------------------------------------------------------------- + 1 + import math + 2 | r = 3.1 # OK + 3 | + … 25 | - - r = 3.141592653589793238462643383279 # FURB152 -26 + r = math.pi # FURB152 -27 | +26 ~ r = math.pi # FURB152 | FURB152 [*] Replace `2.718` with `math.e` @@ -244,13 +231,12 @@ FURB152 [*] Replace `2.718` with `math.e` | help: Use `math.e` | -1 + import math -2 | r = 3.1 # OK --------------------------------------------------------------------------------- + 1 + import math + 2 | r = 3.1 # OK + 3 | + … 31 | - - e = 2.718 # FURB152 -32 + e = math.e # FURB152 -33 | +32 ~ e = math.e # FURB152 | FURB152 [*] Replace `2.7182` with `math.e` @@ -265,13 +251,12 @@ FURB152 [*] Replace `2.7182` with `math.e` | help: Use `math.e` | -1 + import math -2 | r = 3.1 # OK --------------------------------------------------------------------------------- + 1 + import math + 2 | r = 3.1 # OK + 3 | + … 33 | - - e = 2.7182 # FURB152 -34 + e = math.e # FURB152 -35 | +34 ~ e = math.e # FURB152 | FURB152 [*] Replace `2.7183` with `math.e` @@ -286,13 +271,12 @@ FURB152 [*] Replace `2.7183` with `math.e` | help: Use `math.e` | -1 + import math -2 | r = 3.1 # OK --------------------------------------------------------------------------------- + 1 + import math + 2 | r = 3.1 # OK + 3 | + … 35 | - - e = 2.7183 # FURB152 -36 + e = math.e # FURB152 -37 | +36 ~ e = math.e # FURB152 | FURB152 [*] Replace `2.7182000000000001` with `math.e` @@ -304,10 +288,10 @@ FURB152 [*] Replace `2.7182000000000001` with `math.e` | ^^^^^^^^^^^^^^^^^^ help: Use `math.e` | -1 + import math -2 | r = 3.1 # OK --------------------------------------------------------------------------------- + 1 + import math + 2 | r = 3.1 # OK + 3 | + … 45 | - - e = 2.7182000000000001 # FURB152 -46 + e = math.e # FURB152 +46 ~ e = math.e # FURB152 | diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB154_FURB154.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB154_FURB154.py.snap index 61de91d4684a5..fba919c66dbca 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB154_FURB154.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB154_FURB154.py.snap @@ -10,11 +10,9 @@ FURB154 [*] Use of repeated consecutive `global` | |____________^ help: Merge `global` statements | -3 | def f1(): - - global x - - global y +4 - global x +5 - global y 4 + global x, y -5 | | FURB154 [*] Use of repeated consecutive `global` @@ -27,12 +25,10 @@ FURB154 [*] Use of repeated consecutive `global` | |____________^ help: Merge `global` statements | -8 | def f3(): - - global x - - global y - - global z -9 + global x, y, z -10 | + 9 - global x +10 - global y +11 - global z + 9 + global x, y, z | FURB154 [*] Use of repeated consecutive `global` @@ -47,11 +43,9 @@ FURB154 [*] Use of repeated consecutive `global` | help: Merge `global` statements | -14 | def f4(): - - global x - - global y +15 - global x +16 - global y 15 + global x, y -16 | pass | FURB154 [*] Use of repeated consecutive `global` @@ -64,11 +58,9 @@ FURB154 [*] Use of repeated consecutive `global` | |____________^ help: Merge `global` statements | -17 | pass - - global x - - global y +18 - global x +19 - global y 18 + global x, y -19 | | FURB154 [*] Use of repeated consecutive `nonlocal` @@ -83,11 +75,9 @@ FURB154 [*] Use of repeated consecutive `nonlocal` | help: Merge `nonlocal` statements | -25 | def inner(): - - nonlocal x - - nonlocal y +26 - nonlocal x +27 - nonlocal y 26 + nonlocal x, y -27 | | FURB154 [*] Use of repeated consecutive `nonlocal` @@ -103,12 +93,10 @@ FURB154 [*] Use of repeated consecutive `nonlocal` | help: Merge `nonlocal` statements | -29 | def inner2(): - - nonlocal x - - nonlocal y - - nonlocal z +30 - nonlocal x +31 - nonlocal y +32 - nonlocal z 30 + nonlocal x, y, z -31 | | FURB154 [*] Use of repeated consecutive `nonlocal` @@ -123,11 +111,9 @@ FURB154 [*] Use of repeated consecutive `nonlocal` | help: Merge `nonlocal` statements | -34 | def inner3(): - - nonlocal x - - nonlocal y +35 - nonlocal x +36 - nonlocal y 35 + nonlocal x, y -36 | pass | FURB154 [*] Use of repeated consecutive `nonlocal` @@ -140,11 +126,9 @@ FURB154 [*] Use of repeated consecutive `nonlocal` | |__________________^ help: Merge `nonlocal` statements | -37 | pass - - nonlocal x - - nonlocal y +38 - nonlocal x +39 - nonlocal y 38 + nonlocal x, y -39 | | FURB154 [*] Use of repeated consecutive `global` @@ -159,11 +143,9 @@ FURB154 [*] Use of repeated consecutive `global` | help: Merge `global` statements | -45 | def inner(): - - global w - - global x +46 - global w +47 - global x 46 + global w, x -47 | nonlocal y | FURB154 [*] Use of repeated consecutive `nonlocal` @@ -179,11 +161,9 @@ FURB154 [*] Use of repeated consecutive `nonlocal` | help: Merge `nonlocal` statements | -47 | global x - - nonlocal y - - nonlocal z +48 - nonlocal y +49 - nonlocal z 48 + nonlocal y, z -49 | | FURB154 [*] Use of repeated consecutive `nonlocal` @@ -196,11 +176,9 @@ FURB154 [*] Use of repeated consecutive `nonlocal` | |__________________^ help: Merge `nonlocal` statements | -52 | global x - - nonlocal y - - nonlocal z +53 - nonlocal y +54 - nonlocal z 53 + nonlocal y, z -54 | | FURB154 [*] Use of repeated consecutive `global` @@ -213,12 +191,10 @@ FURB154 [*] Use of repeated consecutive `global` | |__________________^ help: Merge `global` statements | -57 | def f6(): - - global x, y, z - - global a, b, c - - global d, e, f +58 - global x, y, z +59 - global a, b, c +60 - global d, e, f 58 + global x, y, z, a, b, c, d, e, f -59 | | FURB154 [*] Use of repeated consecutive `global` @@ -234,11 +210,9 @@ FURB154 [*] Use of repeated consecutive `global` | help: Merge `global` statements | -89 | def func(): - - global x - - # text - - global y +90 - global x +91 - # text +92 - global y 90 + global x, y -91 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB156_FURB156.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB156_FURB156.py.snap index dff625195a6a2..0c2a3eb871bac 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB156_FURB156.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB156_FURB156.py.snap @@ -13,11 +13,8 @@ FURB156 [*] Use of hardcoded string charset | help: Replace hardcoded charset with `string.digits` | -2 | - - _ = "0123456789" 3 + import string -4 + _ = string.digits -5 | _ = "01234567" +4 ~ _ = string.digits | FURB156 [*] Use of hardcoded string charset @@ -31,12 +28,9 @@ FURB156 [*] Use of hardcoded string charset | help: Replace hardcoded charset with `string.octdigits` | -2 | 3 + import string 4 | _ = "0123456789" - - _ = "01234567" -5 + _ = string.octdigits -6 | _ = "0123456789abcdefABCDEF" +5 ~ _ = string.octdigits | FURB156 [*] Use of hardcoded string charset @@ -51,13 +45,10 @@ FURB156 [*] Use of hardcoded string charset | help: Replace hardcoded charset with `string.hexdigits` | -2 | 3 + import string 4 | _ = "0123456789" 5 | _ = "01234567" - - _ = "0123456789abcdefABCDEF" -6 + _ = string.hexdigits -7 | _ = "abcdefghijklmnopqrstuvwxyz" +6 ~ _ = string.hexdigits | FURB156 [*] Use of hardcoded string charset @@ -72,14 +63,11 @@ FURB156 [*] Use of hardcoded string charset | help: Replace hardcoded charset with `string.ascii_lowercase` | -2 | 3 + import string 4 | _ = "0123456789" 5 | _ = "01234567" 6 | _ = "0123456789abcdefABCDEF" - - _ = "abcdefghijklmnopqrstuvwxyz" -7 + _ = string.ascii_lowercase -8 | _ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +7 ~ _ = string.ascii_lowercase | FURB156 [*] Use of hardcoded string charset @@ -94,15 +82,12 @@ FURB156 [*] Use of hardcoded string charset | help: Replace hardcoded charset with `string.ascii_uppercase` | -2 | 3 + import string 4 | _ = "0123456789" 5 | _ = "01234567" 6 | _ = "0123456789abcdefABCDEF" 7 | _ = "abcdefghijklmnopqrstuvwxyz" - - _ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" -8 + _ = string.ascii_uppercase -9 | _ = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" +8 ~ _ = string.ascii_uppercase | FURB156 [*] Use of hardcoded string charset @@ -116,16 +101,14 @@ FURB156 [*] Use of hardcoded string charset 10 | _ = " \t\n\r\v\f" | help: Replace hardcoded charset with `string.ascii_letters` - | -2 | -3 + import string -4 | _ = "0123456789" --------------------------------------------------------------------------------- -8 | _ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - - _ = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" -9 + _ = string.ascii_letters -10 | _ = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""" - | + | +3 + import string +4 | _ = "0123456789" +5 | _ = "01234567" +… +8 | _ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +9 ~ _ = string.ascii_letters + | FURB156 [*] Use of hardcoded string charset --> FURB156.py:9:5 @@ -138,14 +121,12 @@ FURB156 [*] Use of hardcoded string charset | help: Replace hardcoded charset with `string.punctuation` | -2 | -3 + import string -4 | _ = "0123456789" --------------------------------------------------------------------------------- -9 | _ = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" - - _ = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""" -10 + _ = string.punctuation -11 | _ = " \t\n\r\v\f" + 3 + import string + 4 | _ = "0123456789" + 5 | _ = "01234567" + … + 9 | _ = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" +10 ~ _ = string.punctuation | FURB156 [*] Use of hardcoded string charset @@ -160,14 +141,12 @@ FURB156 [*] Use of hardcoded string charset | help: Replace hardcoded charset with `string.whitespace` | -2 | -3 + import string -4 | _ = "0123456789" --------------------------------------------------------------------------------- + 3 + import string + 4 | _ = "0123456789" + 5 | _ = "01234567" + … 10 | _ = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""" - - _ = " \t\n\r\v\f" -11 + _ = string.whitespace -12 | +11 ~ _ = string.whitespace | FURB156 [*] Use of hardcoded string charset @@ -182,14 +161,12 @@ FURB156 [*] Use of hardcoded string charset | help: Replace hardcoded charset with `string.printable` | -2 | -3 + import string -4 | _ = "0123456789" --------------------------------------------------------------------------------- + 3 + import string + 4 | _ = "0123456789" + 5 | _ = "01234567" + … 12 | - - _ = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' -13 + _ = string.printable -14 | _ = ( +13 ~ _ = string.printable | FURB156 [*] Use of hardcoded string charset @@ -205,15 +182,12 @@ FURB156 [*] Use of hardcoded string charset | help: Replace hardcoded charset with `string.printable` | -2 | -3 + import string -4 | _ = "0123456789" --------------------------------------------------------------------------------- + 3 + import string + 4 | _ = "0123456789" + 5 | _ = "01234567" + … 14 | _ = ( - - '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&' - - "'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c" -15 + string.printable -16 | ) +15 ~ string.printable | FURB156 [*] Use of hardcoded string charset @@ -231,16 +205,12 @@ FURB156 [*] Use of hardcoded string charset | help: Replace hardcoded charset with `string.digits` | -2 | -3 + import string -4 | _ = "0123456789" --------------------------------------------------------------------------------- + 3 + import string + 4 | _ = "0123456789" + 5 | _ = "01234567" + … 17 | ) - - _ = id("0123" - - "4567" - - "89") -18 + _ = id(string.digits) -19 | +18 ~ _ = id(string.digits) | FURB156 [*] Use of hardcoded string charset @@ -253,14 +223,12 @@ FURB156 [*] Use of hardcoded string charset | help: Replace hardcoded charset with `string.digits` | -2 | -3 + import string -4 | _ = "0123456789" --------------------------------------------------------------------------------- + 3 + import string + 4 | _ = "0123456789" + 5 | _ = "01234567" + … 22 | _ = ( - - "0123456789" -23 + string.digits -24 | ).capitalize() +23 ~ string.digits | FURB156 [*] Use of hardcoded string charset @@ -274,14 +242,12 @@ FURB156 [*] Use of hardcoded string charset | help: Replace hardcoded charset with `string.digits` | -2 | -3 + import string -4 | _ = "0123456789" --------------------------------------------------------------------------------- + 3 + import string + 4 | _ = "0123456789" + 5 | _ = "01234567" + … 26 | _ = ( - - "0123456789" -27 + string.digits -28 | # with comment +27 ~ string.digits | FURB156 [*] Use of hardcoded string charset @@ -295,12 +261,10 @@ FURB156 [*] Use of hardcoded string charset | help: Replace hardcoded charset with `string.digits` | -2 | -3 + import string -4 | _ = "0123456789" --------------------------------------------------------------------------------- + 3 + import string + 4 | _ = "0123456789" + 5 | _ = "01234567" + … 31 | # example with augmented assignment - - _ += "0123456789" -32 + _ += string.digits -33 | +32 ~ _ += string.digits | diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB157_FURB157.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB157_FURB157.py.snap index b23d38312d5fd..30a80f6231456 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB157_FURB157.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB157_FURB157.py.snap @@ -12,10 +12,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `0` | -4 | # Errors - - Decimal("0") +5 - Decimal("0") 5 + Decimal(0) -6 | Decimal("-42") | FURB157 [*] Verbose expression in `Decimal` constructor @@ -30,10 +28,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `-42` | -5 | Decimal("0") - - Decimal("-42") +6 - Decimal("-42") 6 + Decimal(-42) -7 | Decimal(float("Infinity")) | FURB157 [*] Verbose expression in `Decimal` constructor @@ -48,10 +44,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `"Infinity"` | -6 | Decimal("-42") - - Decimal(float("Infinity")) +7 - Decimal(float("Infinity")) 7 + Decimal("Infinity") -8 | Decimal(float("-Infinity")) | FURB157 [*] Verbose expression in `Decimal` constructor @@ -66,10 +60,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `"-Infinity"` | -7 | Decimal(float("Infinity")) - - Decimal(float("-Infinity")) +8 - Decimal(float("-Infinity")) 8 + Decimal("-Infinity") -9 | Decimal(float("inf")) | FURB157 [*] Verbose expression in `Decimal` constructor @@ -83,12 +75,10 @@ FURB157 [*] Verbose expression in `Decimal` constructor 11 | Decimal(float("nan")) | help: Replace with `"inf"` - | -8 | Decimal(float("-Infinity")) - - Decimal(float("inf")) -9 + Decimal("inf") -10 | Decimal(float("-inf")) - | + | +9 - Decimal(float("inf")) +9 + Decimal("inf") + | FURB157 [*] Verbose expression in `Decimal` constructor --> FURB157.py:10:9 @@ -102,10 +92,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `"-inf"` | -9 | Decimal(float("inf")) - - Decimal(float("-inf")) +10 - Decimal(float("-inf")) 10 + Decimal("-inf") -11 | Decimal(float("nan")) | FURB157 [*] Verbose expression in `Decimal` constructor @@ -119,10 +107,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `"nan"` | -10 | Decimal(float("-inf")) - - Decimal(float("nan")) +11 - Decimal(float("nan")) 11 + Decimal("nan") -12 | decimal.Decimal("0") | FURB157 [*] Verbose expression in `Decimal` constructor @@ -137,10 +123,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `0` | -11 | Decimal(float("nan")) - - decimal.Decimal("0") +12 - decimal.Decimal("0") 12 + decimal.Decimal(0) -13 | | FURB157 [*] Verbose expression in `Decimal` constructor @@ -153,10 +137,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `1_000` | -22 | # Errors - - Decimal("1_000") +23 - Decimal("1_000") 23 + Decimal(1_000) -24 | Decimal("__1____000") | FURB157 [*] Verbose expression in `Decimal` constructor @@ -171,10 +153,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `1_000` | -23 | Decimal("1_000") - - Decimal("__1____000") +24 - Decimal("__1____000") 24 + Decimal(1_000) -25 | | FURB157 [*] Verbose expression in `Decimal` constructor @@ -189,10 +169,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `" nan "` | -47 | # https://github.com/astral-sh/ruff/issues/14587 - - Decimal(float(" nan ")) # Decimal(" nan ") +48 - Decimal(float(" nan ")) # Decimal(" nan ") 48 + Decimal(" nan ") # Decimal(" nan ") -49 | Decimal(float(" +nan ")) # Decimal(" +nan ") | FURB157 [*] Verbose expression in `Decimal` constructor @@ -207,10 +185,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `" +nan "` | -48 | Decimal(float(" nan ")) # Decimal(" nan ") - - Decimal(float(" +nan ")) # Decimal(" +nan ") +49 - Decimal(float(" +nan ")) # Decimal(" +nan ") 49 + Decimal(" +nan ") # Decimal(" +nan ") -50 | # In this one case, " -nan ", the fix has to be | FURB157 [*] Verbose expression in `Decimal` constructor @@ -225,10 +201,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `"nan"` | -51 | # `Decimal(" nan ")`` because `Decimal("-nan") != Decimal(float("-nan"))` - - Decimal(float(" -nan ")) # Decimal("nan") +52 - Decimal(float(" -nan ")) # Decimal("nan") 52 + Decimal("nan") # Decimal("nan") -53 | Decimal(float(" inf ")) # Decimal(" inf ") | FURB157 [*] Verbose expression in `Decimal` constructor @@ -243,10 +217,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `" inf "` | -52 | Decimal(float(" -nan ")) # Decimal("nan") - - Decimal(float(" inf ")) # Decimal(" inf ") +53 - Decimal(float(" inf ")) # Decimal(" inf ") 53 + Decimal(" inf ") # Decimal(" inf ") -54 | Decimal(float(" +inf ")) # Decimal(" +inf ") | FURB157 [*] Verbose expression in `Decimal` constructor @@ -261,10 +233,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `" +inf "` | -53 | Decimal(float(" inf ")) # Decimal(" inf ") - - Decimal(float(" +inf ")) # Decimal(" +inf ") +54 - Decimal(float(" +inf ")) # Decimal(" +inf ") 54 + Decimal(" +inf ") # Decimal(" +inf ") -55 | Decimal(float(" -inf ")) # Decimal(" -inf ") | FURB157 [*] Verbose expression in `Decimal` constructor @@ -279,10 +249,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `" -inf "` | -54 | Decimal(float(" +inf ")) # Decimal(" +inf ") - - Decimal(float(" -inf ")) # Decimal(" -inf ") +55 - Decimal(float(" -inf ")) # Decimal(" -inf ") 55 + Decimal(" -inf ") # Decimal(" -inf ") -56 | Decimal(float(" infinity ")) # Decimal(" infinity ") | FURB157 [*] Verbose expression in `Decimal` constructor @@ -297,10 +265,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `" infinity "` | -55 | Decimal(float(" -inf ")) # Decimal(" -inf ") - - Decimal(float(" infinity ")) # Decimal(" infinity ") +56 - Decimal(float(" infinity ")) # Decimal(" infinity ") 56 + Decimal(" infinity ") # Decimal(" infinity ") -57 | Decimal(float(" +infinity ")) # Decimal(" +infinity ") | FURB157 [*] Verbose expression in `Decimal` constructor @@ -314,10 +280,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `" +infinity "` | -56 | Decimal(float(" infinity ")) # Decimal(" infinity ") - - Decimal(float(" +infinity ")) # Decimal(" +infinity ") +57 - Decimal(float(" +infinity ")) # Decimal(" +infinity ") 57 + Decimal(" +infinity ") # Decimal(" +infinity ") -58 | Decimal(float(" -infinity ")) # Decimal(" -infinity ") | FURB157 [*] Verbose expression in `Decimal` constructor @@ -332,10 +296,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `" -infinity "` | -57 | Decimal(float(" +infinity ")) # Decimal(" +infinity ") - - Decimal(float(" -infinity ")) # Decimal(" -infinity ") +58 - Decimal(float(" -infinity ")) # Decimal(" -infinity ") 58 + Decimal(" -infinity ") # Decimal(" -infinity ") -59 | | FURB157 [*] Verbose expression in `Decimal` constructor @@ -350,10 +312,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `"nan"` | -63 | # https://github.com/astral-sh/ruff/issues/16771 - - Decimal(float("\x2dnan")) +64 - Decimal(float("\x2dnan")) 64 + Decimal("nan") -65 | Decimal(float("\x20\x2dnan")) | FURB157 [*] Verbose expression in `Decimal` constructor @@ -368,10 +328,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `"nan"` | -64 | Decimal(float("\x2dnan")) - - Decimal(float("\x20\x2dnan")) +65 - Decimal(float("\x20\x2dnan")) 65 + Decimal("nan") -66 | Decimal(float("\x20\u002dnan")) | FURB157 [*] Verbose expression in `Decimal` constructor @@ -386,10 +344,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `"nan"` | -65 | Decimal(float("\x20\x2dnan")) - - Decimal(float("\x20\u002dnan")) +66 - Decimal(float("\x20\u002dnan")) 66 + Decimal("nan") -67 | Decimal(float("\x20\U0000002dnan")) | FURB157 [*] Verbose expression in `Decimal` constructor @@ -404,10 +360,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `"nan"` | -66 | Decimal(float("\x20\u002dnan")) - - Decimal(float("\x20\U0000002dnan")) +67 - Decimal(float("\x20\U0000002dnan")) 67 + Decimal("nan") -68 | Decimal(float("\N{space}\N{hyPHen-MINus}nan")) | FURB157 [*] Verbose expression in `Decimal` constructor @@ -422,10 +376,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `"nan"` | -67 | Decimal(float("\x20\U0000002dnan")) - - Decimal(float("\N{space}\N{hyPHen-MINus}nan")) +68 - Decimal(float("\N{space}\N{hyPHen-MINus}nan")) 68 + Decimal("nan") -69 | Decimal(float("\x20\N{character tabulation}\N{hyphen-minus}nan")) | FURB157 [*] Verbose expression in `Decimal` constructor @@ -440,10 +392,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `"nan"` | -68 | Decimal(float("\N{space}\N{hyPHen-MINus}nan")) - - Decimal(float("\x20\N{character tabulation}\N{hyphen-minus}nan")) +69 - Decimal(float("\x20\N{character tabulation}\N{hyphen-minus}nan")) 69 + Decimal("nan") -70 | Decimal(float(" -" "nan")) | FURB157 [*] Verbose expression in `Decimal` constructor @@ -457,10 +407,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `"nan"` | -69 | Decimal(float("\x20\N{character tabulation}\N{hyphen-minus}nan")) - - Decimal(float(" -" "nan")) +70 - Decimal(float(" -" "nan")) 70 + Decimal("nan") -71 | Decimal(float("-nAn")) | FURB157 [*] Verbose expression in `Decimal` constructor @@ -475,10 +423,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `"nan"` | -70 | Decimal(float(" -" "nan")) - - Decimal(float("-nAn")) +71 - Decimal(float("-nAn")) 71 + Decimal("nan") -72 | | FURB157 [*] Verbose expression in `Decimal` constructor @@ -493,10 +439,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `15_000_000` | -74 | # https://github.com/astral-sh/ruff/issues/20572 - - Decimal("15_000_000") # Safe fix: normalizes separators, becomes Decimal(15_000_000) +75 - Decimal("15_000_000") # Safe fix: normalizes separators, becomes Decimal(15_000_000) 75 + Decimal(15_000_000) # Safe fix: normalizes separators, becomes Decimal(15_000_000) -76 | Decimal("1_234_567") # Safe fix: normalizes separators, becomes Decimal(1_234_567) | FURB157 [*] Verbose expression in `Decimal` constructor @@ -511,10 +455,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `1_234_567` | -75 | Decimal("15_000_000") # Safe fix: normalizes separators, becomes Decimal(15_000_000) - - Decimal("1_234_567") # Safe fix: normalizes separators, becomes Decimal(1_234_567) +76 - Decimal("1_234_567") # Safe fix: normalizes separators, becomes Decimal(1_234_567) 76 + Decimal(1_234_567) # Safe fix: normalizes separators, becomes Decimal(1_234_567) -77 | Decimal("-5_000") # Safe fix: normalizes separators, becomes Decimal(-5_000) | FURB157 [*] Verbose expression in `Decimal` constructor @@ -528,10 +470,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `-5_000` | -76 | Decimal("1_234_567") # Safe fix: normalizes separators, becomes Decimal(1_234_567) - - Decimal("-5_000") # Safe fix: normalizes separators, becomes Decimal(-5_000) +77 - Decimal("-5_000") # Safe fix: normalizes separators, becomes Decimal(-5_000) 77 + Decimal(-5_000) # Safe fix: normalizes separators, becomes Decimal(-5_000) -78 | Decimal("+9_999") # Safe fix: normalizes separators, becomes Decimal(+9_999) | FURB157 [*] Verbose expression in `Decimal` constructor @@ -546,10 +486,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `+9_999` | -77 | Decimal("-5_000") # Safe fix: normalizes separators, becomes Decimal(-5_000) - - Decimal("+9_999") # Safe fix: normalizes separators, becomes Decimal(+9_999) +78 - Decimal("+9_999") # Safe fix: normalizes separators, becomes Decimal(+9_999) 78 + Decimal(+9_999) # Safe fix: normalizes separators, becomes Decimal(+9_999) -79 | | FURB157 [*] Verbose expression in `Decimal` constructor @@ -562,10 +500,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `12_34_56_78` | -80 | # Test cases for non-thousands separators - - Decimal("12_34_56_78") # Safe fix: preserves non-thousands separators +81 - Decimal("12_34_56_78") # Safe fix: preserves non-thousands separators 81 + Decimal(12_34_56_78) # Safe fix: preserves non-thousands separators -82 | Decimal("1234_5678") # Safe fix: preserves non-thousands separators | FURB157 [*] Verbose expression in `Decimal` constructor @@ -580,10 +516,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `1234_5678` | -81 | Decimal("12_34_56_78") # Safe fix: preserves non-thousands separators - - Decimal("1234_5678") # Safe fix: preserves non-thousands separators +82 - Decimal("1234_5678") # Safe fix: preserves non-thousands separators 82 + Decimal(1234_5678) # Safe fix: preserves non-thousands separators -83 | | FURB157 [*] Verbose expression in `Decimal` constructor @@ -597,10 +531,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `1_2345` | -84 | # Separators _and_ leading zeros - - Decimal("0001_2345") +85 - Decimal("0001_2345") 85 + Decimal(1_2345) -86 | Decimal("000_1_2345") | FURB157 [*] Verbose expression in `Decimal` constructor @@ -614,10 +546,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `1_2345` | -85 | Decimal("0001_2345") - - Decimal("000_1_2345") +86 - Decimal("000_1_2345") 86 + Decimal(1_2345) -87 | Decimal("000_000") | FURB157 [*] Verbose expression in `Decimal` constructor @@ -632,10 +562,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `0` | -86 | Decimal("000_1_2345") - - Decimal("000_000") +87 - Decimal("000_000") 87 + Decimal(0) -88 | | FURB157 [*] Verbose expression in `Decimal` constructor @@ -650,10 +578,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `-1` | -90 | # https://github.com/astral-sh/ruff/issues/21186 - - Decimal("_-1") # Should flag as verbose +91 - Decimal("_-1") # Should flag as verbose 91 + Decimal(-1) # Should flag as verbose -92 | Decimal("_+1") # Should flag as verbose | FURB157 [*] Verbose expression in `Decimal` constructor @@ -667,10 +593,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | help: Replace with `+1` | -91 | Decimal("_-1") # Should flag as verbose - - Decimal("_+1") # Should flag as verbose +92 - Decimal("_+1") # Should flag as verbose 92 + Decimal(+1) # Should flag as verbose -93 | Decimal("_-1_000") # Should flag as verbose | FURB157 [*] Verbose expression in `Decimal` constructor @@ -682,10 +606,8 @@ FURB157 [*] Verbose expression in `Decimal` constructor | ^^^^^^^^^ help: Replace with `-1_000` | -92 | Decimal("_+1") # Should flag as verbose - - Decimal("_-1_000") # Should flag as verbose +93 - Decimal("_-1_000") # Should flag as verbose 93 + Decimal(-1_000) # Should flag as verbose -94 | | FURB157 [*] Verbose expression in `Decimal` constructor @@ -700,13 +622,11 @@ FURB157 [*] Verbose expression in `Decimal` constructor 101 | ) | help: Replace with `"Infinity"` - | -96 | Decimal( - - float( - - # text - - "Infinity" - - ) -97 + "Infinity" -98 | ) - | + | + 97 - float( + 98 - # text + 99 - "Infinity" +100 - ) + 97 + "Infinity" + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB161_FURB161.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB161_FURB161.py.snap index 8695fec7f5f9e..fa38bb3006fd7 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB161_FURB161.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB161_FURB161.py.snap @@ -13,10 +13,8 @@ FURB161 [*] Use of `bin(x).count('1')` | help: Replace with `(x).bit_count()` | -5 | - - count = bin(x).count("1") # FURB161 +6 - count = bin(x).count("1") # FURB161 6 + count = (x).bit_count() # FURB161 -7 | count = bin(10).count("1") # FURB161 | note: This is an unsafe fix and may change runtime behavior @@ -31,10 +29,8 @@ FURB161 [*] Use of `bin(10).count('1')` | help: Replace with `(10).bit_count()` | -6 | count = bin(x).count("1") # FURB161 - - count = bin(10).count("1") # FURB161 +7 - count = bin(10).count("1") # FURB161 7 + count = (10).bit_count() # FURB161 -8 | count = bin(0b1010).count("1") # FURB161 | FURB161 [*] Use of `bin(0b1010).count('1')` @@ -49,10 +45,8 @@ FURB161 [*] Use of `bin(0b1010).count('1')` | help: Replace with `0b1010.bit_count()` | -7 | count = bin(10).count("1") # FURB161 - - count = bin(0b1010).count("1") # FURB161 +8 - count = bin(0b1010).count("1") # FURB161 8 + count = 0b1010.bit_count() # FURB161 -9 | count = bin(0xA).count("1") # FURB161 | FURB161 [*] Use of `bin(0xA).count('1')` @@ -66,12 +60,10 @@ FURB161 [*] Use of `bin(0xA).count('1')` 11 | count = bin(0x10 + 0x1000).count("1") # FURB161 | help: Replace with `0xA.bit_count()` - | -8 | count = bin(0b1010).count("1") # FURB161 - - count = bin(0xA).count("1") # FURB161 -9 + count = 0xA.bit_count() # FURB161 -10 | count = bin(0o12).count("1") # FURB161 - | + | +9 - count = bin(0xA).count("1") # FURB161 +9 + count = 0xA.bit_count() # FURB161 + | FURB161 [*] Use of `bin(0o12).count('1')` --> FURB161.py:10:9 @@ -85,10 +77,8 @@ FURB161 [*] Use of `bin(0o12).count('1')` | help: Replace with `0o12.bit_count()` | -9 | count = bin(0xA).count("1") # FURB161 - - count = bin(0o12).count("1") # FURB161 +10 - count = bin(0o12).count("1") # FURB161 10 + count = 0o12.bit_count() # FURB161 -11 | count = bin(0x10 + 0x1000).count("1") # FURB161 | FURB161 [*] Use of `bin(0x10 + 0x1000).count('1')` @@ -103,10 +93,8 @@ FURB161 [*] Use of `bin(0x10 + 0x1000).count('1')` | help: Replace with `(0x10 + 0x1000).bit_count()` | -10 | count = bin(0o12).count("1") # FURB161 - - count = bin(0x10 + 0x1000).count("1") # FURB161 +11 - count = bin(0x10 + 0x1000).count("1") # FURB161 11 + count = (0x10 + 0x1000).bit_count() # FURB161 -12 | count = bin(ten()).count("1") # FURB161 | FURB161 [*] Use of `bin(ten()).count('1')` @@ -121,10 +109,8 @@ FURB161 [*] Use of `bin(ten()).count('1')` | help: Replace with `ten().bit_count()` | -11 | count = bin(0x10 + 0x1000).count("1") # FURB161 - - count = bin(ten()).count("1") # FURB161 +12 - count = bin(ten()).count("1") # FURB161 12 + count = ten().bit_count() # FURB161 -13 | count = bin((10)).count("1") # FURB161 | note: This is an unsafe fix and may change runtime behavior @@ -140,10 +126,8 @@ FURB161 [*] Use of `bin(10).count('1')` | help: Replace with `(10).bit_count()` | -12 | count = bin(ten()).count("1") # FURB161 - - count = bin((10)).count("1") # FURB161 +13 - count = bin((10)).count("1") # FURB161 13 + count = (10).bit_count() # FURB161 -14 | count = bin("10" "15").count("1") # FURB161 | FURB161 [*] Use of `bin("10" "15").count('1')` @@ -157,10 +141,8 @@ FURB161 [*] Use of `bin("10" "15").count('1')` | help: Replace with `("10" "15").bit_count()` | -13 | count = bin((10)).count("1") # FURB161 - - count = bin("10" "15").count("1") # FURB161 +14 - count = bin("10" "15").count("1") # FURB161 14 + count = ("10" "15").bit_count() # FURB161 -15 | count = bin("123").count("1") # FURB161 | note: This is an unsafe fix and may change runtime behavior @@ -176,9 +158,7 @@ FURB161 [*] Use of `bin("123").count('1')` | help: Replace with `"123".bit_count()` | -14 | count = bin("10" "15").count("1") # FURB161 - - count = bin("123").count("1") # FURB161 +15 - count = bin("123").count("1") # FURB161 15 + count = "123".bit_count() # FURB161 -16 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB162_FURB162.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB162_FURB162.py.snap index 4b040a8bb3a99..b538ae23f4163 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB162_FURB162.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB162_FURB162.py.snap @@ -12,10 +12,8 @@ FURB162 [*] Unnecessary timezone replacement with zero offset | help: Remove `.replace()` call | -7 | - - datetime.fromisoformat(date.replace("Z", "+00:00")) +8 - datetime.fromisoformat(date.replace("Z", "+00:00")) 8 + datetime.fromisoformat(date) -9 | datetime.fromisoformat(date.replace("Z", "-00:" "00")) | note: This is an unsafe fix and may change runtime behavior @@ -29,12 +27,10 @@ FURB162 [*] Unnecessary timezone replacement with zero offset 11 | datetime.fromisoformat(date[:-1] + "-00") | help: Remove `.replace()` call - | -8 | datetime.fromisoformat(date.replace("Z", "+00:00")) - - datetime.fromisoformat(date.replace("Z", "-00:" "00")) -9 + datetime.fromisoformat(date) -10 | - | + | +9 - datetime.fromisoformat(date.replace("Z", "-00:" "00")) +9 + datetime.fromisoformat(date) + | note: This is an unsafe fix and may change runtime behavior FURB162 [*] Unnecessary timezone replacement with zero offset @@ -48,10 +44,8 @@ FURB162 [*] Unnecessary timezone replacement with zero offset | help: Remove `.replace()` call | -10 | - - datetime.fromisoformat(date[:-1] + "-00") +11 - datetime.fromisoformat(date[:-1] + "-00") 11 + datetime.fromisoformat(date) -12 | datetime.fromisoformat(date[:-1:] + "-0000") | note: This is an unsafe fix and may change runtime behavior @@ -66,10 +60,8 @@ FURB162 [*] Unnecessary timezone replacement with zero offset | help: Remove `.replace()` call | -11 | datetime.fromisoformat(date[:-1] + "-00") - - datetime.fromisoformat(date[:-1:] + "-0000") +12 - datetime.fromisoformat(date[:-1:] + "-0000") 12 + datetime.fromisoformat(date) -13 | | note: This is an unsafe fix and may change runtime behavior @@ -86,11 +78,9 @@ FURB162 [*] Unnecessary timezone replacement with zero offset | help: Remove `.replace()` call | -13 | - - datetime.fromisoformat(date.strip("Z") + """+0""" - - """0""") +14 - datetime.fromisoformat(date.strip("Z") + """+0""" +15 - """0""") 14 + datetime.fromisoformat(date) -15 | datetime.fromisoformat(date.rstrip("Z") + "+\x30\60" '\u0030\N{DIGIT ZERO}') | note: This is an unsafe fix and may change runtime behavior @@ -106,10 +96,8 @@ FURB162 [*] Unnecessary timezone replacement with zero offset | help: Remove `.replace()` call | -15 | """0""") - - datetime.fromisoformat(date.rstrip("Z") + "+\x30\60" '\u0030\N{DIGIT ZERO}') +16 - datetime.fromisoformat(date.rstrip("Z") + "+\x30\60" '\u0030\N{DIGIT ZERO}') 16 + datetime.fromisoformat(date) -17 | | note: This is an unsafe fix and may change runtime behavior @@ -126,10 +114,8 @@ FURB162 [*] Unnecessary timezone replacement with zero offset | help: Remove `.replace()` call | -21 | date - - ).replace("Z", "+00") +22 - ).replace("Z", "+00") 22 + ) -23 | ) | note: This is an unsafe fix and may change runtime behavior @@ -149,14 +135,12 @@ FURB162 [*] Unnecessary timezone replacement with zero offset | help: Remove `.replace()` call | -27 | # Preserved - - ) - - . - - rstrip("Z" - - # Unsafe - - ) + "-00" # Preserved +28 - ) +29 - . +30 - rstrip("Z" +31 - # Unsafe +32 - ) + "-00" # Preserved 28 + ) # Preserved -29 | ) | note: This is an unsafe fix and may change runtime behavior @@ -172,10 +156,8 @@ FURB162 [*] Unnecessary timezone replacement with zero offset | help: Remove `.replace()` call | -37 | date - - ).strip("Z") + "+0000" +38 - ).strip("Z") + "+0000" 38 + ) -39 | ) | note: This is an unsafe fix and may change runtime behavior @@ -194,11 +176,11 @@ FURB162 [*] Unnecessary timezone replacement with zero offset | help: Remove `.replace()` call | -44 | ) - - [ # Unsafe - - :-1 - - ] + "-00" -45 | ) +44 - ) +45 - [ # Unsafe +46 - :-1 +47 - ] + "-00" +44 + ) | note: This is an unsafe fix and may change runtime behavior @@ -210,9 +192,7 @@ FURB162 [*] Unnecessary timezone replacement with zero offset | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove `.replace()` call | -51 | # Edge case - - datetime.fromisoformat("Z2025-01-01T00:00:00Z".strip("Z") + "+00:00") +52 - datetime.fromisoformat("Z2025-01-01T00:00:00Z".strip("Z") + "+00:00") 52 + datetime.fromisoformat("Z2025-01-01T00:00:00Z") -53 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB163_FURB163.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB163_FURB163.py.snap index 05dc04cac272b..14de41b183f7b 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB163_FURB163.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB163_FURB163.py.snap @@ -12,10 +12,10 @@ FURB163 [*] Prefer `math.log2(1)` over `math.log` with a redundant base | help: Replace with `math.log2(1)` | +1 ~ import math +2 | 3 | # Errors - - math.log(1, 2) 4 + math.log2(1) -5 | math.log(1, 10) | note: This is an unsafe fix and may change runtime behavior @@ -31,10 +31,11 @@ FURB163 [*] Prefer `math.log10(1)` over `math.log` with a redundant base | help: Replace with `math.log10(1)` | +1 ~ import math +2 | +3 | # Errors 4 | math.log(1, 2) - - math.log(1, 10) 5 + math.log10(1) -6 | math.log(1, math.e) | note: This is an unsafe fix and may change runtime behavior @@ -50,10 +51,11 @@ FURB163 [*] Prefer `math.log(1)` over `math.log` with a redundant base | help: Replace with `math.log(1)` | +1 ~ import math +2 | +… 5 | math.log(1, 10) - - math.log(1, math.e) 6 + math.log(1) -7 | foo = ... | FURB163 [*] Prefer `math.log2(foo)` over `math.log` with a redundant base @@ -68,10 +70,11 @@ FURB163 [*] Prefer `math.log2(foo)` over `math.log` with a redundant base | help: Replace with `math.log2(foo)` | +1 ~ import math +2 | +… 7 | foo = ... - - math.log(foo, 2) 8 + math.log2(foo) -9 | math.log(foo, 10) | note: This is an unsafe fix and may change runtime behavior @@ -86,12 +89,13 @@ FURB163 [*] Prefer `math.log10(foo)` over `math.log` with a redundant base 11 | math.log(1, 2.0) | help: Replace with `math.log10(foo)` - | -8 | math.log(foo, 2) - - math.log(foo, 10) -9 + math.log10(foo) -10 | math.log(foo, math.e) - | + | +1 ~ import math +2 | +… +8 | math.log(foo, 2) +9 + math.log10(foo) + | note: This is an unsafe fix and may change runtime behavior FURB163 [*] Prefer `math.log(foo)` over `math.log` with a redundant base @@ -106,10 +110,11 @@ FURB163 [*] Prefer `math.log(foo)` over `math.log` with a redundant base | help: Replace with `math.log(foo)` | -9 | math.log(foo, 10) - - math.log(foo, math.e) + 1 ~ import math + 2 | + … + 9 | math.log(foo, 10) 10 + math.log(foo) -11 | math.log(1, 2.0) | FURB163 [*] Prefer `math.log2(1)` over `math.log` with a redundant base @@ -123,10 +128,11 @@ FURB163 [*] Prefer `math.log2(1)` over `math.log` with a redundant base | help: Replace with `math.log2(1)` | + 1 ~ import math + 2 | + … 10 | math.log(foo, math.e) - - math.log(1, 2.0) 11 + math.log2(1) -12 | math.log(1, 10.0) | note: This is an unsafe fix and may change runtime behavior @@ -142,10 +148,11 @@ FURB163 [*] Prefer `math.log10(1)` over `math.log` with a redundant base | help: Replace with `math.log10(1)` | + 1 ~ import math + 2 | + … 11 | math.log(1, 2.0) - - math.log(1, 10.0) 12 + math.log10(1) -13 | | note: This is an unsafe fix and may change runtime behavior @@ -158,10 +165,11 @@ FURB163 [*] Prefer `math.log(yield)` over `math.log` with a redundant base | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `math.log(yield)` | + 1 ~ import math + 2 | + … 48 | def log(): - - yield math.log((yield), math.e) -49 + yield math.log((yield)) -50 | +49 ~ yield math.log((yield)) | FURB163 [*] Prefer `math.log(yield from x)` over `math.log` with a redundant base @@ -175,10 +183,11 @@ FURB163 [*] Prefer `math.log(yield from x)` over `math.log` with a redundant bas | help: Replace with `math.log(yield from x)` | + 1 ~ import math + 2 | + … 52 | def log(): - - yield math.log((yield from x), math.e) -53 + yield math.log((yield from x)) -54 | +53 ~ yield math.log((yield from x)) | FURB163 [*] Prefer `math.log10(1)` over `math.log` with a redundant base @@ -193,11 +202,11 @@ FURB163 [*] Prefer `math.log10(1)` over `math.log` with a redundant base | help: Replace with `math.log10(1)` | + 1 ~ import math + 2 | + … 55 | # see: https://github.com/astral-sh/ruff/issues/18639 - - math.log(1, 10 # comment - - ) 56 + math.log10(1) -57 | | note: This is an unsafe fix and may change runtime behavior @@ -215,12 +224,11 @@ FURB163 [*] Prefer `math.log10(1)` over `math.log` with a redundant base | help: Replace with `math.log10(1)` | + 1 ~ import math + 2 | + … 58 | - - math.log(1, - - 10 # comment - - ) 59 + math.log10(1) -60 | | note: This is an unsafe fix and may change runtime behavior @@ -239,13 +247,11 @@ FURB163 [*] Prefer `math.log10(1)` over `math.log` with a redundant base | help: Replace with `math.log10(1)` | + 1 ~ import math + 2 | + … 62 | - - math.log(1 # comment - - , # comment - - 10 # comment - - ) 63 + math.log10(1) -64 | | note: This is an unsafe fix and may change runtime behavior @@ -265,14 +271,11 @@ FURB163 [*] Prefer `math.log10(1)` over `math.log` with a redundant base | help: Replace with `math.log10(1)` | + 1 ~ import math + 2 | + … 67 | - - math.log( - - 1 # comment - - , - - 10 # comment - - ) 68 + math.log10(1) -69 | | note: This is an unsafe fix and may change runtime behavior @@ -287,10 +290,11 @@ FURB163 [*] Prefer `math.log2(4.13e223)` over `math.log` with a redundant base | help: Replace with `math.log2(4.13e223)` | + 1 ~ import math + 2 | + … 73 | - - math.log(4.13e223, 2) 74 + math.log2(4.13e223) -75 | math.log(4.14e223, 10) | note: This is an unsafe fix and may change runtime behavior @@ -302,10 +306,11 @@ FURB163 [*] Prefer `math.log10(4.14e223)` over `math.log` with a redundant base | ^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `math.log10(4.14e223)` | + 1 ~ import math + 2 | + … 74 | math.log(4.13e223, 2) - - math.log(4.14e223, 10) 75 + math.log10(4.14e223) -76 | | note: This is an unsafe fix and may change runtime behavior @@ -321,9 +326,10 @@ FURB163 [*] Prefer `math.log(*args)` over `math.log` with a redundant base | help: Replace with `math.log(*args)` | + 1 ~ import math + 2 | + … 79 | try: - - print(math.log(*args, math.e)) -80 + print(math.log(*args)) -81 | except TypeError as e: +80 ~ print(math.log(*args)) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB164_FURB164.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB164_FURB164.py.snap index 12431abb9bb72..279514981b703 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB164_FURB164.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB164_FURB164.py.snap @@ -12,10 +12,8 @@ FURB164 [*] Verbose method `from_float` in `Fraction` construction | help: Replace with `Fraction` constructor | -6 | # Errors - - _ = Fraction.from_float(0.1) +7 - _ = Fraction.from_float(0.1) 7 + _ = Fraction(0.1) -8 | _ = Fraction.from_float(-0.5) | FURB164 [*] Verbose method `from_float` in `Fraction` construction @@ -30,10 +28,8 @@ FURB164 [*] Verbose method `from_float` in `Fraction` construction | help: Replace with `Fraction` constructor | -7 | _ = Fraction.from_float(0.1) - - _ = Fraction.from_float(-0.5) +8 - _ = Fraction.from_float(-0.5) 8 + _ = Fraction(-0.5) -9 | _ = Fraction.from_float(5.0) | FURB164 [*] Verbose method `from_float` in `Fraction` construction @@ -47,12 +43,10 @@ FURB164 [*] Verbose method `from_float` in `Fraction` construction 11 | _ = Fraction.from_decimal(Decimal("4.2")) | help: Replace with `Fraction` constructor - | -8 | _ = Fraction.from_float(-0.5) - - _ = Fraction.from_float(5.0) -9 + _ = Fraction(5.0) -10 | _ = fractions.Fraction.from_float(4.2) - | + | +9 - _ = Fraction.from_float(5.0) +9 + _ = Fraction(5.0) + | FURB164 [*] Verbose method `from_float` in `Fraction` construction --> FURB164.py:10:5 @@ -66,10 +60,8 @@ FURB164 [*] Verbose method `from_float` in `Fraction` construction | help: Replace with `Fraction` constructor | -9 | _ = Fraction.from_float(5.0) - - _ = fractions.Fraction.from_float(4.2) +10 - _ = fractions.Fraction.from_float(4.2) 10 + _ = fractions.Fraction(4.2) -11 | _ = Fraction.from_decimal(Decimal("4.2")) | FURB164 [*] Verbose method `from_decimal` in `Fraction` construction @@ -84,10 +76,8 @@ FURB164 [*] Verbose method `from_decimal` in `Fraction` construction | help: Replace with `Fraction` constructor | -10 | _ = fractions.Fraction.from_float(4.2) - - _ = Fraction.from_decimal(Decimal("4.2")) +11 - _ = Fraction.from_decimal(Decimal("4.2")) 11 + _ = Fraction(Decimal("4.2")) -12 | _ = Fraction.from_decimal(Decimal("-4.2")) | FURB164 [*] Verbose method `from_decimal` in `Fraction` construction @@ -102,10 +92,8 @@ FURB164 [*] Verbose method `from_decimal` in `Fraction` construction | help: Replace with `Fraction` constructor | -11 | _ = Fraction.from_decimal(Decimal("4.2")) - - _ = Fraction.from_decimal(Decimal("-4.2")) +12 - _ = Fraction.from_decimal(Decimal("-4.2")) 12 + _ = Fraction(Decimal("-4.2")) -13 | _ = Fraction.from_decimal(Decimal.from_float(4.2)) | FURB164 [*] Verbose method `from_decimal` in `Fraction` construction @@ -120,10 +108,8 @@ FURB164 [*] Verbose method `from_decimal` in `Fraction` construction | help: Replace with `Fraction` constructor | -12 | _ = Fraction.from_decimal(Decimal("-4.2")) - - _ = Fraction.from_decimal(Decimal.from_float(4.2)) +13 - _ = Fraction.from_decimal(Decimal.from_float(4.2)) 13 + _ = Fraction(Decimal.from_float(4.2)) -14 | _ = Decimal.from_float(0.1) | note: This is an unsafe fix and may change runtime behavior @@ -139,10 +125,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -12 | _ = Fraction.from_decimal(Decimal("-4.2")) - - _ = Fraction.from_decimal(Decimal.from_float(4.2)) +13 - _ = Fraction.from_decimal(Decimal.from_float(4.2)) 13 + _ = Fraction.from_decimal(Decimal(4.2)) -14 | _ = Decimal.from_float(0.1) | note: This is an unsafe fix and may change runtime behavior @@ -158,10 +142,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -13 | _ = Fraction.from_decimal(Decimal.from_float(4.2)) - - _ = Decimal.from_float(0.1) +14 - _ = Decimal.from_float(0.1) 14 + _ = Decimal(0.1) -15 | _ = Decimal.from_float(-0.5) | note: This is an unsafe fix and may change runtime behavior @@ -177,10 +159,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -14 | _ = Decimal.from_float(0.1) - - _ = Decimal.from_float(-0.5) +15 - _ = Decimal.from_float(-0.5) 15 + _ = Decimal(-0.5) -16 | _ = Decimal.from_float(5.0) | note: This is an unsafe fix and may change runtime behavior @@ -196,10 +176,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -15 | _ = Decimal.from_float(-0.5) - - _ = Decimal.from_float(5.0) +16 - _ = Decimal.from_float(5.0) 16 + _ = Decimal(5.0) -17 | _ = decimal.Decimal.from_float(4.2) | note: This is an unsafe fix and may change runtime behavior @@ -215,10 +193,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -16 | _ = Decimal.from_float(5.0) - - _ = decimal.Decimal.from_float(4.2) +17 - _ = decimal.Decimal.from_float(4.2) 17 + _ = decimal.Decimal(4.2) -18 | _ = Decimal.from_float(float("inf")) | note: This is an unsafe fix and may change runtime behavior @@ -234,10 +210,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -17 | _ = decimal.Decimal.from_float(4.2) - - _ = Decimal.from_float(float("inf")) +18 - _ = Decimal.from_float(float("inf")) 18 + _ = Decimal("inf") -19 | _ = Decimal.from_float(float("-inf")) | FURB164 [*] Verbose method `from_float` in `Decimal` construction @@ -252,10 +226,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -18 | _ = Decimal.from_float(float("inf")) - - _ = Decimal.from_float(float("-inf")) +19 - _ = Decimal.from_float(float("-inf")) 19 + _ = Decimal("-inf") -20 | _ = Decimal.from_float(float("Infinity")) | FURB164 [*] Verbose method `from_float` in `Decimal` construction @@ -270,10 +242,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -19 | _ = Decimal.from_float(float("-inf")) - - _ = Decimal.from_float(float("Infinity")) +20 - _ = Decimal.from_float(float("Infinity")) 20 + _ = Decimal("infinity") -21 | _ = Decimal.from_float(float("-Infinity")) | FURB164 [*] Verbose method `from_float` in `Decimal` construction @@ -288,10 +258,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -20 | _ = Decimal.from_float(float("Infinity")) - - _ = Decimal.from_float(float("-Infinity")) +21 - _ = Decimal.from_float(float("-Infinity")) 21 + _ = Decimal("-infinity") -22 | _ = Decimal.from_float(float("nan")) | FURB164 [*] Verbose method `from_float` in `Decimal` construction @@ -306,10 +274,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -21 | _ = Decimal.from_float(float("-Infinity")) - - _ = Decimal.from_float(float("nan")) +22 - _ = Decimal.from_float(float("nan")) 22 + _ = Decimal("nan") -23 | _ = Decimal.from_float(float("-NaN ")) | FURB164 [*] Verbose method `from_float` in `Decimal` construction @@ -324,10 +290,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -22 | _ = Decimal.from_float(float("nan")) - - _ = Decimal.from_float(float("-NaN ")) +23 - _ = Decimal.from_float(float("-NaN ")) 23 + _ = Decimal("nan") -24 | _ = Decimal.from_float(float(" \n+nan \t")) | FURB164 [*] Verbose method `from_float` in `Decimal` construction @@ -342,10 +306,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -23 | _ = Decimal.from_float(float("-NaN ")) - - _ = Decimal.from_float(float(" \n+nan \t")) +24 - _ = Decimal.from_float(float(" \n+nan \t")) 24 + _ = Decimal("+nan") -25 | _ = Decimal.from_float(float(" iNf \n\t ")) | FURB164 [*] Verbose method `from_float` in `Decimal` construction @@ -360,10 +322,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -24 | _ = Decimal.from_float(float(" \n+nan \t")) - - _ = Decimal.from_float(float(" iNf \n\t ")) +25 - _ = Decimal.from_float(float(" iNf \n\t ")) 25 + _ = Decimal("inf") -26 | _ = Decimal.from_float(float("  -inF\n \t")) | FURB164 [*] Verbose method `from_float` in `Decimal` construction @@ -378,10 +338,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -25 | _ = Decimal.from_float(float(" iNf \n\t ")) - - _ = Decimal.from_float(float("  -inF\n \t")) +26 - _ = Decimal.from_float(float("  -inF\n \t")) 26 + _ = Decimal("-inf") -27 | _ = Decimal.from_float(float(" InfinIty \n\t ")) | FURB164 [*] Verbose method `from_float` in `Decimal` construction @@ -395,10 +353,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -26 | _ = Decimal.from_float(float("  -inF\n \t")) - - _ = Decimal.from_float(float(" InfinIty \n\t ")) +27 - _ = Decimal.from_float(float(" InfinIty \n\t ")) 27 + _ = Decimal("infinity") -28 | _ = Decimal.from_float(float("  -InfinIty\n \t")) | FURB164 [*] Verbose method `from_float` in `Decimal` construction @@ -413,10 +369,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -27 | _ = Decimal.from_float(float(" InfinIty \n\t ")) - - _ = Decimal.from_float(float("  -InfinIty\n \t")) +28 - _ = Decimal.from_float(float("  -InfinIty\n \t")) 28 + _ = Decimal("-infinity") -29 | | FURB164 [*] Verbose method `from_decimal` in `Fraction` construction @@ -429,10 +383,8 @@ FURB164 [*] Verbose method `from_decimal` in `Fraction` construction | help: Replace with `Fraction` constructor | -30 | # Cases with keyword arguments - should produce unsafe fixes - - _ = Fraction.from_decimal(dec=Decimal("4.2")) +31 - _ = Fraction.from_decimal(dec=Decimal("4.2")) 31 + _ = Fraction(Decimal("4.2")) -32 | _ = Decimal.from_float(f=4.2) | FURB164 Verbose method `from_float` in `Decimal` construction @@ -502,10 +454,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -42 | # Cases with type validation issues - should produce unsafe fixes - - _ = Decimal.from_float("4.2") # Invalid type for from_float +43 - _ = Decimal.from_float("4.2") # Invalid type for from_float 43 + _ = Decimal("4.2") # Invalid type for from_float -44 | _ = Fraction.from_decimal(4.2) # Invalid type for from_decimal | note: This is an unsafe fix and may change runtime behavior @@ -520,10 +470,8 @@ FURB164 [*] Verbose method `from_decimal` in `Fraction` construction | help: Replace with `Fraction` constructor | -43 | _ = Decimal.from_float("4.2") # Invalid type for from_float - - _ = Fraction.from_decimal(4.2) # Invalid type for from_decimal +44 - _ = Fraction.from_decimal(4.2) # Invalid type for from_decimal 44 + _ = Fraction(4.2) # Invalid type for from_decimal -45 | _ = Fraction.from_float("4.2") # Invalid type for from_float | note: This is an unsafe fix and may change runtime behavior @@ -539,10 +487,8 @@ FURB164 [*] Verbose method `from_float` in `Fraction` construction | help: Replace with `Fraction` constructor | -44 | _ = Fraction.from_decimal(4.2) # Invalid type for from_decimal - - _ = Fraction.from_float("4.2") # Invalid type for from_float +45 - _ = Fraction.from_float("4.2") # Invalid type for from_float 45 + _ = Fraction("4.2") # Invalid type for from_float -46 | | note: This is an unsafe fix and may change runtime behavior @@ -556,10 +502,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -59 | # Cases with int and bool - should produce safe fixes - - _ = Decimal.from_float(1) +60 - _ = Decimal.from_float(1) 60 + _ = Decimal(1) -61 | _ = Decimal.from_float(True) | FURB164 [*] Verbose method `from_float` in `Decimal` construction @@ -574,10 +518,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -60 | _ = Decimal.from_float(1) - - _ = Decimal.from_float(True) +61 - _ = Decimal.from_float(True) 61 + _ = Decimal(True) -62 | | FURB164 [*] Verbose method `from_float` in `Decimal` construction @@ -591,10 +533,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -63 | # Cases with non-finite floats - should produce safe fixes - - _ = Decimal.from_float(float("-nan")) +64 - _ = Decimal.from_float(float("-nan")) 64 + _ = Decimal("nan") -65 | _ = Decimal.from_float(float("\x2dnan")) | FURB164 [*] Verbose method `from_float` in `Decimal` construction @@ -608,10 +548,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -64 | _ = Decimal.from_float(float("-nan")) - - _ = Decimal.from_float(float("\x2dnan")) +65 - _ = Decimal.from_float(float("\x2dnan")) 65 + _ = Decimal("nan") -66 | _ = Decimal.from_float(float("\N{HYPHEN-MINUS}nan")) | FURB164 [*] Verbose method `from_float` in `Decimal` construction @@ -626,10 +564,8 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | help: Replace with `Decimal` constructor | -65 | _ = Decimal.from_float(float("\x2dnan")) - - _ = Decimal.from_float(float("\N{HYPHEN-MINUS}nan")) +66 - _ = Decimal.from_float(float("\N{HYPHEN-MINUS}nan")) 66 + _ = Decimal("nan") -67 | | FURB164 [*] Verbose method `from_float` in `Fraction` construction @@ -643,10 +579,8 @@ FURB164 [*] Verbose method `from_float` in `Fraction` construction | help: Replace with `Fraction` constructor | -69 | # fixes must be safe - - _ = Fraction.from_float(f=4.2) +70 - _ = Fraction.from_float(f=4.2) 70 + _ = Fraction(4.2) -71 | _ = Fraction.from_decimal(dec=4) | FURB164 [*] Verbose method `from_decimal` in `Fraction` construction @@ -661,10 +595,8 @@ FURB164 [*] Verbose method `from_decimal` in `Fraction` construction | help: Replace with `Fraction` constructor | -70 | _ = Fraction.from_float(f=4.2) - - _ = Fraction.from_decimal(dec=4) +71 - _ = Fraction.from_decimal(dec=4) 71 + _ = Fraction(4) -72 | | FURB164 [*] Verbose method `from_float` in `Fraction` construction @@ -679,12 +611,10 @@ FURB164 [*] Verbose method `from_float` in `Fraction` construction | help: Replace with `Fraction` constructor | -73 | _ = ( - - Fraction - - # text - - .from_float(4.2) +74 - Fraction +75 - # text +76 - .from_float(4.2) 74 + Fraction(4.2) -75 | ) | note: This is an unsafe fix and may change runtime behavior @@ -701,11 +631,10 @@ FURB164 [*] Verbose method `from_float` in `Decimal` construction | |_^ help: Replace with `Decimal` constructor | -78 | - - _ = Decimal.from_float( - - # keep this comment - - float("inf") - - ) +79 - _ = Decimal.from_float( +80 - # keep this comment +81 - float("inf") +82 - ) 79 + _ = Decimal("inf") | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB166_FURB166.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB166_FURB166.py.snap index b21c9ec5c121d..9cd690d13fb11 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB166_FURB166.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB166_FURB166.py.snap @@ -13,10 +13,8 @@ FURB166 [*] Use of `int` with explicit `base=2` after removing prefix | help: Replace with `base=0` | -2 | - - _ = int("0b1010"[2:], 2) +3 - _ = int("0b1010"[2:], 2) 3 + _ = int("0b1010", 0) -4 | _ = int("0o777"[2:], 8) | note: This is an unsafe fix and may change runtime behavior @@ -30,10 +28,8 @@ FURB166 [*] Use of `int` with explicit `base=8` after removing prefix | help: Replace with `base=0` | -3 | _ = int("0b1010"[2:], 2) - - _ = int("0o777"[2:], 8) +4 - _ = int("0o777"[2:], 8) 4 + _ = int("0o777", 0) -5 | _ = int("0xFFFF"[2:], 16) | note: This is an unsafe fix and may change runtime behavior @@ -49,10 +45,8 @@ FURB166 [*] Use of `int` with explicit `base=16` after removing prefix | help: Replace with `base=0` | -4 | _ = int("0o777"[2:], 8) - - _ = int("0xFFFF"[2:], 16) +5 - _ = int("0xFFFF"[2:], 16) 5 + _ = int("0xFFFF", 0) -6 | | note: This is an unsafe fix and may change runtime behavior @@ -67,10 +61,8 @@ FURB166 [*] Use of `int` with explicit `base=2` after removing prefix | help: Replace with `base=0` | -7 | b = "0b11" - - _ = int(b[2:], 2) +8 - _ = int(b[2:], 2) 8 + _ = int(b, 0) -9 | | note: This is an unsafe fix and may change runtime behavior @@ -86,10 +78,8 @@ FURB166 [*] Use of `int` with explicit `base=16` after removing prefix | help: Replace with `base=0` | -9 | - - _ = int("0xFFFF"[2:], base=16) +10 - _ = int("0xFFFF"[2:], base=16) 10 + _ = int("0xFFFF", base=0) -11 | | note: This is an unsafe fix and may change runtime behavior @@ -102,10 +92,8 @@ FURB166 [*] Use of `int` with explicit `base=16` after removing prefix | ^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `base=0` | -11 | - - _ = int(b"0xFFFF"[2:], 16) +12 - _ = int(b"0xFFFF"[2:], 16) 12 + _ = int(b"0xFFFF", 0) -13 | | note: This is an unsafe fix and may change runtime behavior @@ -119,9 +107,7 @@ FURB166 [*] Use of `int` with explicit `base=16` after removing prefix | help: Replace with `base=0` | -18 | - - _ = int(get_str()[2:], 16) +19 - _ = int(get_str()[2:], 16) 19 + _ = int(get_str(), 0) -20 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB167_FURB167.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB167_FURB167.py.snap index e56e3f467bc6a..1fb37322d170b 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB167_FURB167.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB167_FURB167.py.snap @@ -11,10 +11,10 @@ FURB167 [*] Use of regular expression alias `re.I` | help: Replace with `re.IGNORECASE` | +10 ~ import re +11 | 12 | # FURB167 - - if re.search("^hello", "hello world", re.I): -13 + if re.search("^hello", "hello world", re.IGNORECASE): -14 | pass +13 ~ if re.search("^hello", "hello world", re.IGNORECASE): | FURB167 [*] Use of regular expression alias `re.I` @@ -27,11 +27,10 @@ FURB167 [*] Use of regular expression alias `re.I` | help: Replace with `re.IGNORECASE` | -1 + import re -2 | def func(): --------------------------------------------------------------------------------- + 1 + import re + 2 | def func(): + 3 | import re + … 21 | # FURB167 - - if search("^hello", "hello world", I): -22 + if search("^hello", "hello world", re.IGNORECASE): -23 | pass +22 ~ if search("^hello", "hello world", re.IGNORECASE): | diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB168_FURB168.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB168_FURB168.py.snap index 67a60b4687d4e..f29b49bff42ed 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB168_FURB168.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB168_FURB168.py.snap @@ -12,10 +12,8 @@ FURB168 [*] Prefer `is` operator over `isinstance` to check if an object is `Non | help: Replace with `is` operator | -4 | - - if isinstance(foo, type(None)): +5 - if isinstance(foo, type(None)): 5 + if foo is None: -6 | pass | FURB168 [*] Prefer `is` operator over `isinstance` to check if an object is `None` @@ -29,10 +27,8 @@ FURB168 [*] Prefer `is` operator over `isinstance` to check if an object is `Non | help: Replace with `is` operator | -7 | - - if isinstance(foo and bar, type(None)): +8 - if isinstance(foo and bar, type(None)): 8 + if (foo and bar) is None: -9 | pass | FURB168 [*] Prefer `is` operator over `isinstance` to check if an object is `None` @@ -46,10 +42,8 @@ FURB168 [*] Prefer `is` operator over `isinstance` to check if an object is `Non | help: Replace with `is` operator | -10 | - - if isinstance(foo, (type(None), type(None), type(None))): +11 - if isinstance(foo, (type(None), type(None), type(None))): 11 + if foo is None: -12 | pass | FURB168 [*] Prefer `is` operator over `isinstance` to check if an object is `None` @@ -63,10 +57,8 @@ FURB168 [*] Prefer `is` operator over `isinstance` to check if an object is `Non | help: Replace with `is` operator | -13 | - - if isinstance(foo, type(None)) is True: +14 - if isinstance(foo, type(None)) is True: 14 + if (foo is None) is True: -15 | pass | FURB168 [*] Prefer `is` operator over `isinstance` to check if an object is `None` @@ -80,10 +72,8 @@ FURB168 [*] Prefer `is` operator over `isinstance` to check if an object is `Non | help: Replace with `is` operator | -16 | - - if -isinstance(foo, type(None)): +17 - if -isinstance(foo, type(None)): 17 + if -(foo is None): -18 | pass | FURB168 [*] Prefer `is` operator over `isinstance` to check if an object is `None` @@ -97,10 +87,8 @@ FURB168 [*] Prefer `is` operator over `isinstance` to check if an object is `Non | help: Replace with `is` operator | -19 | - - if isinstance(foo, None | type(None)): +20 - if isinstance(foo, None | type(None)): 20 + if foo is None: -21 | pass | FURB168 [*] Prefer `is` operator over `isinstance` to check if an object is `None` @@ -114,10 +102,8 @@ FURB168 [*] Prefer `is` operator over `isinstance` to check if an object is `Non | help: Replace with `is` operator | -22 | - - if isinstance(foo, type(None) | type(None)): +23 - if isinstance(foo, type(None) | type(None)): 23 + if foo is None: -24 | pass | FURB168 [*] Prefer `is` operator over `isinstance` to check if an object is `None` @@ -130,10 +116,8 @@ FURB168 [*] Prefer `is` operator over `isinstance` to check if an object is `Non | help: Replace with `is` operator | -26 | # A bit contrived, but is both technically valid and equivalent to the above. - - if isinstance(foo, (type(None) | ((((type(None))))) | ((None | type(None))))): +27 - if isinstance(foo, (type(None) | ((((type(None))))) | ((None | type(None))))): 27 + if foo is None: -28 | pass | FURB168 [*] Prefer `is` operator over `isinstance` to check if an object is `None` @@ -147,10 +131,8 @@ FURB168 [*] Prefer `is` operator over `isinstance` to check if an object is `Non | help: Replace with `is` operator | -37 | - - if isinstance(foo, Union[None]): +38 - if isinstance(foo, Union[None]): 38 + if foo is None: -39 | ... | FURB168 [*] Prefer `is` operator over `isinstance` to check if an object is `None` @@ -164,10 +146,8 @@ FURB168 [*] Prefer `is` operator over `isinstance` to check if an object is `Non | help: Replace with `is` operator | -40 | - - if isinstance(foo, Union[None, None]): +41 - if isinstance(foo, Union[None, None]): 41 + if foo is None: -42 | ... | FURB168 [*] Prefer `is` operator over `isinstance` to check if an object is `None` @@ -181,8 +161,6 @@ FURB168 [*] Prefer `is` operator over `isinstance` to check if an object is `Non | help: Replace with `is` operator | -43 | - - if isinstance(foo, Union[None, type(None)]): +44 - if isinstance(foo, Union[None, type(None)]): 44 + if foo is None: -45 | ... | diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB169_FURB169.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB169_FURB169.py.snap index ba454f05e7703..f80b5efb7c37a 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB169_FURB169.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB169_FURB169.py.snap @@ -13,10 +13,8 @@ FURB169 [*] When checking against `None`, use `is` instead of comparison with `t | help: Replace with `is None` | -4 | - - type(foo) is type(None) +5 - type(foo) is type(None) 5 + foo is None -6 | | FURB169 [*] When checking against `None`, use `is` instead of comparison with `type(None)` @@ -31,10 +29,8 @@ FURB169 [*] When checking against `None`, use `is` instead of comparison with `t | help: Replace with `is None` | -6 | - - type(None) is type(foo) +7 - type(None) is type(foo) 7 + foo is None -8 | | FURB169 [*] When checking against `None`, use `is` instead of comparison with `type(None)` @@ -48,12 +44,10 @@ FURB169 [*] When checking against `None`, use `is` instead of comparison with `t 11 | type(foo) is not type(None) | help: Replace with `is None` - | -8 | - - type(None) is type(None) -9 + None is None -10 | - | + | +9 - type(None) is type(None) +9 + None is None + | FURB169 [*] When checking against `None`, use `is not` instead of comparison with `type(None)` --> FURB169.py:11:1 @@ -67,10 +61,8 @@ FURB169 [*] When checking against `None`, use `is not` instead of comparison wit | help: Replace with `is not None` | -10 | - - type(foo) is not type(None) +11 - type(foo) is not type(None) 11 + foo is not None -12 | | FURB169 [*] When checking against `None`, use `is not` instead of comparison with `type(None)` @@ -85,10 +77,8 @@ FURB169 [*] When checking against `None`, use `is not` instead of comparison wit | help: Replace with `is not None` | -12 | - - type(None) is not type(foo) +13 - type(None) is not type(foo) 13 + foo is not None -14 | | FURB169 [*] When checking against `None`, use `is not` instead of comparison with `type(None)` @@ -103,10 +93,8 @@ FURB169 [*] When checking against `None`, use `is not` instead of comparison wit | help: Replace with `is not None` | -14 | - - type(None) is not type(None) +15 - type(None) is not type(None) 15 + None is not None -16 | | FURB169 [*] When checking against `None`, use `is` instead of comparison with `type(None)` @@ -121,10 +109,8 @@ FURB169 [*] When checking against `None`, use `is` instead of comparison with `t | help: Replace with `is None` | -16 | - - type(foo) == type(None) +17 - type(foo) == type(None) 17 + foo is None -18 | | FURB169 [*] When checking against `None`, use `is` instead of comparison with `type(None)` @@ -139,10 +125,8 @@ FURB169 [*] When checking against `None`, use `is` instead of comparison with `t | help: Replace with `is None` | -18 | - - type(None) == type(foo) +19 - type(None) == type(foo) 19 + foo is None -20 | | FURB169 [*] When checking against `None`, use `is` instead of comparison with `type(None)` @@ -157,10 +141,8 @@ FURB169 [*] When checking against `None`, use `is` instead of comparison with `t | help: Replace with `is None` | -20 | - - type(None) == type(None) +21 - type(None) == type(None) 21 + None is None -22 | | FURB169 [*] When checking against `None`, use `is not` instead of comparison with `type(None)` @@ -175,10 +157,8 @@ FURB169 [*] When checking against `None`, use `is not` instead of comparison wit | help: Replace with `is not None` | -22 | - - type(foo) != type(None) +23 - type(foo) != type(None) 23 + foo is not None -24 | | FURB169 [*] When checking against `None`, use `is not` instead of comparison with `type(None)` @@ -193,10 +173,8 @@ FURB169 [*] When checking against `None`, use `is not` instead of comparison wit | help: Replace with `is not None` | -24 | - - type(None) != type(foo) +25 - type(None) != type(foo) 25 + foo is not None -26 | | FURB169 [*] When checking against `None`, use `is not` instead of comparison with `type(None)` @@ -211,10 +189,8 @@ FURB169 [*] When checking against `None`, use `is not` instead of comparison wit | help: Replace with `is not None` | -26 | - - type(None) != type(None) +27 - type(None) != type(None) 27 + None is not None -28 | | FURB169 [*] When checking against `None`, use `is` instead of comparison with `type(None)` @@ -229,10 +205,8 @@ FURB169 [*] When checking against `None`, use `is` instead of comparison with `t | help: Replace with `is None` | -28 | - - type(a.b) is type(None) +29 - type(a.b) is type(None) 29 + a.b is None -30 | | FURB169 [*] When checking against `None`, use `is not` instead of comparison with `type(None)` @@ -251,14 +225,12 @@ FURB169 [*] When checking against `None`, use `is not` instead of comparison wit | help: Replace with `is not None` | -30 | - - type( - - a( - - # Comment - - ) - - ) != type(None) +31 - type( +32 - a( +33 - # Comment +34 - ) +35 - ) != type(None) 31 + a() is not None -32 | | note: This is an unsafe fix and may change runtime behavior @@ -276,12 +248,10 @@ FURB169 [*] When checking against `None`, use `is` instead of comparison with `t | help: Replace with `is None` | -36 | - - type( - - a := 1 - - ) == type(None) +37 - type( +38 - a := 1 +39 - ) == type(None) 37 + (a := 1) is None -38 | | FURB169 [*] When checking against `None`, use `is not` instead of comparison with `type(None)` @@ -295,10 +265,8 @@ FURB169 [*] When checking against `None`, use `is not` instead of comparison wit | |___________________^ help: Replace with `is not None` | -40 | - - type( - - a for a in range(0) - - ) is not type(None) +41 - type( +42 - a for a in range(0) +43 - ) is not type(None) 41 + (a for a in range(0)) is not None -42 | | diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB171_FURB171_0.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB171_FURB171_0.py.snap index 06200aca44203..af14e6f3d1b39 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB171_FURB171_0.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB171_FURB171_0.py.snap @@ -12,10 +12,8 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -2 | - - if 1 in (1,): +3 - if 1 in (1,): 3 + if 1 == 1: -4 | print("Single-element tuple") | note: This is an unsafe fix and may change runtime behavior @@ -30,10 +28,8 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -5 | - - if 1 in [1]: +6 - if 1 in [1]: 6 + if 1 == 1: -7 | print("Single-element list") | note: This is an unsafe fix and may change runtime behavior @@ -47,12 +43,10 @@ FURB171 [*] Membership test against single-item container 10 | print("Single-element set") | help: Convert to equality test - | -8 | - - if 1 in {1}: -9 + if 1 == 1: -10 | print("Single-element set") - | + | +9 - if 1 in {1}: +9 + if 1 == 1: + | note: This is an unsafe fix and may change runtime behavior FURB171 [*] Membership test against single-item container @@ -66,10 +60,8 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -11 | - - if "a" in "a": +12 - if "a" in "a": 12 + if "a" == "a": -13 | print("Single-element string") | note: This is an unsafe fix and may change runtime behavior @@ -84,10 +76,8 @@ FURB171 [*] Membership test against single-item container | help: Convert to inequality test | -14 | - - if 1 not in (1,): +15 - if 1 not in (1,): 15 + if 1 != 1: -16 | print("Check `not in` membership test") | note: This is an unsafe fix and may change runtime behavior @@ -102,10 +92,8 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -17 | - - if not 1 in (1,): +18 - if not 1 in (1,): 18 + if not 1 == 1: -19 | print("Check the negated membership test") | note: This is an unsafe fix and may change runtime behavior @@ -124,13 +112,11 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -51 | # https://github.com/astral-sh/ruff/issues/10063 - - _ = a in ( - - # Foo - - b, - - ) +52 - _ = a in ( +53 - # Foo +54 - b, +55 - ) 52 + _ = a == b -53 | | note: This is an unsafe fix and may change runtime behavior @@ -162,25 +148,11 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -56 | - - _ = a in ( # Foo1 - - ( # Foo2 - - # Foo3 - - ( # Tuple - - ( # Bar -57 + _ = a == ( # Bar -58 | (b -59 | # Bar -60 | ) -61 | ) - - # Foo4 - - # Foo5 - - , - - ) - - # Foo6 - - ) - - ) -62 | +57 ~ _ = a == ( # Bar +58 + (b +59 + # Bar +60 + ) +61 + ) | note: This is an unsafe fix and may change runtime behavior @@ -200,14 +172,12 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -76 | .ipsum() - - .dolor(lambda sit: sit in ( - - # Foo1 - - # Foo2 - - amet, - - )) +77 - .dolor(lambda sit: sit in ( +78 - # Foo1 +79 - # Foo2 +80 - amet, +81 - )) 77 + .dolor(lambda sit: sit == amet) -78 | ) | note: This is an unsafe fix and may change runtime behavior @@ -229,17 +199,11 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -86 | .ipsum() - - .dolor(lambda sit: sit in ( - - ( -87 + .dolor(lambda sit: sit == ( -88 | # Foo1 -89 | # Foo2 -90 | amet - - ), - - )) -91 + )) -92 | ) +87 ~ .dolor(lambda sit: sit == ( +88 + # Foo1 +89 + # Foo2 +90 + amet +91 ~ )) | note: This is an unsafe fix and may change runtime behavior @@ -259,16 +223,14 @@ FURB171 [*] Membership test against single-item container 104 | def _(): | help: Convert to equality test - | -97 | .ipsum() \ - - .dolor(lambda sit: sit in ( - - # Foo1 - - # Foo2 - - amet, - - )) -98 + .dolor(lambda sit: sit == amet) -99 | - | + | + 98 - .dolor(lambda sit: sit in ( + 99 - # Foo1 +100 - # Foo2 +101 - amet, +102 - )) + 98 + .dolor(lambda sit: sit == amet) + | note: This is an unsafe fix and may change runtime behavior FURB171 [*] Membership test against single-item container @@ -288,15 +250,13 @@ FURB171 [*] Membership test against single-item container | help: Convert to inequality test | -104 | def _(): - - if foo not \ - - in [ - - # Before - - bar - - # After - - ]: ... +105 - if foo not \ +106 - in [ +107 - # Before +108 - bar +109 - # After +110 - ]: ... 105 + if foo != bar: ... -106 | | note: This is an unsafe fix and may change runtime behavior @@ -316,15 +276,13 @@ FURB171 [*] Membership test against single-item container | help: Convert to inequality test | -112 | def _(): - - if foo not \ - - in [ - - # Before - - bar - - # After - - ] and \ +113 - if foo not \ +114 - in [ +115 - # Before +116 - bar +117 - # After +118 - ] and \ 113 + if foo != bar and \ -114 | 0 < 1: ... | note: This is an unsafe fix and may change runtime behavior @@ -338,10 +296,8 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -124 | # NaN behavior differences - - if math.nan in [math.nan]: +125 - if math.nan in [math.nan]: 125 + if math.nan == math.nan: -126 | print("This is True") | note: This is an unsafe fix and may change runtime behavior @@ -356,10 +312,8 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -127 | - - if math.nan in (math.nan,): +128 - if math.nan in (math.nan,): 128 + if math.nan == math.nan: -129 | print("This is True") | note: This is an unsafe fix and may change runtime behavior @@ -374,10 +328,8 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -130 | - - if math.nan in {math.nan}: +131 - if math.nan in {math.nan}: 131 + if math.nan == math.nan: -132 | print("This is True") | note: This is an unsafe fix and may change runtime behavior @@ -391,10 +343,8 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -139 | obj = CustomEq() - - if obj in [CustomEq()]: +140 - if obj in [CustomEq()]: 140 + if obj == CustomEq(): -141 | pass | note: This is an unsafe fix and may change runtime behavior @@ -409,10 +359,8 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -142 | - - if obj in (CustomEq(),): +143 - if obj in (CustomEq(),): 143 + if obj == CustomEq(): -144 | pass | note: This is an unsafe fix and may change runtime behavior @@ -427,9 +375,7 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -145 | - - if obj in {CustomEq()}: +146 - if obj in {CustomEq()}: 146 + if obj == CustomEq(): -147 | pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB171_FURB171_1.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB171_FURB171_1.py.snap index 7916543b7f6fc..ee65e46fe3709 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB171_FURB171_1.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB171_FURB171_1.py.snap @@ -12,10 +12,8 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -2 | - - if 1 in set([1]): +3 - if 1 in set([1]): 3 + if 1 == 1: -4 | print("Single-element set") | note: This is an unsafe fix and may change runtime behavior @@ -30,10 +28,8 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -5 | - - if 1 in set((1,)): +6 - if 1 in set((1,)): 6 + if 1 == 1: -7 | print("Single-element set") | note: This is an unsafe fix and may change runtime behavior @@ -47,12 +43,10 @@ FURB171 [*] Membership test against single-item container 10 | print("Single-element set") | help: Convert to equality test - | -8 | - - if 1 in set({1}): -9 + if 1 == 1: -10 | print("Single-element set") - | + | +9 - if 1 in set({1}): +9 + if 1 == 1: + | note: This is an unsafe fix and may change runtime behavior FURB171 [*] Membership test against single-item container @@ -66,10 +60,8 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -11 | - - if 1 in frozenset([1]): +12 - if 1 in frozenset([1]): 12 + if 1 == 1: -13 | print("Single-element set") | note: This is an unsafe fix and may change runtime behavior @@ -84,10 +76,8 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -14 | - - if 1 in frozenset((1,)): +15 - if 1 in frozenset((1,)): 15 + if 1 == 1: -16 | print("Single-element set") | note: This is an unsafe fix and may change runtime behavior @@ -102,10 +92,8 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -17 | - - if 1 in frozenset({1}): +18 - if 1 in frozenset({1}): 18 + if 1 == 1: -19 | print("Single-element set") | note: This is an unsafe fix and may change runtime behavior @@ -120,10 +108,8 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -20 | - - if 1 in set(set([1])): +21 - if 1 in set(set([1])): 21 + if 1 == 1: -22 | print('Recursive solution') | note: This is an unsafe fix and may change runtime behavior @@ -137,10 +123,8 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -58 | # set() and frozenset() with NaN - - if math.nan in set([math.nan]): +59 - if math.nan in set([math.nan]): 59 + if math.nan == math.nan: -60 | print("This should be marked unsafe") | note: This is an unsafe fix and may change runtime behavior @@ -155,9 +139,7 @@ FURB171 [*] Membership test against single-item container | help: Convert to equality test | -61 | - - if math.nan in frozenset([math.nan]): +62 - if math.nan in frozenset([math.nan]): 62 + if math.nan == math.nan: -63 | print("This should be marked unsafe") | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB177_FURB177.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB177_FURB177.py.snap index 32e2d02c704e7..09feeae136d73 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB177_FURB177.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB177_FURB177.py.snap @@ -11,10 +11,10 @@ FURB177 [*] Prefer `Path.cwd()` over `Path().resolve()` for current-directory lo | help: Replace `Path().resolve()` with `Path.cwd()` | +2 ~ from pathlib import Path +3 | 4 | # Errors - - _ = Path().resolve() -5 + _ = Path.cwd() -6 | _ = pathlib.Path().resolve() +5 ~ _ = Path.cwd() | note: This is an unsafe fix and may change runtime behavior @@ -30,10 +30,11 @@ FURB177 [*] Prefer `Path.cwd()` over `Path().resolve()` for current-directory lo | help: Replace `Path().resolve()` with `Path.cwd()` | +2 ~ from pathlib import Path +3 | +4 | # Errors 5 | _ = Path().resolve() - - _ = pathlib.Path().resolve() -6 + _ = Path.cwd() -7 | +6 ~ _ = Path.cwd() | note: This is an unsafe fix and may change runtime behavior @@ -48,10 +49,11 @@ FURB177 [*] Prefer `Path.cwd()` over `Path().resolve()` for current-directory lo | help: Replace `Path().resolve()` with `Path.cwd()` | +2 ~ from pathlib import Path +3 | +… 7 | - - _ = Path("").resolve() -8 + _ = Path.cwd() -9 | _ = pathlib.Path("").resolve() +8 ~ _ = Path.cwd() | note: This is an unsafe fix and may change runtime behavior @@ -65,12 +67,13 @@ FURB177 [*] Prefer `Path.cwd()` over `Path().resolve()` for current-directory lo 11 | _ = Path(".").resolve() | help: Replace `Path().resolve()` with `Path.cwd()` - | -8 | _ = Path("").resolve() - - _ = pathlib.Path("").resolve() -9 + _ = Path.cwd() -10 | - | + | +2 ~ from pathlib import Path +3 | +… +8 | _ = Path("").resolve() +9 ~ _ = Path.cwd() + | note: This is an unsafe fix and may change runtime behavior FURB177 [*] Prefer `Path.cwd()` over `Path().resolve()` for current-directory lookups @@ -84,10 +87,11 @@ FURB177 [*] Prefer `Path.cwd()` over `Path().resolve()` for current-directory lo | help: Replace `Path().resolve()` with `Path.cwd()` | + 2 ~ from pathlib import Path + 3 | + … 10 | - - _ = Path(".").resolve() -11 + _ = Path.cwd() -12 | _ = pathlib.Path(".").resolve() +11 ~ _ = Path.cwd() | note: This is an unsafe fix and may change runtime behavior @@ -102,10 +106,11 @@ FURB177 [*] Prefer `Path.cwd()` over `Path().resolve()` for current-directory lo | help: Replace `Path().resolve()` with `Path.cwd()` | + 2 ~ from pathlib import Path + 3 | + … 11 | _ = Path(".").resolve() - - _ = pathlib.Path(".").resolve() -12 + _ = Path.cwd() -13 | +12 ~ _ = Path.cwd() | note: This is an unsafe fix and may change runtime behavior @@ -120,10 +125,11 @@ FURB177 [*] Prefer `Path.cwd()` over `Path().resolve()` for current-directory lo | help: Replace `Path().resolve()` with `Path.cwd()` | + 2 ~ from pathlib import Path + 3 | + … 13 | - - _ = Path("", **kwargs).resolve() -14 + _ = Path.cwd() -15 | _ = pathlib.Path("", **kwargs).resolve() +14 ~ _ = Path.cwd() | note: This is an unsafe fix and may change runtime behavior @@ -138,10 +144,11 @@ FURB177 [*] Prefer `Path.cwd()` over `Path().resolve()` for current-directory lo | help: Replace `Path().resolve()` with `Path.cwd()` | + 2 ~ from pathlib import Path + 3 | + … 14 | _ = Path("", **kwargs).resolve() - - _ = pathlib.Path("", **kwargs).resolve() -15 + _ = Path.cwd() -16 | +15 ~ _ = Path.cwd() | note: This is an unsafe fix and may change runtime behavior @@ -156,10 +163,11 @@ FURB177 [*] Prefer `Path.cwd()` over `Path().resolve()` for current-directory lo | help: Replace `Path().resolve()` with `Path.cwd()` | + 2 ~ from pathlib import Path + 3 | + … 16 | - - _ = Path(".", **kwargs).resolve() -17 + _ = Path.cwd() -18 | _ = pathlib.Path(".", **kwargs).resolve() +17 ~ _ = Path.cwd() | note: This is an unsafe fix and may change runtime behavior @@ -174,9 +182,10 @@ FURB177 [*] Prefer `Path.cwd()` over `Path().resolve()` for current-directory lo | help: Replace `Path().resolve()` with `Path.cwd()` | + 2 ~ from pathlib import Path + 3 | + … 17 | _ = Path(".", **kwargs).resolve() - - _ = pathlib.Path(".", **kwargs).resolve() -18 + _ = Path.cwd() -19 | +18 ~ _ = Path.cwd() | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB180_FURB180.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB180_FURB180.py.snap index 121a8cb671aa8..37fbb7b32f433 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB180_FURB180.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB180_FURB180.py.snap @@ -13,10 +13,11 @@ FURB180 [*] Use of `metaclass=abc.ABCMeta` to define abstract base class | help: Replace with `abc.ABC` | +1 ~ import abc +2 | from abc import abstractmethod, ABCMeta +… 6 | - - class A0(metaclass=abc.ABCMeta): -7 + class A0(abc.ABC): -8 | @abstractmethod +7 ~ class A0(abc.ABC): | FURB180 [*] Use of `metaclass=abc.ABCMeta` to define abstract base class @@ -29,10 +30,11 @@ FURB180 [*] Use of `metaclass=abc.ABCMeta` to define abstract base class | help: Replace with `abc.ABC` | + 1 ~ import abc + 2 | from abc import abstractmethod, ABCMeta + … 11 | - - class A1(metaclass=ABCMeta): -12 + class A1(abc.ABC): -13 | @abstractmethod +12 ~ class A1(abc.ABC): | FURB180 [*] Use of `metaclass=abc.ABCMeta` to define abstract base class @@ -45,10 +47,11 @@ FURB180 [*] Use of `metaclass=abc.ABCMeta` to define abstract base class | help: Replace with `abc.ABC` | + 1 ~ import abc + 2 | from abc import abstractmethod, ABCMeta + … 25 | - - class A2(B0, B1, metaclass=ABCMeta): -26 + class A2(B0, B1, abc.ABC): -27 | @abstractmethod +26 ~ class A2(B0, B1, abc.ABC): | note: This is an unsafe fix and may change runtime behavior @@ -61,10 +64,11 @@ FURB180 [*] Use of `metaclass=abc.ABCMeta` to define abstract base class | help: Replace with `abc.ABC` | + 1 ~ import abc + 2 | from abc import abstractmethod, ABCMeta + … 30 | - - class A3(B0, before_metaclass=1, metaclass=abc.ABCMeta): -31 + class A3(B0, abc.ABC, before_metaclass=1): -32 | pass +31 ~ class A3(B0, abc.ABC, before_metaclass=1): | note: This is an unsafe fix and may change runtime behavior @@ -79,10 +83,11 @@ FURB180 [*] Use of `metaclass=abc.ABCMeta` to define abstract base class | help: Replace with `abc.ABC` | + 1 ~ import abc + 2 | from abc import abstractmethod, ABCMeta + … 61 | # Regression tests for https://github.com/astral-sh/ruff/issues/17162 - - class A8(abc.ABC, metaclass=ABCMeta): # FURB180 -62 + class A8(abc.ABC): # FURB180 -63 | @abstractmethod +62 ~ class A8(abc.ABC): # FURB180 | note: This is an unsafe fix and may change runtime behavior @@ -98,10 +103,9 @@ FURB180 [*] Use of `metaclass=abc.ABCMeta` to define abstract base class | help: Replace with `abc.ABC` | +69 ~ from abc import ABC 70 | - - class A9(ABC, metaclass=ABCMeta): # FURB180 -71 + class A9(ABC): # FURB180 -72 | @abstractmethod +71 ~ class A9(ABC): # FURB180 | note: This is an unsafe fix and may change runtime behavior @@ -117,10 +121,9 @@ FURB180 [*] Use of `metaclass=abc.ABCMeta` to define abstract base class | help: Replace with `abc.ABC` | +78 ~ from abc import ABC as ABCAlternativeName 79 | - - class A10(ABCAlternativeName, metaclass=ABCMeta): # FURB180 -80 + class A10(ABCAlternativeName): # FURB180 -81 | @abstractmethod +80 ~ class A10(ABCAlternativeName): # FURB180 | note: This is an unsafe fix and may change runtime behavior @@ -134,10 +137,11 @@ FURB180 [*] Use of `metaclass=abc.ABCMeta` to define abstract base class | help: Replace with `abc.ABC` | + 1 ~ import abc + 2 | from abc import abstractmethod, ABCMeta + … 88 | - - class A11(MyMetaClass, metaclass=ABCMeta): # FURB180 -89 + class A11(MyMetaClass): # FURB180 -90 | @abstractmethod +89 ~ class A11(MyMetaClass): # FURB180 | note: This is an unsafe fix and may change runtime behavior @@ -153,11 +157,10 @@ FURB180 [*] Use of `metaclass=abc.ABCMeta` to define abstract base class | help: Replace with `abc.ABC` | + 1 ~ import abc + 2 | from abc import abstractmethod, ABCMeta + … 95 | class A12( - - keyword_argument=1, - - # comment - - metaclass=abc.ABCMeta, -96 + abc.ABC, keyword_argument=1, -97 | ): # FURB180 +96 ~ abc.ABC, keyword_argument=1, | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB181_FURB181.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB181_FURB181.py.snap index 4cd176d1ed3cd..a077151bf62e6 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB181_FURB181.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB181_FURB181.py.snap @@ -13,10 +13,8 @@ FURB181 [*] Use of hashlib's `.digest().hex()` | help: Replace with `.hexdigest()` | -18 | - - blake2b().digest().hex() +19 - blake2b().digest().hex() 19 + blake2b().hexdigest() -20 | blake2s().digest().hex() | FURB181 [*] Use of hashlib's `.digest().hex()` @@ -30,10 +28,8 @@ FURB181 [*] Use of hashlib's `.digest().hex()` | help: Replace with `.hexdigest()` | -19 | blake2b().digest().hex() - - blake2s().digest().hex() +20 - blake2s().digest().hex() 20 + blake2s().hexdigest() -21 | md5().digest().hex() | FURB181 [*] Use of hashlib's `.digest().hex()` @@ -48,10 +44,8 @@ FURB181 [*] Use of hashlib's `.digest().hex()` | help: Replace with `.hexdigest()` | -20 | blake2s().digest().hex() - - md5().digest().hex() +21 - md5().digest().hex() 21 + md5().hexdigest() -22 | sha1().digest().hex() | FURB181 [*] Use of hashlib's `.digest().hex()` @@ -66,10 +60,8 @@ FURB181 [*] Use of hashlib's `.digest().hex()` | help: Replace with `.hexdigest()` | -21 | md5().digest().hex() - - sha1().digest().hex() +22 - sha1().digest().hex() 22 + sha1().hexdigest() -23 | sha224().digest().hex() | FURB181 [*] Use of hashlib's `.digest().hex()` @@ -84,10 +76,8 @@ FURB181 [*] Use of hashlib's `.digest().hex()` | help: Replace with `.hexdigest()` | -22 | sha1().digest().hex() - - sha224().digest().hex() +23 - sha224().digest().hex() 23 + sha224().hexdigest() -24 | sha256().digest().hex() | FURB181 [*] Use of hashlib's `.digest().hex()` @@ -102,10 +92,8 @@ FURB181 [*] Use of hashlib's `.digest().hex()` | help: Replace with `.hexdigest()` | -23 | sha224().digest().hex() - - sha256().digest().hex() +24 - sha256().digest().hex() 24 + sha256().hexdigest() -25 | sha384().digest().hex() | FURB181 [*] Use of hashlib's `.digest().hex()` @@ -120,10 +108,8 @@ FURB181 [*] Use of hashlib's `.digest().hex()` | help: Replace with `.hexdigest()` | -24 | sha256().digest().hex() - - sha384().digest().hex() +25 - sha384().digest().hex() 25 + sha384().hexdigest() -26 | sha3_224().digest().hex() | FURB181 [*] Use of hashlib's `.digest().hex()` @@ -138,10 +124,8 @@ FURB181 [*] Use of hashlib's `.digest().hex()` | help: Replace with `.hexdigest()` | -25 | sha384().digest().hex() - - sha3_224().digest().hex() +26 - sha3_224().digest().hex() 26 + sha3_224().hexdigest() -27 | sha3_256().digest().hex() | FURB181 [*] Use of hashlib's `.digest().hex()` @@ -156,10 +140,8 @@ FURB181 [*] Use of hashlib's `.digest().hex()` | help: Replace with `.hexdigest()` | -26 | sha3_224().digest().hex() - - sha3_256().digest().hex() +27 - sha3_256().digest().hex() 27 + sha3_256().hexdigest() -28 | sha3_384().digest().hex() | FURB181 [*] Use of hashlib's `.digest().hex()` @@ -174,10 +156,8 @@ FURB181 [*] Use of hashlib's `.digest().hex()` | help: Replace with `.hexdigest()` | -27 | sha3_256().digest().hex() - - sha3_384().digest().hex() +28 - sha3_384().digest().hex() 28 + sha3_384().hexdigest() -29 | sha3_512().digest().hex() | FURB181 [*] Use of hashlib's `.digest().hex()` @@ -192,10 +172,8 @@ FURB181 [*] Use of hashlib's `.digest().hex()` | help: Replace with `.hexdigest()` | -28 | sha3_384().digest().hex() - - sha3_512().digest().hex() +29 - sha3_512().digest().hex() 29 + sha3_512().hexdigest() -30 | sha512().digest().hex() | FURB181 [*] Use of hashlib's `.digest().hex()` @@ -210,10 +188,8 @@ FURB181 [*] Use of hashlib's `.digest().hex()` | help: Replace with `.hexdigest()` | -29 | sha3_512().digest().hex() - - sha512().digest().hex() +30 - sha512().digest().hex() 30 + sha512().hexdigest() -31 | shake_128().digest(10).hex() | FURB181 Use of hashlib's `.digest().hex()` @@ -251,10 +227,8 @@ FURB181 [*] Use of hashlib's `.digest().hex()` | help: Replace with `.hexdigest()` | -33 | - - hashlib.sha256().digest().hex() +34 - hashlib.sha256().digest().hex() 34 + hashlib.sha256().hexdigest() -35 | | FURB181 [*] Use of hashlib's `.digest().hex()` @@ -269,10 +243,8 @@ FURB181 [*] Use of hashlib's `.digest().hex()` | help: Replace with `.hexdigest()` | -35 | - - sha256(b"text").digest().hex() +36 - sha256(b"text").digest().hex() 36 + sha256(b"text").hexdigest() -37 | | FURB181 [*] Use of hashlib's `.digest().hex()` @@ -287,10 +259,8 @@ FURB181 [*] Use of hashlib's `.digest().hex()` | help: Replace with `.hexdigest()` | -37 | - - hash_algo().digest().hex() +38 - hash_algo().digest().hex() 38 + hash_algo().hexdigest() -39 | | FURB181 [*] Use of hashlib's `.digest().hex()` @@ -307,13 +277,11 @@ FURB181 [*] Use of hashlib's `.digest().hex()` | help: Replace with `.hexdigest()` | -60 | hashed = ( - - sha512(b"some data") - - .digest( - - # text - - ) - - .hex() +61 - sha512(b"some data") +62 - .digest( +63 - # text +64 - ) +65 - .hex() 61 + sha512(b"some data").hexdigest() -62 | ) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB187_FURB187.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB187_FURB187.py.snap index 24f1a54ecc1f4..5d5056de0f6ed 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB187_FURB187.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB187_FURB187.py.snap @@ -10,10 +10,8 @@ FURB187 [*] Use of assignment of `reversed` on list `l` | ^^^^^^^^^^^^^^^ help: Replace with `l.reverse()` | -5 | l = [] - - l = reversed(l) +6 - l = reversed(l) 6 + l.reverse() -7 | | note: This is an unsafe fix and may change runtime behavior @@ -26,10 +24,8 @@ FURB187 [*] Use of assignment of `reversed` on list `l` | ^^^^^^^^^^^^^^^^^^^^^ help: Replace with `l.reverse()` | -10 | l = [] - - l = list(reversed(l)) +11 - l = list(reversed(l)) 11 + l.reverse() -12 | | note: This is an unsafe fix and may change runtime behavior @@ -42,9 +38,7 @@ FURB187 [*] Use of assignment of `reversed` on list `l` | ^^^^^^^^^^^ help: Replace with `l.reverse()` | -15 | l = [] - - l = l[::-1] +16 - l = l[::-1] 16 + l.reverse() -17 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB188_FURB188.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB188_FURB188.py.snap index 67c26ad968e9c..5e834e5b556d6 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB188_FURB188.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB188_FURB188.py.snap @@ -13,11 +13,9 @@ FURB188 [*] Prefer `str.removesuffix()` over conditionally replacing with slice. | help: Use removesuffix instead of assignment conditional upon endswith. | -6 | def remove_extension_via_slice(filename: str) -> str: - - if filename.endswith(".txt"): - - filename = filename[:-4] +7 - if filename.endswith(".txt"): +8 - filename = filename[:-4] 7 + filename = filename.removesuffix(".txt") -8 | | FURB188 [*] Prefer `str.removesuffix()` over conditionally replacing with slice. @@ -32,11 +30,9 @@ FURB188 [*] Prefer `str.removesuffix()` over conditionally replacing with slice. | help: Use removesuffix instead of assignment conditional upon endswith. | -13 | def remove_extension_via_slice_len(filename: str, extension: str) -> str: - - if filename.endswith(extension): - - filename = filename[:-len(extension)] +14 - if filename.endswith(extension): +15 - filename = filename[:-len(extension)] 14 + filename = filename.removesuffix(extension) -15 | | FURB188 [*] Prefer `str.removesuffix()` over conditionally replacing with slice. @@ -47,10 +43,8 @@ FURB188 [*] Prefer `str.removesuffix()` over conditionally replacing with slice. | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use removesuffix instead of ternary expression conditional upon endswith. | -20 | def remove_extension_via_ternary(filename: str) -> str: - - return filename[:-4] if filename.endswith(".txt") else filename +21 - return filename[:-4] if filename.endswith(".txt") else filename 21 + return filename.removesuffix(".txt") -22 | | FURB188 [*] Prefer `str.removesuffix()` over conditionally replacing with slice. @@ -61,10 +55,8 @@ FURB188 [*] Prefer `str.removesuffix()` over conditionally replacing with slice. | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use removesuffix instead of ternary expression conditional upon endswith. | -24 | def remove_extension_via_ternary_with_len(filename: str, extension: str) -> str: - - return filename[:-len(extension)] if filename.endswith(extension) else filename +25 - return filename[:-len(extension)] if filename.endswith(extension) else filename 25 + return filename.removesuffix(extension) -26 | | FURB188 [*] Prefer `str.removeprefix()` over conditionally replacing with slice. @@ -75,10 +67,8 @@ FURB188 [*] Prefer `str.removeprefix()` over conditionally replacing with slice. | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use removeprefix instead of ternary expression conditional upon startswith. | -28 | def remove_prefix(filename: str) -> str: - - return filename[4:] if filename.startswith("abc-") else filename +29 - return filename[4:] if filename.startswith("abc-") else filename 29 + return filename.removeprefix("abc-") -30 | | FURB188 [*] Prefer `str.removeprefix()` over conditionally replacing with slice. @@ -89,10 +79,8 @@ FURB188 [*] Prefer `str.removeprefix()` over conditionally replacing with slice. | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use removeprefix instead of ternary expression conditional upon startswith. | -32 | def remove_prefix_via_len(filename: str, prefix: str) -> str: - - return filename[len(prefix):] if filename.startswith(prefix) else filename +33 - return filename[len(prefix):] if filename.startswith(prefix) else filename 33 + return filename.removeprefix(prefix) -34 | | FURB188 [*] Prefer `str.removesuffix()` over conditionally replacing with slice. @@ -107,10 +95,8 @@ FURB188 [*] Prefer `str.removesuffix()` over conditionally replacing with slice. | help: Use removesuffix instead of ternary expression conditional upon endswith. | -145 | - - x = foo.bar.baz[:-len(SUFFIX)] if foo.bar.baz.endswith(SUFFIX) else foo.bar.baz +146 - x = foo.bar.baz[:-len(SUFFIX)] if foo.bar.baz.endswith(SUFFIX) else foo.bar.baz 146 + x = foo.bar.baz.removesuffix(SUFFIX) -147 | | FURB188 [*] Prefer `str.removeprefix()` over conditionally replacing with slice. @@ -124,10 +110,8 @@ FURB188 [*] Prefer `str.removeprefix()` over conditionally replacing with slice. | help: Use removeprefix instead of ternary expression conditional upon startswith. | -148 | def remove_prefix_comparable_literal_expr() -> None: - - return ("abc" "def")[3:] if ("abc" "def").startswith("abc") else "abc" "def" +149 - return ("abc" "def")[3:] if ("abc" "def").startswith("abc") else "abc" "def" 149 + return "abc" "def".removeprefix("abc") -150 | | FURB188 [*] Prefer `str.removesuffix()` over conditionally replacing with slice. @@ -142,10 +126,8 @@ FURB188 [*] Prefer `str.removesuffix()` over conditionally replacing with slice. | help: Use removesuffix instead of ternary expression conditional upon endswith. | -153 | - - return filename[:-builtins_len(extension)] if filename.endswith(extension) else filename +154 - return filename[:-builtins_len(extension)] if filename.endswith(extension) else filename 154 + return filename.removesuffix(extension) -155 | | FURB188 [*] Prefer `str.removeprefix()` over conditionally replacing with slice. @@ -161,11 +143,9 @@ FURB188 [*] Prefer `str.removeprefix()` over conditionally replacing with slice. | help: Use removeprefix instead of assignment conditional upon startswith. | -157 | text = "!x!y!z" - - if text.startswith("!"): - - text = text[1::1] +158 - if text.startswith("!"): +159 - text = text[1::1] 158 + text = text.removeprefix("!") -159 | if text.startswith("!"): | FURB188 [*] Prefer `str.removeprefix()` over conditionally replacing with slice. @@ -181,11 +161,9 @@ FURB188 [*] Prefer `str.removeprefix()` over conditionally replacing with slice. | help: Use removeprefix instead of assignment conditional upon startswith. | -159 | text = text[1::1] - - if text.startswith("!"): - - text = text[1::True] +160 - if text.startswith("!"): +161 - text = text[1::True] 160 + text = text.removeprefix("!") -161 | if text.startswith("!"): | FURB188 [*] Prefer `str.removeprefix()` over conditionally replacing with slice. @@ -200,11 +178,9 @@ FURB188 [*] Prefer `str.removeprefix()` over conditionally replacing with slice. | help: Use removeprefix instead of assignment conditional upon startswith. | -161 | text = text[1::True] - - if text.startswith("!"): - - text = text[1::None] +162 - if text.startswith("!"): +163 - text = text[1::None] 162 + text = text.removeprefix("!") -163 | print(text) | FURB188 [*] Prefer `str.removeprefix()` over conditionally replacing with slice. @@ -217,11 +193,9 @@ FURB188 [*] Prefer `str.removeprefix()` over conditionally replacing with slice. | |_______________________^ help: Use removeprefix instead of assignment conditional upon startswith. | -182 | text = "řetězec" - - if text.startswith("ř"): - - text = text[1:] +183 - if text.startswith("ř"): +184 - text = text[1:] 183 + text = text.removeprefix("ř") -184 | | FURB188 [*] Prefer `str.removeprefix()` over conditionally replacing with slice. @@ -237,11 +211,9 @@ FURB188 [*] Prefer `str.removeprefix()` over conditionally replacing with slice. | help: Use removeprefix instead of assignment conditional upon startswith. | -189 | text = "\ud800\udc00heythere" - - if text.startswith("\ud800\udc00"): - - text = text[2:] +190 - if text.startswith("\ud800\udc00"): +191 - text = text[2:] 190 + text = text.removeprefix("\ud800\udc00") -191 | text = "\U00010000heythere" | FURB188 [*] Prefer `str.removeprefix()` over conditionally replacing with slice. @@ -257,11 +229,9 @@ FURB188 [*] Prefer `str.removeprefix()` over conditionally replacing with slice. | help: Use removeprefix instead of assignment conditional upon startswith. | -192 | text = "\U00010000heythere" - - if text.startswith("\U00010000"): - - text = text[1:] +193 - if text.startswith("\U00010000"): +194 - text = text[1:] 193 + text = text.removeprefix("\U00010000") -194 | | FURB188 [*] Prefer `str.removesuffix()` over conditionally replacing with slice. @@ -276,11 +246,9 @@ FURB188 [*] Prefer `str.removesuffix()` over conditionally replacing with slice. | help: Use removesuffix instead of assignment conditional upon endswith. | -204 | a = "sjdfaskldjfakljklfoo" - - if a.endswith("foo"): - - a = a[: -len("foo")] +205 - if a.endswith("foo"): +206 - a = a[: -len("foo")] 205 + a = a.removesuffix("foo") -206 | print(a) | FURB188 [*] Prefer `str.removesuffix()` over conditionally replacing with slice. @@ -296,11 +264,9 @@ FURB188 [*] Prefer `str.removesuffix()` over conditionally replacing with slice. | help: Use removesuffix instead of ternary expression conditional upon endswith. | -211 | filename = ( - - filename[:-4] # text - - if filename.endswith(".txt") # text - - else filename +212 - filename[:-4] # text +213 - if filename.endswith(".txt") # text +214 - else filename 212 + filename.removesuffix(".txt") -213 | ) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB189_FURB189.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB189_FURB189.py.snap index 2a28e242a13b4..9d7113420c1c7 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB189_FURB189.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB189_FURB189.py.snap @@ -11,15 +11,11 @@ FURB189 [*] Subclassing `dict` can be error prone, use `collections.UserDict` in | help: Replace with `collections.UserDict` | -2 | from enum import Enum, EnumMeta - - from collections import UserList as UL -3 + from collections import UserList as UL, UserDict -4 | --------------------------------------------------------------------------------- + 3 ~ from collections import UserList as UL, UserDict + 4 | + … 16 | # positives - - class D(dict): -17 + class D(UserDict): -18 | pass +17 ~ class D(UserDict): | note: This is an unsafe fix and may change runtime behavior @@ -34,10 +30,11 @@ FURB189 [*] Subclassing `list` can be error prone, use `collections.UserList` in | help: Replace with `collections.UserList` | + 3 ~ from collections import UserList as UL + 4 | + … 19 | - - class L(list): -20 + class L(UL): -21 | pass +20 ~ class L(UL): | note: This is an unsafe fix and may change runtime behavior @@ -52,15 +49,11 @@ FURB189 [*] Subclassing `str` can be error prone, use `collections.UserString` i | help: Replace with `collections.UserString` | -2 | from enum import Enum, EnumMeta - - from collections import UserList as UL -3 + from collections import UserList as UL, UserString -4 | --------------------------------------------------------------------------------- + 3 ~ from collections import UserList as UL, UserString + 4 | + … 22 | - - class S(str): -23 + class S(UserString): -24 | pass +23 ~ class S(UserString): | note: This is an unsafe fix and may change runtime behavior @@ -75,15 +68,11 @@ FURB189 [*] Subclassing `dict` can be error prone, use `collections.UserDict` in | help: Replace with `collections.UserDict` | -2 | from enum import Enum, EnumMeta - - from collections import UserList as UL -3 + from collections import UserList as UL, UserDict -4 | --------------------------------------------------------------------------------- + 3 ~ from collections import UserList as UL, UserDict + 4 | + … 25 | - - class SubscriptDict(dict[str, str]): -26 + class SubscriptDict(UserDict[str, str]): -27 | pass +26 ~ class SubscriptDict(UserDict[str, str]): | note: This is an unsafe fix and may change runtime behavior @@ -98,9 +87,10 @@ FURB189 [*] Subclassing `list` can be error prone, use `collections.UserList` in | help: Replace with `collections.UserList` | + 3 ~ from collections import UserList as UL + 4 | + … 28 | - - class SubscriptList(list[str]): -29 + class SubscriptList(UL[str]): -30 | pass +29 ~ class SubscriptList(UL[str]): | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB192_FURB192.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB192_FURB192.py.snap index b9733ca518caa..1b5507288a7c3 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB192_FURB192.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB192_FURB192.py.snap @@ -13,10 +13,8 @@ FURB192 [*] Prefer `min` over `sorted()` to compute the minimum value in a seque | help: Replace with `min` | -2 | - - sorted(l)[0] +3 - sorted(l)[0] 3 + min(l) -4 | | note: This is an unsafe fix and may change runtime behavior @@ -32,10 +30,8 @@ FURB192 [*] Prefer `max` over `sorted()` to compute the maximum value in a seque | help: Replace with `max` | -4 | - - sorted(l)[-1] +5 - sorted(l)[-1] 5 + max(l) -6 | | note: This is an unsafe fix and may change runtime behavior @@ -51,10 +47,8 @@ FURB192 [*] Prefer `max` over `sorted()` to compute the maximum value in a seque | help: Replace with `max` | -6 | - - sorted(l, reverse=False)[-1] +7 - sorted(l, reverse=False)[-1] 7 + max(l) -8 | | note: This is an unsafe fix and may change runtime behavior @@ -69,12 +63,10 @@ FURB192 [*] Prefer `min` over `sorted()` to compute the minimum value in a seque 11 | sorted(l, key=key_fn)[0] | help: Replace with `min` - | -8 | - - sorted(l, key=lambda x: x)[0] -9 + min(l, key=lambda x: x) -10 | - | + | +9 - sorted(l, key=lambda x: x)[0] +9 + min(l, key=lambda x: x) + | note: This is an unsafe fix and may change runtime behavior FURB192 [*] Prefer `min` over `sorted()` to compute the minimum value in a sequence @@ -89,10 +81,8 @@ FURB192 [*] Prefer `min` over `sorted()` to compute the minimum value in a seque | help: Replace with `min` | -10 | - - sorted(l, key=key_fn)[0] +11 - sorted(l, key=key_fn)[0] 11 + min(l, key=key_fn) -12 | | note: This is an unsafe fix and may change runtime behavior @@ -108,10 +98,8 @@ FURB192 [*] Prefer `min` over `sorted()` to compute the minimum value in a seque | help: Replace with `min` | -12 | - - sorted([1, 2, 3])[0] +13 - sorted([1, 2, 3])[0] 13 + min([1, 2, 3]) -14 | | note: This is an unsafe fix and may change runtime behavior @@ -127,10 +115,8 @@ FURB192 [*] Prefer `min` over `sorted()` to compute the minimum value in a seque | help: Replace with `min` | -16 | - - sorted(l, key=key_fn, reverse=True)[-1] +17 - sorted(l, key=key_fn, reverse=True)[-1] 17 + min(l, key=key_fn) -18 | | note: This is an unsafe fix and may change runtime behavior @@ -146,10 +132,8 @@ FURB192 [*] Prefer `max` over `sorted()` to compute the maximum value in a seque | help: Replace with `max` | -18 | - - sorted(l, reverse=True)[0] +19 - sorted(l, reverse=True)[0] 19 + max(l) -20 | | note: This is an unsafe fix and may change runtime behavior @@ -165,9 +149,7 @@ FURB192 [*] Prefer `min` over `sorted()` to compute the minimum value in a seque | help: Replace with `min` | -20 | - - sorted(l, reverse=True)[-1] +21 - sorted(l, reverse=True)[-1] 21 + min(l) -22 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB192_FURB192_1.py.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB192_FURB192_1.py.snap index 5e5ec280ff19b..3a624c56ac510 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB192_FURB192_1.py.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB192_FURB192_1.py.snap @@ -11,12 +11,10 @@ FURB192 [*] Prefer `min` over `sorted()` to compute the minimum value in a seque 11 | sorted((yield l))[-1] | help: Replace with `min` - | -8 | def f(l, key_fn): - - sorted((yield))[0] -9 + min((yield)) -10 | - | + | +9 - sorted((yield))[0] +9 + min((yield)) + | note: This is an unsafe fix and may change runtime behavior FURB192 [*] Prefer `max` over `sorted()` to compute the maximum value in a sequence @@ -31,10 +29,8 @@ FURB192 [*] Prefer `max` over `sorted()` to compute the maximum value in a seque | help: Replace with `max` | -10 | - - sorted((yield l))[-1] +11 - sorted((yield l))[-1] 11 + max((yield l)) -12 | | note: This is an unsafe fix and may change runtime behavior @@ -50,10 +46,8 @@ FURB192 [*] Prefer `min` over `sorted()` to compute the minimum value in a seque | help: Replace with `min` | -12 | - - sorted((yield), key=key_fn)[0] +13 - sorted((yield), key=key_fn)[0] 13 + min((yield), key=key_fn) -14 | | note: This is an unsafe fix and may change runtime behavior @@ -69,10 +63,8 @@ FURB192 [*] Prefer `min` over `sorted()` to compute the minimum value in a seque | help: Replace with `min` | -14 | - - sorted((yield from l))[0] +15 - sorted((yield from l))[0] 15 + min((yield from l)) -16 | | note: This is an unsafe fix and may change runtime behavior @@ -85,8 +77,7 @@ FURB192 [*] Prefer `min` over `sorted()` to compute the minimum value in a seque | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `min` | -16 | - - sorted((yield), reverse=True)[-1] +17 - sorted((yield), reverse=True)[-1] 17 + min((yield)) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__fstring_number_format_python_311.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__fstring_number_format_python_311.snap index 830f08dc4fe1d..56045dd2e6ee7 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__fstring_number_format_python_311.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__fstring_number_format_python_311.snap @@ -12,12 +12,10 @@ FURB116 [*] Replace `oct` call with `f"{num:o}"` 11 | print(bin(num)[2:]) # FURB116 | help: Replace with `f"{num:o}"` - | -8 | - - print(oct(num)[2:]) # FURB116 -9 + print(f"{num:o}") # FURB116 -10 | print(hex(num)[2:]) # FURB116 - | + | +9 - print(oct(num)[2:]) # FURB116 +9 + print(f"{num:o}") # FURB116 + | note: This is a display-only fix and is likely to be incorrect FURB116 [*] Replace `hex` call with `f"{num:x}"` @@ -30,10 +28,8 @@ FURB116 [*] Replace `hex` call with `f"{num:x}"` | help: Replace with `f"{num:x}"` | -9 | print(oct(num)[2:]) # FURB116 - - print(hex(num)[2:]) # FURB116 +10 - print(hex(num)[2:]) # FURB116 10 + print(f"{num:x}") # FURB116 -11 | print(bin(num)[2:]) # FURB116 | note: This is a display-only fix and is likely to be incorrect @@ -49,10 +45,8 @@ FURB116 [*] Replace `bin` call with `f"{num:b}"` | help: Replace with `f"{num:b}"` | -10 | print(hex(num)[2:]) # FURB116 - - print(bin(num)[2:]) # FURB116 +11 - print(bin(num)[2:]) # FURB116 11 + print(f"{num:b}") # FURB116 -12 | | note: This is a display-only fix and is likely to be incorrect @@ -68,10 +62,8 @@ FURB116 [*] Replace `oct` call with `f"{1337:o}"` | help: Replace with `f"{1337:o}"` | -12 | - - print(oct(1337)[2:]) # FURB116 +13 - print(oct(1337)[2:]) # FURB116 13 + print(f"{1337:o}") # FURB116 -14 | print(hex(1337)[2:]) # FURB116 | FURB116 [*] Replace `hex` call with `f"{1337:x}"` @@ -85,10 +77,8 @@ FURB116 [*] Replace `hex` call with `f"{1337:x}"` | help: Replace with `f"{1337:x}"` | -13 | print(oct(1337)[2:]) # FURB116 - - print(hex(1337)[2:]) # FURB116 +14 - print(hex(1337)[2:]) # FURB116 14 + print(f"{1337:x}") # FURB116 -15 | print(bin(1337)[2:]) # FURB116 | FURB116 [*] Replace `bin` call with `f"{1337:b}"` @@ -102,10 +92,8 @@ FURB116 [*] Replace `bin` call with `f"{1337:b}"` | help: Replace with `f"{1337:b}"` | -14 | print(hex(1337)[2:]) # FURB116 - - print(bin(1337)[2:]) # FURB116 +15 - print(bin(1337)[2:]) # FURB116 15 + print(f"{1337:b}") # FURB116 -16 | print(bin(+1337)[2:]) # FURB116 | FURB116 [*] Replace `bin` call with `f"{+1337:b}"` @@ -120,10 +108,8 @@ FURB116 [*] Replace `bin` call with `f"{+1337:b}"` | help: Replace with `f"{+1337:b}"` | -15 | print(bin(1337)[2:]) # FURB116 - - print(bin(+1337)[2:]) # FURB116 +16 - print(bin(+1337)[2:]) # FURB116 16 + print(f"{+1337:b}") # FURB116 -17 | | FURB116 Replace `bin` call with f-string @@ -160,10 +146,8 @@ FURB116 [*] Replace `bin` call with `f"{d:b}"` | help: Replace with `f"{d:b}"` | -31 | # autofix is display-only - - print(bin(d)[2:]) +32 - print(bin(d)[2:]) 32 + print(f"{d:b}") -33 | # no autofix for Python 3.11 and earlier, as it introduces a syntax error | note: This is a display-only fix and is likely to be incorrect @@ -190,10 +174,8 @@ FURB116 [*] Replace `bin` call with `f"{ {0: 1}[0].numerator:b}"` | help: Replace with `f"{ {0: 1}[0].numerator:b}"` | -36 | # autofix is display-only - - print(bin({0: 1}[0].numerator)[2:]) +37 - print(bin({0: 1}[0].numerator)[2:]) 37 + print(f"{ {0: 1}[0].numerator:b}") -38 | # no autofix for Python 3.11 and earlier, as it introduces a syntax error | note: This is a display-only fix and is likely to be incorrect @@ -231,10 +213,8 @@ FURB116 [*] Replace `bin` call with `f"{-1:b}"` | ^^^^^^^^^^^ help: Replace with `f"{-1:b}"` | -43 | # for negatives numbers autofix is display-only - - print(bin(-1)[2:]) +44 - print(bin(-1)[2:]) 44 + print(f"{-1:b}") -45 | | note: This is a display-only fix and is likely to be incorrect @@ -251,12 +231,10 @@ FURB116 [*] Replace `bin` call with `f"{1337:b}"` | help: Replace with `f"{1337:b}"` | -47 | print( - - bin( - - 1337 - - # text - - )[2:] +48 - bin( +49 - 1337 +50 - # text +51 - )[2:] 48 + f"{1337:b}" -49 | ) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__read_whole_file_newline_python_version_diff.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__read_whole_file_newline_python_version_diff.snap index e659af2632597..1cb4a3a809c69 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__read_whole_file_newline_python_version_diff.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__read_whole_file_newline_python_version_diff.snap @@ -20,12 +20,8 @@ FURB101 [*] `open` and `read` should be replaced by `Path("file.txt").read_text( | help: Replace with `Path("file.txt").read_text(newline="\r\n")` | -3 | # FURB101 (newline is supported in read_text on Python 3.13+) - - with open("file.txt", newline="\r\n") as f: - - x = f.read() 4 + import pathlib -5 + x = pathlib.Path("file.txt").read_text(newline="\r\n") -6 | +5 ~ x = pathlib.Path("file.txt").read_text(newline="\r\n") | @@ -38,18 +34,14 @@ FURB101 [*] `open` and `read` should be replaced by `Path("file.txt").read_text( 9 | x = f.read() | help: Replace with `Path("file.txt").read_text(encoding="utf-8", newline="")` - | -3 | # FURB101 (newline is supported in read_text on Python 3.13+) -4 + import pathlib -5 | with open("file.txt", newline="\r\n") as f: -6 | x = f.read() -7 | -8 | # FURB101 (newline with encoding) - - with open("file.txt", encoding="utf-8", newline="") as f: - - x = f.read() -9 + x = pathlib.Path("file.txt").read_text(encoding="utf-8", newline="") -10 | - | + | +4 + import pathlib +5 | with open("file.txt", newline="\r\n") as f: +6 | x = f.read() +7 | +8 | # FURB101 (newline with encoding) +9 + x = pathlib.Path("file.txt").read_text(encoding="utf-8", newline="") + | FURB101 [*] `open` and `read` should be replaced by `Path("file.txt").read_text(newline=None)` @@ -62,12 +54,10 @@ FURB101 [*] `open` and `read` should be replaced by `Path("file.txt").read_text( | help: Replace with `Path("file.txt").read_text(newline=None)` | -3 | # FURB101 (newline is supported in read_text on Python 3.13+) -4 + import pathlib -5 | with open("file.txt", newline="\r\n") as f: --------------------------------------------------------------------------------- + 4 + import pathlib + 5 | with open("file.txt", newline="\r\n") as f: + 6 | x = f.read() + … 12 | # FURB101 (newline=None is also valid) - - with open("file.txt", newline=None) as f: - - x = f.read() 13 + x = pathlib.Path("file.txt").read_text(newline=None) | diff --git a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__write_whole_file_python_39.snap b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__write_whole_file_python_39.snap index a2c56e2b9e36a..2bd286c36514d 100644 --- a/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__write_whole_file_python_39.snap +++ b/crates/ruff_linter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__write_whole_file_python_39.snap @@ -11,14 +11,12 @@ FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_tex | help: Replace with `Path("file.txt").write_text("test")` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 12 | # FURB103 - - with open("file.txt", "w") as f: - - f.write("test") 13 + pathlib.Path("file.txt").write_text("test") -14 | | FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_bytes(foobar)` @@ -31,14 +29,12 @@ FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_byt | help: Replace with `Path("file.txt").write_bytes(foobar)` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 16 | # FURB103 - - with open("file.txt", "wb") as f: - - f.write(foobar) 17 + pathlib.Path("file.txt").write_bytes(foobar) -18 | | FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_bytes(b"abc")` @@ -51,14 +47,12 @@ FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_byt | help: Replace with `Path("file.txt").write_bytes(b"abc")` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 20 | # FURB103 - - with open("file.txt", mode="wb") as f: - - f.write(b"abc") 21 + pathlib.Path("file.txt").write_bytes(b"abc") -22 | | FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_text(foobar, encoding="utf8")` @@ -71,14 +65,12 @@ FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_tex | help: Replace with `Path("file.txt").write_text(foobar, encoding="utf8")` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 24 | # FURB103 - - with open("file.txt", "w", encoding="utf8") as f: - - f.write(foobar) 25 + pathlib.Path("file.txt").write_text(foobar, encoding="utf8") -26 | | FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_text(foobar, errors="ignore")` @@ -91,14 +83,12 @@ FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_tex | help: Replace with `Path("file.txt").write_text(foobar, errors="ignore")` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 28 | # FURB103 - - with open("file.txt", "w", errors="ignore") as f: - - f.write(foobar) 29 + pathlib.Path("file.txt").write_text(foobar, errors="ignore") -30 | | FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_text(foobar)` @@ -111,14 +101,12 @@ FURB103 [*] `open` and `write` should be replaced by `Path("file.txt").write_tex | help: Replace with `Path("file.txt").write_text(foobar)` | -1 + import pathlib -2 | def foo(): --------------------------------------------------------------------------------- + 1 + import pathlib + 2 | def foo(): + 3 | ... + … 32 | # FURB103 - - with open("file.txt", mode="w") as f: - - f.write(foobar) 33 + pathlib.Path("file.txt").write_text(foobar) -34 | | FURB103 `open` and `write` should be replaced by `Path(foo()).write_bytes(bar())` @@ -176,15 +164,11 @@ FURB103 [*] `open` and `write` should be replaced by `Path("test.json")....` | help: Replace with `Path("test.json")....` | -150 | import json 151 + import pathlib -152 | +152 + 153 | data = {"price": 100} 154 | - - with open("test.json", "wb") as f: - - f.write(json.dumps(data, indent=4).encode("utf-8")) 155 + pathlib.Path("test.json").write_bytes(json.dumps(data, indent=4).encode("utf-8")) -156 | | FURB103 [*] `open` and `write` should be replaced by `Path("tmp_path/pyproject.toml")....` @@ -198,13 +182,15 @@ FURB103 [*] `open` and `write` should be replaced by `Path("tmp_path/pyproject.t | help: Replace with `Path("tmp_path/pyproject.toml")....` | -150 | import json 151 + import pathlib -152 | --------------------------------------------------------------------------------- +152 + +153 | data = {"price": 100} + … 158 | # See: https://github.com/astral-sh/ruff/issues/21381 - - with open("tmp_path/pyproject.toml", "w") as f: - - f.write(dedent( 159 + pathlib.Path("tmp_path/pyproject.toml").write_text(dedent( -160 | """ +160 + """ +161 + [project] +162 + other = 1.234 +163 + """, +164 + )) | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__PY313_RUF036_runtime_evaluated.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__PY313_RUF036_runtime_evaluated.snap index 43cfe4baf5bb9..f8ae6bbab64b0 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__PY313_RUF036_runtime_evaluated.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__PY313_RUF036_runtime_evaluated.snap @@ -10,9 +10,7 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -1 | - - def func(arg: None | int): +2 - def func(arg: None | int): 2 + def func(arg: int | None): -3 | ... | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__PY315_RUF015_RUF015_py315.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__PY315_RUF015_RUF015_py315.py.snap index 79c3527454afe..dae50addd1a04 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__PY315_RUF015_RUF015_py315.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__PY315_RUF015_RUF015_py315.py.snap @@ -12,10 +12,8 @@ RUF015 [*] Prefer `next(*x for x in xs)` over single element slice | help: Replace with `next(*x for x in xs)` | -2 | - - [*x for x in xs][0] +3 - [*x for x in xs][0] 3 + next(*x for x in xs) -4 | list(*x for x in xs)[0] | note: This is an unsafe fix and may change runtime behavior @@ -27,8 +25,7 @@ RUF015 [*] Prefer `next(*x for x in xs)` over single element slice | ^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `next(*x for x in xs)` | -3 | [*x for x in xs][0] - - list(*x for x in xs)[0] +4 - list(*x for x in xs)[0] 4 + next(*x for x in xs) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__PY315_RUF017_RUF017_0.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__PY315_RUF017_RUF017_0.py.snap index 08249804051f7..077fc4c21450e 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__PY315_RUF017_RUF017_0.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__PY315_RUF017_RUF017_0.py.snap @@ -12,10 +12,8 @@ RUF017 [*] Avoid quadratic list summation | help: Replace with a starred list comprehension | -4 | # RUF017 - - sum([x, y], start=[]) +5 - sum([x, y], start=[]) 5 + [*sublist for sublist in [x, y]] -6 | sum([x, y], []) | note: This is an unsafe fix and may change runtime behavior @@ -31,10 +29,8 @@ RUF017 [*] Avoid quadratic list summation | help: Replace with a starred list comprehension | -5 | sum([x, y], start=[]) - - sum([x, y], []) +6 - sum([x, y], []) 6 + [*sublist for sublist in [x, y]] -7 | sum([[1, 2, 3], [4, 5, 6]], start=[]) | note: This is an unsafe fix and may change runtime behavior @@ -50,10 +46,8 @@ RUF017 [*] Avoid quadratic list summation | help: Replace with a starred list comprehension | -6 | sum([x, y], []) - - sum([[1, 2, 3], [4, 5, 6]], start=[]) +7 - sum([[1, 2, 3], [4, 5, 6]], start=[]) 7 + [*sublist for sublist in [[1, 2, 3], [4, 5, 6]]] -8 | sum([[1, 2, 3], [4, 5, 6]], []) | note: This is an unsafe fix and may change runtime behavior @@ -69,10 +63,8 @@ RUF017 [*] Avoid quadratic list summation | help: Replace with a starred list comprehension | -7 | sum([[1, 2, 3], [4, 5, 6]], start=[]) - - sum([[1, 2, 3], [4, 5, 6]], []) +8 - sum([[1, 2, 3], [4, 5, 6]], []) 8 + [*sublist for sublist in [[1, 2, 3], [4, 5, 6]]] -9 | sum([[1, 2, 3], [4, 5, 6]], | note: This is an unsafe fix and may change runtime behavior @@ -89,11 +81,9 @@ RUF017 [*] Avoid quadratic list summation | help: Replace with a starred list comprehension | -8 | sum([[1, 2, 3], [4, 5, 6]], []) - - sum([[1, 2, 3], [4, 5, 6]], - - []) -9 + [*sublist for sublist in [[1, 2, 3], [4, 5, 6]]] -10 | + 9 - sum([[1, 2, 3], [4, 5, 6]], +10 - []) + 9 + [*sublist for sublist in [[1, 2, 3], [4, 5, 6]]] | note: This is an unsafe fix and may change runtime behavior @@ -106,10 +96,8 @@ RUF017 [*] Avoid quadratic list summation | ^^^^^^^^^^^^^^^ help: Replace with a starred list comprehension | -20 | - - sum([x, y], []) +21 - sum([x, y], []) 21 + [*sublist for sublist in [x, y]] -22 | | note: This is an unsafe fix and may change runtime behavior @@ -122,8 +110,7 @@ RUF017 [*] Avoid quadratic list summation | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with a starred list comprehension | -25 | def func(): - - sum((factor.dims for factor in bases), []) +26 - sum((factor.dims for factor in bases), []) 26 + [*sublist for sublist in (factor.dims for factor in bases)] | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__PY39_RUF013_RUF013_0.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__PY39_RUF013_RUF013_0.py.snap index b2446e9e39a64..b405a99996c54 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__PY39_RUF013_RUF013_0.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__PY39_RUF013_RUF013_0.py.snap @@ -10,10 +10,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | + 1 ~ from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 2 | + … 19 | - - def f(arg: int = None): # RUF013 -20 + def f(arg: Optional[int] = None): # RUF013 -21 | pass +20 ~ def f(arg: Optional[int] = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -26,10 +27,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | + 1 ~ from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 2 | + … 23 | - - def f(arg: str = None): # RUF013 -24 + def f(arg: Optional[str] = None): # RUF013 -25 | pass +24 ~ def f(arg: Optional[str] = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -42,10 +44,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | + 1 ~ from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 2 | + … 27 | - - def f(arg: Tuple[str] = None): # RUF013 -28 + def f(arg: Optional[Tuple[str]] = None): # RUF013 -29 | pass +28 ~ def f(arg: Optional[Tuple[str]] = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -58,10 +61,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | + 1 ~ from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 2 | + … 57 | - - def f(arg: Union = None): # RUF013 -58 + def f(arg: Optional[Union] = None): # RUF013 -59 | pass +58 ~ def f(arg: Optional[Union] = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -74,10 +78,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | + 1 ~ from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 2 | + … 61 | - - def f(arg: Union[int] = None): # RUF013 -62 + def f(arg: Optional[Union[int]] = None): # RUF013 -63 | pass +62 ~ def f(arg: Optional[Union[int]] = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -90,10 +95,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | + 1 ~ from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 2 | + … 65 | - - def f(arg: Union[int, str] = None): # RUF013 -66 + def f(arg: Optional[Union[int, str]] = None): # RUF013 -67 | pass +66 ~ def f(arg: Optional[Union[int, str]] = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -106,10 +112,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | + 1 ~ from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 2 | + … 84 | - - def f(arg: int | float = None): # RUF013 -85 + def f(arg: Optional[int | float] = None): # RUF013 -86 | pass +85 ~ def f(arg: Optional[int | float] = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -122,10 +129,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | + 1 ~ from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 2 | + … 88 | - - def f(arg: int | float | str | bytes = None): # RUF013 -89 + def f(arg: Optional[int | float | str | bytes] = None): # RUF013 -90 | pass +89 ~ def f(arg: Optional[int | float | str | bytes] = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -138,10 +146,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | + 1 ~ from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 2 | + … 107 | - - def f(arg: Literal[1] = None): # RUF013 -108 + def f(arg: Optional[Literal[1]] = None): # RUF013 -109 | pass +108 ~ def f(arg: Optional[Literal[1]] = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -154,10 +163,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | + 1 ~ from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 2 | + … 111 | - - def f(arg: Literal[1, "foo"] = None): # RUF013 -112 + def f(arg: Optional[Literal[1, "foo"]] = None): # RUF013 -113 | pass +112 ~ def f(arg: Optional[Literal[1, "foo"]] = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -170,10 +180,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | + 1 ~ from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 2 | + … 130 | - - def f(arg: Annotated[int, ...] = None): # RUF013 -131 + def f(arg: Annotated[Optional[int], ...] = None): # RUF013 -132 | pass +131 ~ def f(arg: Annotated[Optional[int], ...] = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -186,10 +197,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | + 1 ~ from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 2 | + … 134 | - - def f(arg: Annotated[Annotated[int | str, ...], ...] = None): # RUF013 -135 + def f(arg: Annotated[Annotated[Optional[int | str], ...], ...] = None): # RUF013 -136 | pass +135 ~ def f(arg: Annotated[Annotated[Optional[int | str], ...], ...] = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -204,10 +216,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | + 1 ~ from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 2 | + … 150 | def f( - - arg1: int = None, # RUF013 -151 + arg1: Optional[int] = None, # RUF013 -152 | arg2: Union[int, float] = None, # RUF013 +151 ~ arg1: Optional[int] = None, # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -223,10 +236,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | + 1 ~ from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 2 | + … 151 | arg1: int = None, # RUF013 - - arg2: Union[int, float] = None, # RUF013 -152 + arg2: Optional[Union[int, float]] = None, # RUF013 -153 | arg3: Literal[1, 2, 3] = None, # RUF013 +152 ~ arg2: Optional[Union[int, float]] = None, # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -242,10 +256,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | + 1 ~ from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 2 | + … 152 | arg2: Union[int, float] = None, # RUF013 - - arg3: Literal[1, 2, 3] = None, # RUF013 -153 + arg3: Optional[Literal[1, 2, 3]] = None, # RUF013 -154 | ): +153 ~ arg3: Optional[Literal[1, 2, 3]] = None, # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -258,10 +273,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | + 1 ~ from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 2 | + … 180 | - - def f(arg: Union[Annotated[int, ...], Union[str, bytes]] = None): # RUF013 -181 + def f(arg: Optional[Union[Annotated[int, ...], Union[str, bytes]]] = None): # RUF013 -182 | pass +181 ~ def f(arg: Optional[Union[Annotated[int, ...], Union[str, bytes]]] = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -274,10 +290,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | + 1 ~ from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 2 | + … 187 | - - def f(arg: "int" = None): # RUF013 -188 + def f(arg: "Optional[int]" = None): # RUF013 -189 | pass +188 ~ def f(arg: "Optional[int]" = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -290,10 +307,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | + 1 ~ from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 2 | + … 191 | - - def f(arg: "str" = None): # RUF013 -192 + def f(arg: "Optional[str]" = None): # RUF013 -193 | pass +192 ~ def f(arg: "Optional[str]" = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -315,9 +333,10 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | + 1 ~ from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 2 | + … 203 | - - def f(arg: Union["int", "str"] = None): # RUF013 -204 + def f(arg: Optional[Union["int", "str"]] = None): # RUF013 -205 | pass +204 ~ def f(arg: Optional[Union["int", "str"]] = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__PY39_RUF013_RUF013_1.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__PY39_RUF013_RUF013_1.py.snap index 13a992a9fa474..7d2a96ee3dd5e 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__PY39_RUF013_RUF013_1.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__PY39_RUF013_RUF013_1.py.snap @@ -10,10 +10,7 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | -3 | - - def f(arg: int = None): # RUF013 4 + from typing import Optional -5 + def f(arg: Optional[int] = None): # RUF013 -6 | pass +5 ~ def f(arg: Optional[int] = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF005_RUF005.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF005_RUF005.py.snap index f3c41721a4bd0..12c1c65b9c314 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF005_RUF005.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF005_RUF005.py.snap @@ -55,10 +55,8 @@ RUF005 [*] Consider `[1, 2, 3, *foo]` instead of concatenation | help: Replace with `[1, 2, 3, *foo]` | -38 | foo = [4, 5, 6] - - bar = [1, 2, 3] + foo +39 - bar = [1, 2, 3] + foo 39 + bar = [1, 2, 3, *foo] -40 | zoob = tuple(bar) | note: This is an unsafe fix and may change runtime behavior @@ -74,10 +72,8 @@ RUF005 [*] Consider `(7, 8, 9, *zoob)` instead of concatenation | help: Replace with `(7, 8, 9, *zoob)` | -40 | zoob = tuple(bar) - - quux = (7, 8, 9) + zoob +41 - quux = (7, 8, 9) + zoob 41 + quux = (7, 8, 9, *zoob) -42 | spam = quux + (10, 11, 12) | note: This is an unsafe fix and may change runtime behavior @@ -93,10 +89,8 @@ RUF005 [*] Consider `(*quux, 10, 11, 12)` instead of concatenation | help: Replace with `(*quux, 10, 11, 12)` | -41 | quux = (7, 8, 9) + zoob - - spam = quux + (10, 11, 12) +42 - spam = quux + (10, 11, 12) 42 + spam = (*quux, 10, 11, 12) -43 | spom = list(spam) | note: This is an unsafe fix and may change runtime behavior @@ -112,10 +106,8 @@ RUF005 [*] Consider `[*spom, 13, 14, 15]` instead of concatenation | help: Replace with `[*spom, 13, 14, 15]` | -43 | spom = list(spam) - - eggs = spom + [13, 14, 15] +44 - eggs = spom + [13, 14, 15] 44 + eggs = [*spom, 13, 14, 15] -45 | elatement = ("we all say",) + yay() | note: This is an unsafe fix and may change runtime behavior @@ -131,10 +123,8 @@ RUF005 [*] Consider `("we all say", *yay())` instead of concatenation | help: Replace with `("we all say", *yay())` | -44 | eggs = spom + [13, 14, 15] - - elatement = ("we all say",) + yay() +45 - elatement = ("we all say",) + yay() 45 + elatement = ("we all say", *yay()) -46 | excitement = ("we all think",) + Fun().yay() | note: This is an unsafe fix and may change runtime behavior @@ -149,10 +139,8 @@ RUF005 [*] Consider `("we all think", *Fun().yay())` instead of concatenation | help: Replace with `("we all think", *Fun().yay())` | -45 | elatement = ("we all say",) + yay() - - excitement = ("we all think",) + Fun().yay() +46 - excitement = ("we all think",) + Fun().yay() 46 + excitement = ("we all think", *Fun().yay()) -47 | astonishment = ("we all feel",) + Fun.words | note: This is an unsafe fix and may change runtime behavior @@ -168,10 +156,8 @@ RUF005 [*] Consider `("we all feel", *Fun.words)` instead of concatenation | help: Replace with `("we all feel", *Fun.words)` | -46 | excitement = ("we all think",) + Fun().yay() - - astonishment = ("we all feel",) + Fun.words +47 - astonishment = ("we all feel",) + Fun.words 47 + astonishment = ("we all feel", *Fun.words) -48 | | note: This is an unsafe fix and may change runtime behavior @@ -187,10 +173,8 @@ RUF005 [*] Consider iterable unpacking instead of concatenation | help: Replace with iterable unpacking | -48 | - - chain = ["a", "b", "c"] + eggs + list(("yes", "no", "pants") + zoob) +49 - chain = ["a", "b", "c"] + eggs + list(("yes", "no", "pants") + zoob) 49 + chain = ["a", "b", "c", *eggs, *list(("yes", "no", "pants") + zoob)] -50 | | note: This is an unsafe fix and may change runtime behavior @@ -206,10 +190,8 @@ RUF005 [*] Consider `("yes", "no", "pants", *zoob)` instead of concatenation | help: Replace with `("yes", "no", "pants", *zoob)` | -48 | - - chain = ["a", "b", "c"] + eggs + list(("yes", "no", "pants") + zoob) +49 - chain = ["a", "b", "c"] + eggs + list(("yes", "no", "pants") + zoob) 49 + chain = ["a", "b", "c"] + eggs + list(("yes", "no", "pants", *zoob)) -50 | | note: This is an unsafe fix and may change runtime behavior @@ -225,10 +207,8 @@ RUF005 [*] Consider `(*zoob,)` instead of concatenation | help: Replace with `(*zoob,)` | -50 | - - baz = () + zoob +51 - baz = () + zoob 51 + baz = (*zoob,) -52 | | note: This is an unsafe fix and may change runtime behavior @@ -245,11 +225,9 @@ RUF005 [*] Consider `[*foo]` instead of concatenation | help: Replace with `[*foo]` | -52 | - - [] + foo + [ - - ] +53 - [] + foo + [ +54 - ] 53 + [*foo] -54 | | note: This is an unsafe fix and may change runtime behavior @@ -265,10 +243,8 @@ RUF005 [*] Consider `[sys.executable, "-m", "pylint", *args, path]` instead of c | help: Replace with `[sys.executable, "-m", "pylint", *args, path]` | -55 | - - pylint_call = [sys.executable, "-m", "pylint"] + args + [path] +56 - pylint_call = [sys.executable, "-m", "pylint"] + args + [path] 56 + pylint_call = [sys.executable, "-m", "pylint", *args, path] -57 | pylint_call_tuple = (sys.executable, "-m", "pylint") + args + (path, path2) | note: This is an unsafe fix and may change runtime behavior @@ -282,10 +258,8 @@ RUF005 [*] Consider iterable unpacking instead of concatenation | help: Replace with iterable unpacking | -56 | pylint_call = [sys.executable, "-m", "pylint"] + args + [path] - - pylint_call_tuple = (sys.executable, "-m", "pylint") + args + (path, path2) +57 - pylint_call_tuple = (sys.executable, "-m", "pylint") + args + (path, path2) 57 + pylint_call_tuple = (sys.executable, "-m", "pylint", *args, path, path2) -58 | b = a + [2, 3] + [4] | note: This is an unsafe fix and may change runtime behavior @@ -301,10 +275,8 @@ RUF005 [*] Consider `[*a, 2, 3, 4]` instead of concatenation | help: Replace with `[*a, 2, 3, 4]` | -57 | pylint_call_tuple = (sys.executable, "-m", "pylint") + args + (path, path2) - - b = a + [2, 3] + [4] +58 - b = a + [2, 3] + [4] 58 + b = [*a, 2, 3, 4] -59 | | note: This is an unsafe fix and may change runtime behavior @@ -319,9 +291,7 @@ RUF005 [*] Consider `[*a(), 'b']` instead of concatenation | help: Replace with `[*a(), 'b']` | -60 | # Uses the non-preferred quote style, which should be retained. - - f"{a() + ['b']}" +61 - f"{a() + ['b']}" 61 + f"{[*a(), 'b']}" -62 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF005_RUF005_slices.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF005_RUF005_slices.py.snap index c5155871ed491..b16f3c68865dd 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF005_RUF005_slices.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF005_RUF005_slices.py.snap @@ -12,10 +12,8 @@ RUF005 [*] Consider `[1, 2, 3, *foo]` instead of concatenation | help: Replace with `[1, 2, 3, *foo]` | -1 | foo = [4, 5, 6] - - bar = [1, 2, 3] + foo +2 - bar = [1, 2, 3] + foo 2 + bar = [1, 2, 3, *foo] -3 | slicing1 = foo[:1] + [7, 8, 9] | note: This is an unsafe fix and may change runtime behavior @@ -31,10 +29,8 @@ RUF005 [*] Consider `[*foo[:1], 7, 8, 9]` instead of concatenation | help: Replace with `[*foo[:1], 7, 8, 9]` | -2 | bar = [1, 2, 3] + foo - - slicing1 = foo[:1] + [7, 8, 9] +3 - slicing1 = foo[:1] + [7, 8, 9] 3 + slicing1 = [*foo[:1], 7, 8, 9] -4 | slicing2 = [7, 8, 9] + bar[1:] | note: This is an unsafe fix and may change runtime behavior @@ -50,10 +46,8 @@ RUF005 [*] Consider `[7, 8, 9, *bar[1:]]` instead of concatenation | help: Replace with `[7, 8, 9, *bar[1:]]` | -3 | slicing1 = foo[:1] + [7, 8, 9] - - slicing2 = [7, 8, 9] + bar[1:] +4 - slicing2 = [7, 8, 9] + bar[1:] 4 + slicing2 = [7, 8, 9, *bar[1:]] -5 | slicing3 = foo[:1] + [7, 8, 9] + bar[1:] | note: This is an unsafe fix and may change runtime behavior @@ -68,9 +62,7 @@ RUF005 [*] Consider `[*foo[:1], 7, 8, 9, *bar[1:]]` instead of concatenation | help: Replace with `[*foo[:1], 7, 8, 9, *bar[1:]]` | -4 | slicing2 = [7, 8, 9] + bar[1:] - - slicing3 = foo[:1] + [7, 8, 9] + bar[1:] +5 - slicing3 = foo[:1] + [7, 8, 9] + bar[1:] 5 + slicing3 = [*foo[:1], 7, 8, 9, *bar[1:]] -6 | indexing = foo[0] + [7, 8, 9] + bar[1] # Not changed; looks a little suspect for concatenation. | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF007_RUF007.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF007_RUF007.py.snap index df6aeed6fe58d..c455e32c24643 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF007_RUF007.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF007_RUF007.py.snap @@ -12,13 +12,12 @@ RUF007 [*] Prefer `itertools.pairwise()` over `zip()` when iterating over succes | help: Replace `zip()` with `itertools.pairwise()` | -1 + import itertools -2 | input = [1, 2, 3] --------------------------------------------------------------------------------- + 1 + import itertools + 2 | input = [1, 2, 3] + 3 | otherInput = [2, 3, 4] + … 16 | # Errors - - zip(input, input[1:]) 17 + itertools.pairwise(input) -18 | zip(input, input[1::1]) | note: This is an unsafe fix and may change runtime behavior @@ -34,13 +33,12 @@ RUF007 [*] Prefer `itertools.pairwise()` over `zip()` when iterating over succes | help: Replace `zip()` with `itertools.pairwise()` | -1 + import itertools -2 | input = [1, 2, 3] --------------------------------------------------------------------------------- + 1 + import itertools + 2 | input = [1, 2, 3] + 3 | otherInput = [2, 3, 4] + … 17 | zip(input, input[1:]) - - zip(input, input[1::1]) 18 + itertools.pairwise(input) -19 | zip(input[:-1], input[1:]) | note: This is an unsafe fix and may change runtime behavior @@ -56,13 +54,12 @@ RUF007 [*] Prefer `itertools.pairwise()` over `zip()` when iterating over succes | help: Replace `zip()` with `itertools.pairwise()` | -1 + import itertools -2 | input = [1, 2, 3] --------------------------------------------------------------------------------- + 1 + import itertools + 2 | input = [1, 2, 3] + 3 | otherInput = [2, 3, 4] + … 18 | zip(input, input[1::1]) - - zip(input[:-1], input[1:]) 19 + itertools.pairwise(input) -20 | zip(input[1:], input[2:]) | note: This is an unsafe fix and may change runtime behavior @@ -78,13 +75,12 @@ RUF007 [*] Prefer `itertools.pairwise()` over `zip()` when iterating over succes | help: Replace `zip()` with `itertools.pairwise()` | -1 + import itertools -2 | input = [1, 2, 3] --------------------------------------------------------------------------------- + 1 + import itertools + 2 | input = [1, 2, 3] + 3 | otherInput = [2, 3, 4] + … 19 | zip(input[:-1], input[1:]) - - zip(input[1:], input[2:]) 20 + itertools.pairwise(input) -21 | zip(input[1:-1], input[2:]) | note: This is an unsafe fix and may change runtime behavior @@ -100,13 +96,12 @@ RUF007 [*] Prefer `itertools.pairwise()` over `zip()` when iterating over succes | help: Replace `zip()` with `itertools.pairwise()` | -1 + import itertools -2 | input = [1, 2, 3] --------------------------------------------------------------------------------- + 1 + import itertools + 2 | input = [1, 2, 3] + 3 | otherInput = [2, 3, 4] + … 20 | zip(input[1:], input[2:]) - - zip(input[1:-1], input[2:]) 21 + itertools.pairwise(input) -22 | list(zip(input, input[1:])) | note: This is an unsafe fix and may change runtime behavior @@ -122,13 +117,12 @@ RUF007 [*] Prefer `itertools.pairwise()` over `zip()` when iterating over succes | help: Replace `zip()` with `itertools.pairwise()` | -1 + import itertools -2 | input = [1, 2, 3] --------------------------------------------------------------------------------- + 1 + import itertools + 2 | input = [1, 2, 3] + 3 | otherInput = [2, 3, 4] + … 21 | zip(input[1:-1], input[2:]) - - list(zip(input, input[1:])) -22 + list(itertools.pairwise(input)) -23 | list(zip(input[:-1], input[1:])) +22 ~ list(itertools.pairwise(input)) | note: This is an unsafe fix and may change runtime behavior @@ -144,13 +138,12 @@ RUF007 [*] Prefer `itertools.pairwise()` over `zip()` when iterating over succes | help: Replace `zip()` with `itertools.pairwise()` | -1 + import itertools -2 | input = [1, 2, 3] --------------------------------------------------------------------------------- + 1 + import itertools + 2 | input = [1, 2, 3] + 3 | otherInput = [2, 3, 4] + … 22 | list(zip(input, input[1:])) - - list(zip(input[:-1], input[1:])) -23 + list(itertools.pairwise(input)) -24 | zip(foo[:-1], foo[1:], strict=True) +23 ~ list(itertools.pairwise(input)) | note: This is an unsafe fix and may change runtime behavior @@ -166,13 +159,12 @@ RUF007 [*] Prefer `itertools.pairwise()` over `zip()` when iterating over succes | help: Replace `zip()` with `itertools.pairwise()` | -1 + import itertools -2 | input = [1, 2, 3] --------------------------------------------------------------------------------- + 1 + import itertools + 2 | input = [1, 2, 3] + 3 | otherInput = [2, 3, 4] + … 23 | list(zip(input[:-1], input[1:])) - - zip(foo[:-1], foo[1:], strict=True) 24 + itertools.pairwise(foo) -25 | zip(foo[:-1], foo[1:], strict=False) | note: This is an unsafe fix and may change runtime behavior @@ -187,13 +179,12 @@ RUF007 [*] Prefer `itertools.pairwise()` over `zip()` when iterating over succes | help: Replace `zip()` with `itertools.pairwise()` | -1 + import itertools -2 | input = [1, 2, 3] --------------------------------------------------------------------------------- + 1 + import itertools + 2 | input = [1, 2, 3] + 3 | otherInput = [2, 3, 4] + … 24 | zip(foo[:-1], foo[1:], strict=True) - - zip(foo[:-1], foo[1:], strict=False) 25 + itertools.pairwise(foo) -26 | zip(foo[:-1], foo[1:], strict=bool(foo)) | note: This is an unsafe fix and may change runtime behavior @@ -206,11 +197,11 @@ RUF007 [*] Prefer `itertools.pairwise()` over `zip()` when iterating over succes | ^^^ help: Replace `zip()` with `itertools.pairwise()` | -1 + import itertools -2 | input = [1, 2, 3] --------------------------------------------------------------------------------- + 1 + import itertools + 2 | input = [1, 2, 3] + 3 | otherInput = [2, 3, 4] + … 25 | zip(foo[:-1], foo[1:], strict=False) - - zip(foo[:-1], foo[1:], strict=bool(foo)) 26 + itertools.pairwise(foo) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF010_RUF010.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF010_RUF010.py.snap index a2064e5cc93c7..15a89ff3cae97 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF010_RUF010.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF010_RUF010.py.snap @@ -10,12 +10,10 @@ RUF010 [*] Use explicit conversion flag 11 | f"{str(d['a'])}, {repr(d['b'])}, {ascii(d['c'])}" # RUF010 | help: Replace with conversion flag - | -8 | - - f"{str(bla)}, {repr(bla)}, {ascii(bla)}" # RUF010 -9 + f"{bla!s}, {repr(bla)}, {ascii(bla)}" # RUF010 -10 | - | + | +9 - f"{str(bla)}, {repr(bla)}, {ascii(bla)}" # RUF010 +9 + f"{bla!s}, {repr(bla)}, {ascii(bla)}" # RUF010 + | RUF010 [*] Use explicit conversion flag --> RUF010.py:9:16 @@ -26,12 +24,10 @@ RUF010 [*] Use explicit conversion flag 11 | f"{str(d['a'])}, {repr(d['b'])}, {ascii(d['c'])}" # RUF010 | help: Replace with conversion flag - | -8 | - - f"{str(bla)}, {repr(bla)}, {ascii(bla)}" # RUF010 -9 + f"{str(bla)}, {bla!r}, {ascii(bla)}" # RUF010 -10 | - | + | +9 - f"{str(bla)}, {repr(bla)}, {ascii(bla)}" # RUF010 +9 + f"{str(bla)}, {bla!r}, {ascii(bla)}" # RUF010 + | RUF010 [*] Use explicit conversion flag --> RUF010.py:9:29 @@ -42,12 +38,10 @@ RUF010 [*] Use explicit conversion flag 11 | f"{str(d['a'])}, {repr(d['b'])}, {ascii(d['c'])}" # RUF010 | help: Replace with conversion flag - | -8 | - - f"{str(bla)}, {repr(bla)}, {ascii(bla)}" # RUF010 -9 + f"{str(bla)}, {repr(bla)}, {bla!a}" # RUF010 -10 | - | + | +9 - f"{str(bla)}, {repr(bla)}, {ascii(bla)}" # RUF010 +9 + f"{str(bla)}, {repr(bla)}, {bla!a}" # RUF010 + | RUF010 [*] Use explicit conversion flag --> RUF010.py:11:4 @@ -61,10 +55,8 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -10 | - - f"{str(d['a'])}, {repr(d['b'])}, {ascii(d['c'])}" # RUF010 +11 - f"{str(d['a'])}, {repr(d['b'])}, {ascii(d['c'])}" # RUF010 11 + f"{d['a']!s}, {repr(d['b'])}, {ascii(d['c'])}" # RUF010 -12 | | RUF010 [*] Use explicit conversion flag @@ -79,10 +71,8 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -10 | - - f"{str(d['a'])}, {repr(d['b'])}, {ascii(d['c'])}" # RUF010 +11 - f"{str(d['a'])}, {repr(d['b'])}, {ascii(d['c'])}" # RUF010 11 + f"{str(d['a'])}, {d['b']!r}, {ascii(d['c'])}" # RUF010 -12 | | RUF010 [*] Use explicit conversion flag @@ -97,10 +87,8 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -10 | - - f"{str(d['a'])}, {repr(d['b'])}, {ascii(d['c'])}" # RUF010 +11 - f"{str(d['a'])}, {repr(d['b'])}, {ascii(d['c'])}" # RUF010 11 + f"{str(d['a'])}, {repr(d['b'])}, {d['c']!a}" # RUF010 -12 | | RUF010 [*] Use explicit conversion flag @@ -115,10 +103,8 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -12 | - - f"{(str(bla))}, {(repr(bla))}, {(ascii(bla))}" # RUF010 +13 - f"{(str(bla))}, {(repr(bla))}, {(ascii(bla))}" # RUF010 13 + f"{bla!s}, {(repr(bla))}, {(ascii(bla))}" # RUF010 -14 | | RUF010 [*] Use explicit conversion flag @@ -133,10 +119,8 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -12 | - - f"{(str(bla))}, {(repr(bla))}, {(ascii(bla))}" # RUF010 +13 - f"{(str(bla))}, {(repr(bla))}, {(ascii(bla))}" # RUF010 13 + f"{(str(bla))}, {bla!r}, {(ascii(bla))}" # RUF010 -14 | | RUF010 [*] Use explicit conversion flag @@ -151,10 +135,8 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -12 | - - f"{(str(bla))}, {(repr(bla))}, {(ascii(bla))}" # RUF010 +13 - f"{(str(bla))}, {(repr(bla))}, {(ascii(bla))}" # RUF010 13 + f"{(str(bla))}, {(repr(bla))}, {bla!a}" # RUF010 -14 | | RUF010 [*] Use explicit conversion flag @@ -169,10 +151,8 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -14 | - - f"{bla!s}, {(repr(bla))}, {(ascii(bla))}" # RUF010 +15 - f"{bla!s}, {(repr(bla))}, {(ascii(bla))}" # RUF010 15 + f"{bla!s}, {bla!r}, {(ascii(bla))}" # RUF010 -16 | | RUF010 [*] Use explicit conversion flag @@ -187,10 +167,8 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -14 | - - f"{bla!s}, {(repr(bla))}, {(ascii(bla))}" # RUF010 +15 - f"{bla!s}, {(repr(bla))}, {(ascii(bla))}" # RUF010 15 + f"{bla!s}, {(repr(bla))}, {bla!a}" # RUF010 -16 | | RUF010 [*] Use explicit conversion flag @@ -204,10 +182,8 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -34 | " intermediary content " - - f" that flows {repr(obj)} of type {type(obj)}.{additional_message}" # RUF010 +35 - f" that flows {repr(obj)} of type {type(obj)}.{additional_message}" # RUF010 35 + f" that flows {obj!r} of type {type(obj)}.{additional_message}" # RUF010 -36 | ) | RUF010 [*] Use explicit conversion flag @@ -221,10 +197,8 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -39 | # https://github.com/astral-sh/ruff/issues/16325 - - f"{str({})}" +40 - f"{str({})}" 40 + f"{ {}!s}" -41 | | RUF010 [*] Use explicit conversion flag @@ -239,10 +213,8 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -41 | - - f"{str({} | {})}" +42 - f"{str({} | {})}" 42 + f"{ {} | {}!s}" -43 | | RUF010 [*] Use explicit conversion flag @@ -257,10 +229,8 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -45 | - - f"{builtins.repr(1)}" +46 - f"{builtins.repr(1)}" 46 + f"{1!r}" -47 | | RUF010 [*] Use explicit conversion flag @@ -275,10 +245,8 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -49 | - - f"{repr(lambda: 1)}" +50 - f"{repr(lambda: 1)}" 50 + f"{(lambda: 1)!r}" -51 | | RUF010 [*] Use explicit conversion flag @@ -293,10 +261,8 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -51 | - - f"{repr(x := 2)}" +52 - f"{repr(x := 2)}" 52 + f"{(x := 2)!r}" -53 | | RUF010 [*] Use explicit conversion flag @@ -311,10 +277,8 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -53 | - - f"{str(object=3)}" +54 - f"{str(object=3)}" 54 + f"{3!s}" -55 | | RUF010 [*] Use explicit conversion flag @@ -329,10 +293,8 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -55 | - - f"{str(x for x in [])}" +56 - f"{str(x for x in [])}" 56 + f"{(x for x in [])!s}" -57 | | RUF010 [*] Use explicit conversion flag @@ -347,10 +309,8 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -57 | - - f"{str((x for x in []))}" +58 - f"{str((x for x in []))}" 58 + f"{(x for x in [])!s}" -59 | | RUF010 [*] Use explicit conversion flag @@ -368,13 +328,11 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -68 | # Fix should be unsafe when it deletes a comment (https://github.com/astral-sh/ruff/issues/19745) - - f"{ascii( - - # comment - - 1 - - )}" +69 - f"{ascii( +70 - # comment +71 - 1 +72 - )}" 69 + f"{1!a}" -70 | | note: This is an unsafe fix and may change runtime behavior @@ -394,13 +352,11 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -73 | - - f"{repr( - - # comment - - 1 - - )}" +74 - f"{repr( +75 - # comment +76 - 1 +77 - )}" 74 + f"{1!r}" -75 | | note: This is an unsafe fix and may change runtime behavior @@ -420,13 +376,11 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -78 | - - f"{str( - - # comment - - 1 - - )}" +79 - f"{str( +80 - # comment +81 - 1 +82 - )}" 79 + f"{1!s}" -80 | | note: This is an unsafe fix and may change runtime behavior @@ -443,11 +397,9 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -84 | # Fix should be unsafe when it deletes comments after the argument - - f"{ascii(1 # comment - - )}" +85 - f"{ascii(1 # comment +86 - )}" 85 + f"{1!a}" -86 | | note: This is an unsafe fix and may change runtime behavior @@ -467,14 +419,9 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -87 | - - f"{repr(( 88 + f"{( -89 | 1 - - ) # comment - - )}" +89 + 1 90 + )!r}" -91 | | note: This is an unsafe fix and may change runtime behavior @@ -495,15 +442,9 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -92 | - - f"{str(( 93 + f"{( -94 | 1 - - ) - - # comment - - )}" +94 + 1 95 + )!s}" -96 | | note: This is an unsafe fix and may change runtime behavior @@ -522,14 +463,10 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -99 | # Fix should be safe when the comment is preserved inside extra parentheses - - f"{ascii(( 100 + f"{( -101 | # comment -102 | 1 - - ))}" +101 + # comment +102 + 1 103 + )!a}" -104 | | RUF010 [*] Use explicit conversion flag @@ -547,13 +484,9 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -104 | - - f"{repr(( 105 + f"{( -106 | 1 # comment - - ))}" +106 + 1 # comment 107 + )!r}" -108 | | RUF010 [*] Use explicit conversion flag @@ -572,14 +505,10 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -108 | - - f"{repr(( 109 + f"{( -110 | 1 -111 | # comment - - ))}" +110 + 1 +111 + # comment 112 + )!r}" -113 | | RUF010 [*] Use explicit conversion flag @@ -598,14 +527,10 @@ RUF010 [*] Use explicit conversion flag | help: Replace with conversion flag | -113 | - - f"{repr(( 114 + f"{( -115 | # comment -116 | 1 - - ))}" +115 + # comment +116 + 1 117 + )!r}" -118 | | RUF010 [*] Use explicit conversion flag @@ -621,11 +546,8 @@ RUF010 [*] Use explicit conversion flag | |__^ help: Replace with conversion flag | -118 | - - f"{str(( 119 + f"{( -120 | # comment -121 | 1 - - ))}" +120 + # comment +121 + 1 122 + )!s}" | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF013_RUF013_0.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF013_RUF013_0.py.snap index 2764d2786a5c6..4877df5bccd39 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF013_RUF013_0.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF013_RUF013_0.py.snap @@ -10,11 +10,8 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -19 | - - def f(arg: int = None): # RUF013 -20 + def f(arg: int | None = None): # RUF013 -21 | pass - | +20 | def f(arg: int | None = None): # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior RUF013 [*] PEP 484 prohibits implicit `Optional` @@ -26,11 +23,8 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -23 | - - def f(arg: str = None): # RUF013 -24 + def f(arg: str | None = None): # RUF013 -25 | pass - | +24 | def f(arg: str | None = None): # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior RUF013 [*] PEP 484 prohibits implicit `Optional` @@ -42,11 +36,8 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -27 | - - def f(arg: Tuple[str] = None): # RUF013 -28 + def f(arg: Tuple[str] | None = None): # RUF013 -29 | pass - | +28 | def f(arg: Tuple[str] | None = None): # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior RUF013 [*] PEP 484 prohibits implicit `Optional` @@ -58,11 +49,8 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -57 | - - def f(arg: Union = None): # RUF013 -58 + def f(arg: Union | None = None): # RUF013 -59 | pass - | +58 | def f(arg: Union | None = None): # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior RUF013 [*] PEP 484 prohibits implicit `Optional` @@ -74,11 +62,8 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -61 | - - def f(arg: Union[int] = None): # RUF013 -62 + def f(arg: Union[int] | None = None): # RUF013 -63 | pass - | +62 | def f(arg: Union[int] | None = None): # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior RUF013 [*] PEP 484 prohibits implicit `Optional` @@ -90,11 +75,8 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -65 | - - def f(arg: Union[int, str] = None): # RUF013 -66 + def f(arg: Union[int, str] | None = None): # RUF013 -67 | pass - | +66 | def f(arg: Union[int, str] | None = None): # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior RUF013 [*] PEP 484 prohibits implicit `Optional` @@ -106,11 +88,8 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -84 | - - def f(arg: int | float = None): # RUF013 -85 + def f(arg: int | float | None = None): # RUF013 -86 | pass - | +85 | def f(arg: int | float | None = None): # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior RUF013 [*] PEP 484 prohibits implicit `Optional` @@ -122,11 +101,8 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -88 | - - def f(arg: int | float | str | bytes = None): # RUF013 -89 + def f(arg: int | float | str | bytes | None = None): # RUF013 -90 | pass - | +89 | def f(arg: int | float | str | bytes | None = None): # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior RUF013 [*] PEP 484 prohibits implicit `Optional` @@ -138,11 +114,8 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -107 | - - def f(arg: Literal[1] = None): # RUF013 -108 + def f(arg: Literal[1] | None = None): # RUF013 -109 | pass - | +108 | def f(arg: Literal[1] | None = None): # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior RUF013 [*] PEP 484 prohibits implicit `Optional` @@ -154,11 +127,8 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -111 | - - def f(arg: Literal[1, "foo"] = None): # RUF013 -112 + def f(arg: Literal[1, "foo"] | None = None): # RUF013 -113 | pass - | +112 | def f(arg: Literal[1, "foo"] | None = None): # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior RUF013 [*] PEP 484 prohibits implicit `Optional` @@ -170,11 +140,8 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -130 | - - def f(arg: Annotated[int, ...] = None): # RUF013 -131 + def f(arg: Annotated[int | None, ...] = None): # RUF013 -132 | pass - | +131 | def f(arg: Annotated[int | None, ...] = None): # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior RUF013 [*] PEP 484 prohibits implicit `Optional` @@ -186,11 +153,8 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -134 | - - def f(arg: Annotated[Annotated[int | str, ...], ...] = None): # RUF013 -135 + def f(arg: Annotated[Annotated[int | str | None, ...], ...] = None): # RUF013 -136 | pass - | +135 | def f(arg: Annotated[Annotated[int | str | None, ...], ...] = None): # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior RUF013 [*] PEP 484 prohibits implicit `Optional` @@ -204,11 +168,8 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -150 | def f( - - arg1: int = None, # RUF013 -151 + arg1: int | None = None, # RUF013 -152 | arg2: Union[int, float] = None, # RUF013 - | +151 | arg1: int | None = None, # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior RUF013 [*] PEP 484 prohibits implicit `Optional` @@ -223,11 +184,8 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -151 | arg1: int = None, # RUF013 - - arg2: Union[int, float] = None, # RUF013 -152 + arg2: Union[int, float] | None = None, # RUF013 -153 | arg3: Literal[1, 2, 3] = None, # RUF013 - | +152 | arg2: Union[int, float] | None = None, # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior RUF013 [*] PEP 484 prohibits implicit `Optional` @@ -242,11 +200,8 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -152 | arg2: Union[int, float] = None, # RUF013 - - arg3: Literal[1, 2, 3] = None, # RUF013 -153 + arg3: Literal[1, 2, 3] | None = None, # RUF013 -154 | ): - | +153 | arg3: Literal[1, 2, 3] | None = None, # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior RUF013 [*] PEP 484 prohibits implicit `Optional` @@ -258,11 +213,8 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -180 | - - def f(arg: Union[Annotated[int, ...], Union[str, bytes]] = None): # RUF013 -181 + def f(arg: Union[Annotated[int, ...], Union[str, bytes]] | None = None): # RUF013 -182 | pass - | +181 | def f(arg: Union[Annotated[int, ...], Union[str, bytes]] | None = None): # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior RUF013 [*] PEP 484 prohibits implicit `Optional` @@ -274,11 +226,8 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -187 | - - def f(arg: "int" = None): # RUF013 -188 + def f(arg: "int | None" = None): # RUF013 -189 | pass - | +188 | def f(arg: "int | None" = None): # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior RUF013 [*] PEP 484 prohibits implicit `Optional` @@ -290,11 +239,8 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -191 | - - def f(arg: "str" = None): # RUF013 -192 + def f(arg: "str | None" = None): # RUF013 -193 | pass - | +192 | def f(arg: "str | None" = None): # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior RUF013 PEP 484 prohibits implicit `Optional` @@ -315,9 +261,6 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -203 | - - def f(arg: Union["int", "str"] = None): # RUF013 -204 + def f(arg: Union["int", "str"] | None = None): # RUF013 -205 | pass - | +204 | def f(arg: Union["int", "str"] | None = None): # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF013_RUF013_1.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF013_RUF013_1.py.snap index 19538add73e46..770833546ea9d 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF013_RUF013_1.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF013_RUF013_1.py.snap @@ -10,9 +10,6 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -3 | - - def f(arg: int = None): # RUF013 -4 + def f(arg: int | None = None): # RUF013 -5 | pass - | +4 | def f(arg: int | None = None): # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF013_RUF013_3.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF013_RUF013_3.py.snap index d8487eae92df1..fdcf1767b836e 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF013_RUF013_3.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF013_RUF013_3.py.snap @@ -10,11 +10,8 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -3 | - - def f(arg: typing.List[str] = None): # RUF013 -4 + def f(arg: typing.List[str] | None = None): # RUF013 -5 | pass - | +4 | def f(arg: typing.List[str] | None = None): # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior RUF013 [*] PEP 484 prohibits implicit `Optional` @@ -26,11 +23,8 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -21 | - - def f(arg: typing.Union[int, str] = None): # RUF013 -22 + def f(arg: typing.Union[int, str] | None = None): # RUF013 -23 | pass - | +22 | def f(arg: typing.Union[int, str] | None = None): # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior RUF013 [*] PEP 484 prohibits implicit `Optional` @@ -42,9 +36,6 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -28 | - - def f(arg: typing.Literal[1, "foo", True] = None): # RUF013 -29 + def f(arg: typing.Literal[1, "foo", True] | None = None): # RUF013 -30 | pass - | +29 | def f(arg: typing.Literal[1, "foo", True] | None = None): # RUF013 + | ++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF013_RUF013_4.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF013_RUF013_4.py.snap index 745e2f89b22a4..2e88592a23a5f 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF013_RUF013_4.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF013_RUF013_4.py.snap @@ -8,9 +8,6 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | ^^^ help: Convert to `T | None` | -14 | - - def multiple_2(arg1: Optional, arg2: Optional = None, arg3: int = None): ... -15 + def multiple_2(arg1: Optional, arg2: Optional = None, arg3: int | None = None): ... -16 | - | +15 | def multiple_2(arg1: Optional, arg2: Optional = None, arg3: int | None = None): ... + | ++++++ note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF015_RUF015.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF015_RUF015.py.snap index 87d7c0c429ea4..5fc2599835960 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF015_RUF015.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF015_RUF015.py.snap @@ -12,10 +12,8 @@ RUF015 [*] Prefer `next(iter(x))` over single element slice | help: Replace with `next(iter(x))` | -3 | # RUF015 - - list(x)[0] +4 - list(x)[0] 4 + next(iter(x)) -5 | tuple(x)[0] | note: This is an unsafe fix and may change runtime behavior @@ -31,10 +29,8 @@ RUF015 [*] Prefer `next(iter(x))` over single element slice | help: Replace with `next(iter(x))` | -4 | list(x)[0] - - tuple(x)[0] +5 - tuple(x)[0] 5 + next(iter(x)) -6 | list(i for i in x)[0] | note: This is an unsafe fix and may change runtime behavior @@ -49,10 +45,8 @@ RUF015 [*] Prefer `next(iter(x))` over single element slice | help: Replace with `next(iter(x))` | -5 | tuple(x)[0] - - list(i for i in x)[0] +6 - list(i for i in x)[0] 6 + next(iter(x)) -7 | [i for i in x][0] | note: This is an unsafe fix and may change runtime behavior @@ -68,10 +62,8 @@ RUF015 [*] Prefer `next(iter(x))` over single element slice | help: Replace with `next(iter(x))` | -6 | list(i for i in x)[0] - - [i for i in x][0] +7 - [i for i in x][0] 7 + next(iter(x)) -8 | | note: This is an unsafe fix and may change runtime behavior @@ -86,10 +78,8 @@ RUF015 [*] Prefer `next(i + 1 for i in x)` over single element slice | help: Replace with `next(i + 1 for i in x)` | -28 | # RUF015 (doesn't mirror the underlying list) - - [i + 1 for i in x][0] +29 - [i + 1 for i in x][0] 29 + next(i + 1 for i in x) -30 | [i for i in x if i > 5][0] | note: This is an unsafe fix and may change runtime behavior @@ -104,10 +94,8 @@ RUF015 [*] Prefer `next(i for i in x if i > 5)` over single element slice | help: Replace with `next(i for i in x if i > 5)` | -29 | [i + 1 for i in x][0] - - [i for i in x if i > 5][0] +30 - [i for i in x if i > 5][0] 30 + next(i for i in x if i > 5) -31 | [(i, i + 1) for i in x][0] | note: This is an unsafe fix and may change runtime behavior @@ -123,10 +111,8 @@ RUF015 [*] Prefer `next((i, i + 1) for i in x)` over single element slice | help: Replace with `next((i, i + 1) for i in x)` | -30 | [i for i in x if i > 5][0] - - [(i, i + 1) for i in x][0] +31 - [(i, i + 1) for i in x][0] 31 + next((i, i + 1) for i in x) -32 | | note: This is an unsafe fix and may change runtime behavior @@ -142,10 +128,8 @@ RUF015 [*] Prefer `next(i + j for i in x for j in y)` over single element slice | help: Replace with `next(i + j for i in x for j in y)` | -34 | y = range(10) - - [i + j for i in x for j in y][0] +35 - [i + j for i in x for j in y][0] 35 + next(i + j for i in x for j in y) -36 | | note: This is an unsafe fix and may change runtime behavior @@ -160,10 +144,8 @@ RUF015 [*] Prefer `next(iter(range(10)))` over single element slice | help: Replace with `next(iter(range(10)))` | -37 | # RUF015 - - list(range(10))[0] +38 - list(range(10))[0] 38 + next(iter(range(10))) -39 | list(x.y)[0] | note: This is an unsafe fix and may change runtime behavior @@ -179,10 +161,8 @@ RUF015 [*] Prefer `next(iter(x.y))` over single element slice | help: Replace with `next(iter(x.y))` | -38 | list(range(10))[0] - - list(x.y)[0] +39 - list(x.y)[0] 39 + next(iter(x.y)) -40 | list(x["y"])[0] | note: This is an unsafe fix and may change runtime behavior @@ -198,10 +178,8 @@ RUF015 [*] Prefer `next(iter(x["y"]))` over single element slice | help: Replace with `next(iter(x["y"]))` | -39 | list(x.y)[0] - - list(x["y"])[0] +40 - list(x["y"])[0] 40 + next(iter(x["y"])) -41 | [*range(10)][0] | note: This is an unsafe fix and may change runtime behavior @@ -217,10 +195,8 @@ RUF015 [*] Prefer `next(iter(range(10)))` over single element slice | help: Replace with `next(iter(range(10)))` | -40 | list(x["y"])[0] - - [*range(10)][0] +41 - [*range(10)][0] 41 + next(iter(range(10))) -42 | [*x["y"]][0] | note: This is an unsafe fix and may change runtime behavior @@ -236,10 +212,8 @@ RUF015 [*] Prefer `next(iter(x["y"]))` over single element slice | help: Replace with `next(iter(x["y"]))` | -41 | [*range(10)][0] - - [*x["y"]][0] +42 - [*x["y"]][0] 42 + next(iter(x["y"])) -43 | [*x.y][0] | note: This is an unsafe fix and may change runtime behavior @@ -255,10 +229,8 @@ RUF015 [*] Prefer `next(iter(x.y))` over single element slice | help: Replace with `next(iter(x.y))` | -42 | [*x["y"]][0] - - [*x.y][0] +43 - [*x.y][0] 43 + next(iter(x.y)) -44 | [* x.y][0] | note: This is an unsafe fix and may change runtime behavior @@ -274,10 +246,8 @@ RUF015 [*] Prefer `next(iter(x.y))` over single element slice | help: Replace with `next(iter(x.y))` | -43 | [*x.y][0] - - [* x.y][0] +44 - [* x.y][0] 44 + next(iter(x.y)) -45 | [ | note: This is an unsafe fix and may change runtime behavior @@ -295,12 +265,10 @@ RUF015 [*] Prefer `next(iter(x.y))` over single element slice | help: Replace with `next(iter(x.y))` | -44 | [* x.y][0] - - [ - - *x.y - - ][0] +45 - [ +46 - *x.y +47 - ][0] 45 + next(iter(x.y)) -46 | | note: This is an unsafe fix and may change runtime behavior @@ -320,15 +288,11 @@ RUF015 [*] Prefer `next(...)` over single element slice | help: Replace with `next(...)` | -49 | # RUF015 (multi-line) - - revision_heads_map_ast = [ -50 + revision_heads_map_ast = next( -51 | a -52 | for a in revision_heads_map_ast_obj.body -53 | if isinstance(a, ast.Assign) and a.targets[0].id == "REVISION_HEADS_MAP" - - ][0] +50 ~ revision_heads_map_ast = next( +51 + a +52 + for a in revision_heads_map_ast_obj.body +53 + if isinstance(a, ast.Assign) and a.targets[0].id == "REVISION_HEADS_MAP" 54 + ) -55 | | note: This is an unsafe fix and may change runtime behavior @@ -342,10 +306,8 @@ RUF015 [*] Prefer `next(zip(x, y))` over single element slice | help: Replace with `next(zip(x, y))` | -56 | # RUF015 (zip) - - list(zip(x, y))[0] +57 - list(zip(x, y))[0] 57 + next(zip(x, y)) -58 | [*zip(x, y)][0] | note: This is an unsafe fix and may change runtime behavior @@ -361,10 +323,8 @@ RUF015 [*] Prefer `next(zip(x, y))` over single element slice | help: Replace with `next(zip(x, y))` | -57 | list(zip(x, y))[0] - - [*zip(x, y)][0] +58 - [*zip(x, y)][0] 58 + next(zip(x, y)) -59 | | note: This is an unsafe fix and may change runtime behavior @@ -379,10 +339,8 @@ RUF015 [*] Prefer `next(iter(x))` over single element slice | help: Replace with `next(iter(x))` | -60 | # RUF015 (pop) - - list(x).pop(0) +61 - list(x).pop(0) 61 + next(iter(x)) -62 | [i for i in x].pop(0) | note: This is an unsafe fix and may change runtime behavior @@ -397,10 +355,8 @@ RUF015 [*] Prefer `next(iter(x))` over single element slice | help: Replace with `next(iter(x))` | -61 | list(x).pop(0) - - [i for i in x].pop(0) +62 - [i for i in x].pop(0) 62 + next(iter(x)) -63 | list(i for i in x).pop(0) | note: This is an unsafe fix and may change runtime behavior @@ -416,10 +372,8 @@ RUF015 [*] Prefer `next(iter(x))` over single element slice | help: Replace with `next(iter(x))` | -62 | [i for i in x].pop(0) - - list(i for i in x).pop(0) +63 - list(i for i in x).pop(0) 63 + next(iter(x)) -64 | | note: This is an unsafe fix and may change runtime behavior @@ -432,8 +386,7 @@ RUF015 [*] Prefer `next(iter(zip(x, y)))` over single element slice | ^^^^^^^^^^^^^^^^^^ help: Replace with `next(iter(zip(x, y)))` | -72 | zip = list # Overwrite the builtin zip - - list(zip(x, y))[0] +73 - list(zip(x, y))[0] 73 + next(iter(zip(x, y))) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF017_RUF017_0.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF017_RUF017_0.py.snap index 601c205bbdbea..e8a1edec042d9 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF017_RUF017_0.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF017_RUF017_0.py.snap @@ -13,14 +13,12 @@ RUF017 [*] Avoid quadratic list summation help: Replace with `functools.reduce` | 1 + import functools -2 + import operator +2 ~ import operator 3 | x = [1, 2, 3] 4 | y = [4, 5, 6] 5 | 6 | # RUF017 - - sum([x, y], start=[]) 7 + functools.reduce(operator.iadd, [x, y], []) -8 | sum([x, y], []) | note: This is an unsafe fix and may change runtime behavior @@ -37,13 +35,12 @@ RUF017 [*] Avoid quadratic list summation help: Replace with `functools.reduce` | 1 + import functools -2 + import operator +2 ~ import operator 3 | x = [1, 2, 3] --------------------------------------------------------------------------------- +4 | y = [4, 5, 6] +… 7 | sum([x, y], start=[]) - - sum([x, y], []) 8 + functools.reduce(operator.iadd, [x, y], []) -9 | sum([[1, 2, 3], [4, 5, 6]], start=[]) | note: This is an unsafe fix and may change runtime behavior @@ -58,16 +55,15 @@ RUF017 [*] Avoid quadratic list summation 9 | sum([[1, 2, 3], [4, 5, 6]], | help: Replace with `functools.reduce` - | -1 + import functools -2 + import operator -3 | x = [1, 2, 3] --------------------------------------------------------------------------------- -8 | sum([x, y], []) - - sum([[1, 2, 3], [4, 5, 6]], start=[]) -9 + functools.reduce(operator.iadd, [[1, 2, 3], [4, 5, 6]], []) -10 | sum([[1, 2, 3], [4, 5, 6]], []) - | + | +1 + import functools +2 ~ import operator +3 | x = [1, 2, 3] +4 | y = [4, 5, 6] +… +8 | sum([x, y], []) +9 + functools.reduce(operator.iadd, [[1, 2, 3], [4, 5, 6]], []) + | note: This is an unsafe fix and may change runtime behavior RUF017 [*] Avoid quadratic list summation @@ -82,14 +78,13 @@ RUF017 [*] Avoid quadratic list summation | help: Replace with `functools.reduce` | -1 + import functools -2 + import operator -3 | x = [1, 2, 3] --------------------------------------------------------------------------------- -9 | sum([[1, 2, 3], [4, 5, 6]], start=[]) - - sum([[1, 2, 3], [4, 5, 6]], []) + 1 + import functools + 2 ~ import operator + 3 | x = [1, 2, 3] + 4 | y = [4, 5, 6] + … + 9 | sum([[1, 2, 3], [4, 5, 6]], start=[]) 10 + functools.reduce(operator.iadd, [[1, 2, 3], [4, 5, 6]], []) -11 | sum([[1, 2, 3], [4, 5, 6]], | note: This is an unsafe fix and may change runtime behavior @@ -106,15 +101,13 @@ RUF017 [*] Avoid quadratic list summation | help: Replace with `functools.reduce` | -1 + import functools -2 + import operator -3 | x = [1, 2, 3] --------------------------------------------------------------------------------- + 1 + import functools + 2 ~ import operator + 3 | x = [1, 2, 3] + 4 | y = [4, 5, 6] + … 10 | sum([[1, 2, 3], [4, 5, 6]], []) - - sum([[1, 2, 3], [4, 5, 6]], - - []) 11 + functools.reduce(operator.iadd, [[1, 2, 3], [4, 5, 6]], []) -12 | | note: This is an unsafe fix and may change runtime behavior @@ -127,10 +120,9 @@ RUF017 [*] Avoid quadratic list summation | ^^^^^^^^^^^^^^^ help: Replace with `functools.reduce` | +19 ~ import functools, operator 20 | - - sum([x, y], []) -21 + functools.reduce(operator.iadd, [x, y], []) -22 | +21 ~ functools.reduce(operator.iadd, [x, y], []) | note: This is an unsafe fix and may change runtime behavior @@ -143,12 +135,12 @@ RUF017 [*] Avoid quadratic list summation | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `functools.reduce` | -1 + import functools -2 + import operator -3 | x = [1, 2, 3] --------------------------------------------------------------------------------- + 1 + import functools + 2 ~ import operator + 3 | x = [1, 2, 3] + 4 | y = [4, 5, 6] + … 27 | def func(): - - sum((factor.dims for factor in bases), []) -28 + functools.reduce(operator.iadd, (factor.dims for factor in bases), []) +28 ~ functools.reduce(operator.iadd, (factor.dims for factor in bases), []) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF017_RUF017_1.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF017_RUF017_1.py.snap index 28a251a13f94c..34158b98f2ae0 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF017_RUF017_1.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF017_RUF017_1.py.snap @@ -8,9 +8,8 @@ RUF017 [*] Avoid quadratic list summation | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `functools.reduce` | - - sum((factor.dims for factor in bases), []) 1 + import functools -2 + import operator -3 + functools.reduce(operator.iadd, (factor.dims for factor in bases), []) +2 ~ import operator +3 ~ functools.reduce(operator.iadd, (factor.dims for factor in bases), []) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF019_RUF019.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF019_RUF019.py.snap index 18048376427be..94ff13a575eec 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF019_RUF019.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF019_RUF019.py.snap @@ -12,10 +12,8 @@ RUF019 [*] Unnecessary key check before dictionary access | help: Replace with `dict.get` | -2 | # RUF019 - - if "k" in d and d["k"]: +3 - if "k" in d and d["k"]: 3 + if d.get("k"): -4 | pass | RUF019 [*] Unnecessary key check before dictionary access @@ -28,10 +26,8 @@ RUF019 [*] Unnecessary key check before dictionary access | help: Replace with `dict.get` | -6 | k = "k" - - if k in d and d[k]: +7 - if k in d and d[k]: 7 + if d.get(k): -8 | pass | RUF019 [*] Unnecessary key check before dictionary access @@ -45,10 +41,8 @@ RUF019 [*] Unnecessary key check before dictionary access | help: Replace with `dict.get` | -9 | - - if (k) in d and d[k]: +10 - if (k) in d and d[k]: 10 + if d.get(k): -11 | pass | RUF019 [*] Unnecessary key check before dictionary access @@ -62,10 +56,8 @@ RUF019 [*] Unnecessary key check before dictionary access | help: Replace with `dict.get` | -12 | - - if k in d and d[(k)]: +13 - if k in d and d[(k)]: 13 + if d.get((k)): -14 | pass | RUF019 [*] Unnecessary key check before dictionary access @@ -80,10 +72,8 @@ RUF019 [*] Unnecessary key check before dictionary access | help: Replace with `dict.get` | -15 | - - not ("key" in dct and dct["key"]) +16 - not ("key" in dct and dct["key"]) 16 + not (dct.get("key")) -17 | | RUF019 [*] Unnecessary key check before dictionary access @@ -98,10 +88,8 @@ RUF019 [*] Unnecessary key check before dictionary access | help: Replace with `dict.get` | -17 | - - bool("key" in dct and dct["key"]) +18 - bool("key" in dct and dct["key"]) 18 + bool(dct.get("key")) -19 | | RUF019 [*] Unnecessary key check before dictionary access @@ -117,12 +105,10 @@ RUF019 [*] Unnecessary key check before dictionary access | help: Replace with `dict.get` | -27 | if ( - - "key" in d - - and # text - - d ["key"] +28 - "key" in d +29 - and # text +30 - d ["key"] 28 + d.get("key") -29 | ): | note: This is an unsafe fix and may change runtime behavior @@ -136,10 +122,8 @@ RUF019 [*] Unnecessary key check before dictionary access | help: Replace with `dict.get` | -41 | c = Formatter() - - if f"{c}" in d and d[f"{c}"]: +42 - if f"{c}" in d and d[f"{c}"]: 42 + if d.get(f"{c}"): -43 | pass | note: This is an unsafe fix and may change runtime behavior @@ -153,10 +137,8 @@ RUF019 [*] Unnecessary key check before dictionary access | help: Replace with `dict.get` | -45 | # F-string with only literal interpolation — safe fix - - if f"{1}" in d and d[f"{1}"]: +46 - if f"{1}" in d and d[f"{1}"]: 46 + if d.get(f"{1}"): -47 | pass | RUF019 [*] Unnecessary key check before dictionary access @@ -169,8 +151,6 @@ RUF019 [*] Unnecessary key check before dictionary access | help: Replace with `dict.get` | -49 | # Plain f-string without interpolation — safe fix - - if f"key" in d and d[f"key"]: +50 - if f"key" in d and d[f"key"]: 50 + if d.get(f"key"): -51 | pass | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF020_RUF020.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF020_RUF020.py.snap index afecdbe964f8c..c824f23279f42 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF020_RUF020.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF020_RUF020.py.snap @@ -13,10 +13,8 @@ RUF020 [*] `Union[Never, T]` is equivalent to `T` | help: Remove `Never` | -2 | - - Union[Never, int] +3 - Union[Never, int] 3 + int -4 | Union[NoReturn, int] | RUF020 [*] `Union[NoReturn, T]` is equivalent to `T` @@ -30,10 +28,8 @@ RUF020 [*] `Union[NoReturn, T]` is equivalent to `T` | help: Remove `NoReturn` | -3 | Union[Never, int] - - Union[NoReturn, int] +4 - Union[NoReturn, int] 4 + int -5 | Never | int | RUF020 [*] `Never | T` is equivalent to `T` @@ -48,10 +44,8 @@ RUF020 [*] `Never | T` is equivalent to `T` | help: Remove `Never` | -4 | Union[NoReturn, int] - - Never | int +5 - Never | int 5 + int -6 | NoReturn | int | RUF020 [*] `NoReturn | T` is equivalent to `T` @@ -66,10 +60,8 @@ RUF020 [*] `NoReturn | T` is equivalent to `T` | help: Remove `NoReturn` | -5 | Never | int - - NoReturn | int +6 - NoReturn | int 6 + int -7 | Union[Union[Never, int], Union[NoReturn, int]] | RUF020 [*] `Union[Never, T]` is equivalent to `T` @@ -83,10 +75,8 @@ RUF020 [*] `Union[Never, T]` is equivalent to `T` | help: Remove `Never` | -6 | NoReturn | int - - Union[Union[Never, int], Union[NoReturn, int]] +7 - Union[Union[Never, int], Union[NoReturn, int]] 7 + Union[int, Union[NoReturn, int]] -8 | Union[NoReturn, int, float] | RUF020 [*] `Union[NoReturn, T]` is equivalent to `T` @@ -100,10 +90,8 @@ RUF020 [*] `Union[NoReturn, T]` is equivalent to `T` | help: Remove `NoReturn` | -6 | NoReturn | int - - Union[Union[Never, int], Union[NoReturn, int]] +7 - Union[Union[Never, int], Union[NoReturn, int]] 7 + Union[Union[Never, int], int] -8 | Union[NoReturn, int, float] | RUF020 [*] `Union[NoReturn, T]` is equivalent to `T` @@ -115,10 +103,8 @@ RUF020 [*] `Union[NoReturn, T]` is equivalent to `T` | ^^^^^^^^ help: Remove `NoReturn` | -7 | Union[Union[Never, int], Union[NoReturn, int]] - - Union[NoReturn, int, float] +8 - Union[NoReturn, int, float] 8 + Union[int, float] -9 | | RUF020 `Never | T` is equivalent to `T` @@ -193,10 +179,8 @@ RUF020 [*] `Never | T` is equivalent to `T` | help: Remove `Never` | -20 | def func() -> ( - - Never # text - - | # text -21 | int +21 - Never # text +22 - | # text | note: This is an unsafe fix and may change runtime behavior @@ -211,13 +195,7 @@ RUF020 [*] `Union[Never, T]` is equivalent to `T` | help: Remove `Never` | -30 | - - x: Union[ - - Never, - - Literal["LongLiteralNumberOne"] -31 + x: (Literal["LongLiteralNumberOne"] -32 | | Literal["LongLiteralNumberTwo"] - - | Literal["LongLiteralNumberThree"] - - ] +31 ~ x: (Literal["LongLiteralNumberOne"] +32 + | Literal["LongLiteralNumberTwo"] 33 + | Literal["LongLiteralNumberThree"]) | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF021_RUF021.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF021_RUF021.py.snap index 3a905313e9e7c..9e51b4592d663 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF021_RUF021.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF021_RUF021.py.snap @@ -11,10 +11,8 @@ RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` toget | help: Parenthesize the `and` subexpression | -11 | a, b, c = 1, 0, 2 - - x = a or b and c # RUF021: => `a or (b and c)` +12 - x = a or b and c # RUF021: => `a or (b and c)` 12 + x = a or (b and c) # RUF021: => `a or (b and c)` -13 | x = a or b and c # looooooooooooooooooooooooooooooong comment but it won't prevent an autofix | RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` together, to make the precedence clear @@ -29,10 +27,8 @@ RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` toget | help: Parenthesize the `and` subexpression | -12 | x = a or b and c # RUF021: => `a or (b and c)` - - x = a or b and c # looooooooooooooooooooooooooooooong comment but it won't prevent an autofix +13 - x = a or b and c # looooooooooooooooooooooooooooooong comment but it won't prevent an autofix 13 + x = a or (b and c) # looooooooooooooooooooooooooooooong comment but it won't prevent an autofix -14 | | RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` together, to make the precedence clear @@ -46,10 +42,8 @@ RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` toget | help: Parenthesize the `and` subexpression | -15 | a, b, c = 0, 1, 2 - - y = a and b or c # RUF021: => `(a and b) or c` +16 - y = a and b or c # RUF021: => `(a and b) or c` 16 + y = (a and b) or c # RUF021: => `(a and b) or c` -17 | | RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` together, to make the precedence clear @@ -62,10 +56,8 @@ RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` toget | help: Parenthesize the `and` subexpression | -18 | a, b, c, d = 1, 2, 0, 3 - - if a or b or c and d: # RUF021: => `a or b or (c and d)` +19 - if a or b or c and d: # RUF021: => `a or b or (c and d)` 19 + if a or b or (c and d): # RUF021: => `a or b or (c and d)` -20 | pass | RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` together, to make the precedence clear @@ -79,10 +71,8 @@ RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` toget | help: Parenthesize the `and` subexpression | -25 | pass - - elif a or b and c or d: # RUF021: => `a or (b and c) or d` +26 - elif a or b and c or d: # RUF021: => `a or (b and c) or d` 26 + elif a or (b and c) or d: # RUF021: => `a or (b and c) or d` -27 | pass | RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` together, to make the precedence clear @@ -95,10 +85,8 @@ RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` toget | help: Parenthesize the `and` subexpression | -29 | a, b, c, d = 0, 1, 0, 2 - - while a and b or c and d: # RUF021: => `(and b) or (c and d)` +30 - while a and b or c and d: # RUF021: => `(and b) or (c and d)` 30 + while (a and b) or c and d: # RUF021: => `(and b) or (c and d)` -31 | pass | RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` together, to make the precedence clear @@ -111,10 +99,8 @@ RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` toget | help: Parenthesize the `and` subexpression | -29 | a, b, c, d = 0, 1, 0, 2 - - while a and b or c and d: # RUF021: => `(and b) or (c and d)` +30 - while a and b or c and d: # RUF021: => `(and b) or (c and d)` 30 + while a and b or (c and d): # RUF021: => `(and b) or (c and d)` -31 | pass | RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` together, to make the precedence clear @@ -129,10 +115,8 @@ RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` toget | help: Parenthesize the `and` subexpression | -34 | # RUF021: => `a or b or c or (d and e)`: - - z = [a for a in range(5) if a or b or c or d and e] +35 - z = [a for a in range(5) if a or b or c or d and e] 35 + z = [a for a in range(5) if a or b or c or (d and e)] -36 | | RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` together, to make the precedence clear @@ -146,10 +130,8 @@ RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` toget | help: Parenthesize the `and` subexpression | -37 | a, b, c, d = 0, 1, 3, 0 - - assert not a and b or c or d # RUF021: => `(not a and b) or c or d` +38 - assert not a and b or c or d # RUF021: => `(not a and b) or c or d` 38 + assert (not a and b) or c or d # RUF021: => `(not a and b) or c or d` -39 | | RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` together, to make the precedence clear @@ -164,10 +146,8 @@ RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` toget | help: Parenthesize the `and` subexpression | -39 | - - if (not a) and b or c or d: # RUF021: => `((not a) and b) or c or d` +40 - if (not a) and b or c or d: # RUF021: => `((not a) and b) or c or d` 40 + if ((not a) and b) or c or d: # RUF021: => `((not a) and b) or c or d` -41 | if (not a and b) or c or d: # OK | RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` together, to make the precedence clear @@ -184,12 +164,8 @@ RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` toget | help: Parenthesize the `and` subexpression | -45 | some_reasonably_long_condition - - or some_other_reasonably_long_condition - - and some_third_reasonably_long_condition -46 + or (some_other_reasonably_long_condition +46 ~ or (some_other_reasonably_long_condition 47 + and some_third_reasonably_long_condition) -48 | or some_fourth_reasonably_long_condition | RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` together, to make the precedence clear @@ -209,13 +185,9 @@ RUF021 [*] Parenthesize `a and b` expressions when chaining `and` and `or` toget | help: Parenthesize the `and` subexpression | -47 | and some_third_reasonably_long_condition - - or some_fourth_reasonably_long_condition -48 + or (some_fourth_reasonably_long_condition -49 | and some_fifth_reasonably_long_condition -50 | # a comment -51 | and some_sixth_reasonably_long_condition - - and some_seventh_reasonably_long_condition +48 ~ or (some_fourth_reasonably_long_condition +49 + and some_fifth_reasonably_long_condition +50 + # a comment +51 + and some_sixth_reasonably_long_condition 52 + and some_seventh_reasonably_long_condition) -53 | # another comment | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF022_RUF022.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF022_RUF022.py.snap index 4da3c77a35f48..bb4da055aa5cc 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF022_RUF022.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF022_RUF022.py.snap @@ -13,10 +13,8 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -4 | - - __all__ = ["d", "c", "b", "a"] # a comment that is untouched +5 - __all__ = ["d", "c", "b", "a"] # a comment that is untouched 5 + __all__ = ["a", "b", "c", "d"] # a comment that is untouched -6 | __all__ += ["foo", "bar", "antipasti"] | RUF022 [*] `__all__` is not sorted @@ -29,10 +27,8 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -5 | __all__ = ["d", "c", "b", "a"] # a comment that is untouched - - __all__ += ["foo", "bar", "antipasti"] +6 - __all__ += ["foo", "bar", "antipasti"] 6 + __all__ += ["antipasti", "bar", "foo"] -7 | __all__ = ("d", "c", "b", "a") | RUF022 [*] `__all__` is not sorted @@ -47,10 +43,8 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -6 | __all__ += ["foo", "bar", "antipasti"] - - __all__ = ("d", "c", "b", "a") +7 - __all__ = ("d", "c", "b", "a") 7 + __all__ = ("a", "b", "c", "d") -8 | | RUF022 [*] `__all__` is not sorted @@ -65,10 +59,8 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -10 | # but unnecessary parens are not - - __all__: list = ['b', "c", ((('a')))] +11 - __all__: list = ['b', "c", ((('a')))] 11 + __all__: list = ['a', 'b', "c"] -12 | # Trailing commas are also not retained in single-line `__all__` definitions | RUF022 [*] `__all__` is not sorted @@ -83,10 +75,8 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -13 | # (but they are in multiline `__all__` definitions) - - __all__: tuple = ("b", "c", "a",) +14 - __all__: tuple = ("b", "c", "a",) 14 + __all__: tuple = ("a", "b", "c") -15 | | RUF022 [*] `__all__` is not sorted @@ -100,10 +90,8 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -16 | if bool(): - - __all__ += ("x", "m", "a", "s") +17 - __all__ += ("x", "m", "a", "s") 17 + __all__ += ("a", "m", "s", "x") -18 | else: | RUF022 [*] `__all__` is not sorted @@ -118,10 +106,8 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -18 | else: - - __all__ += "foo3", "foo2", "foo1" # NB: an implicit tuple (without parens) +19 - __all__ += "foo3", "foo2", "foo1" # NB: an implicit tuple (without parens) 19 + __all__ += "foo1", "foo2", "foo3" # NB: an implicit tuple (without parens) -20 | | RUF022 [*] `__all__` is not sorted @@ -136,10 +122,8 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -20 | - - __all__: list[str] = ["the", "three", "little", "pigs"] +21 - __all__: list[str] = ["the", "three", "little", "pigs"] 21 + __all__: list[str] = ["little", "pigs", "the", "three"] -22 | | RUF022 [*] `__all__` is not sorted @@ -154,10 +138,8 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -22 | - - __all__ = ("parenthesized_item"), "in", ("an_unparenthesized_tuple") +23 - __all__ = ("parenthesized_item"), "in", ("an_unparenthesized_tuple") 23 + __all__ = "an_unparenthesized_tuple", "in", "parenthesized_item" -24 | __all__.extend(["foo", "bar"]) | RUF022 [*] `__all__` is not sorted @@ -171,10 +153,8 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -23 | __all__ = ("parenthesized_item"), "in", ("an_unparenthesized_tuple") - - __all__.extend(["foo", "bar"]) +24 - __all__.extend(["foo", "bar"]) 24 + __all__.extend(["bar", "foo"]) -25 | __all__.extend(("foo", "bar")) | RUF022 [*] `__all__` is not sorted @@ -188,10 +168,8 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -24 | __all__.extend(["foo", "bar"]) - - __all__.extend(("foo", "bar")) +25 - __all__.extend(("foo", "bar")) 25 + __all__.extend(("bar", "foo")) -26 | __all__.extend((((["foo", "bar"])))) | RUF022 [*] `__all__` is not sorted @@ -206,10 +184,8 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -25 | __all__.extend(("foo", "bar")) - - __all__.extend((((["foo", "bar"])))) +26 - __all__.extend((((["foo", "bar"])))) 26 + __all__.extend((((["bar", "foo"])))) -27 | | RUF022 [*] `__all__` is not sorted @@ -231,17 +207,13 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -32 | __all__ = ( - - "d0", +32 ~ __all__ = ( 33 + # a comment regarding 'a0': 34 + "a0", 35 + "b0", -36 | "c0", # a comment regarding 'c0' - - "b0", - - # a comment regarding 'a0': - - "a0" +36 + "c0", # a comment regarding 'c0' 37 + "d0" -38 | ) +38 + ) | note: This is an unsafe fix and may change runtime behavior @@ -264,17 +236,13 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -40 | __all__ = [ - - "d", +40 ~ __all__ = [ 41 + # a comment regarding 'a': 42 + "a", 43 + "b", -44 | "c", # a comment regarding 'c' - - "b", - - # a comment regarding 'a': - - "a" +44 + "c", # a comment regarding 'c' 45 + "d" -46 | ] +46 + ] | note: This is an unsafe fix and may change runtime behavior @@ -321,27 +289,26 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -56 | "AUGUST", - - "Calendar", -57 | "DECEMBER", - - "Day", -58 | "FEBRUARY", -59 | "FRIDAY", - - "HTMLCalendar", - - "IllegalMonthError", -60 | "JANUARY", -61 | "JULY", -62 | "JUNE", - - "LocaleHTMLCalendar", -63 | "MARCH", -64 | "MAY", -65 | "MONDAY", - - "Month", -66 | "NOVEMBER", --------------------------------------------------------------------------------- -72 | "TUESDAY", - - "TextCalendar", -73 | "WEDNESDAY", +54 ~ __all__ = [ +55 + "APRIL", +56 + "AUGUST", +57 + "DECEMBER", +58 + "FEBRUARY", +59 + "FRIDAY", +60 + "JANUARY", +61 + "JULY", +62 + "JUNE", +63 + "MARCH", +64 + "MAY", +65 + "MONDAY", +66 + "NOVEMBER", +67 + "OCTOBER", +68 + "SATURDAY", +69 + "SEPTEMBER", +70 + "SUNDAY", +71 + "THURSDAY", +72 + "TUESDAY", +73 + "WEDNESDAY", 74 + "Calendar", 75 + "Day", 76 + "HTMLCalendar", @@ -349,13 +316,11 @@ help: Apply an isort-style sorting to `__all__` 78 + "LocaleHTMLCalendar", 79 + "Month", 80 + "TextCalendar", -81 | "calendar", -82 | "timegm", -83 | "weekday", - - "weekheader"] +81 + "calendar", +82 + "timegm", +83 + "weekday", 84 + "weekheader", 85 + ] -86 | | RUF022 [*] `__all__` is not sorted @@ -376,22 +341,17 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -90 | # comment0 - - __all__ = ("d", "a", # comment1 - - # comment2 - - "f", "b", - - "strangely", # comment3 - - # comment4 -91 + __all__ = ( -92 + "a", -93 + "b", -94 + "d", # comment1 -95 + # comment2 -96 + "f", -97 + # comment4 -98 | "formatted", -99 + "strangely", # comment3 -100 | # comment5 + 91 ~ __all__ = ( + 92 + "a", + 93 + "b", + 94 + "d", # comment1 + 95 + # comment2 + 96 + "f", + 97 + # comment4 + 98 + "formatted", + 99 + "strangely", # comment3 +100 + # comment5 +101 ~ ) # comment6 | note: This is an unsafe fix and may change runtime behavior @@ -415,15 +375,17 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -101 | __all__ = [ # comment0 +101 ~ __all__ = [ # comment0 102 + "ax", 103 + "bx", 104 + "cx", -105 | # comment1 -106 | # comment2 - - "dx", "cx", "bx", "ax" # comment3 +105 + # comment1 +106 + # comment2 107 + "dx" # comment3 -108 | # comment4 +108 + # comment4 +109 + # comment5 +110 + # comment6 +111 ~ ] # comment7 | note: This is an unsafe fix and may change runtime behavior @@ -453,22 +415,7 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -109 | - - __all__ = ["register", "lookup", "open", "EncodedFile", "BOM", "BOM_BE", - - "BOM_LE", "BOM32_BE", "BOM32_LE", "BOM64_BE", "BOM64_LE", - - "BOM_UTF8", "BOM_UTF16", "BOM_UTF16_LE", "BOM_UTF16_BE", - - "BOM_UTF32", "BOM_UTF32_LE", "BOM_UTF32_BE", - - "CodecInfo", "Codec", "IncrementalEncoder", "IncrementalDecoder", - - "StreamReader", "StreamWriter", - - "StreamReaderWriter", "StreamRecoder", - - "getencoder", "getdecoder", "getincrementalencoder", - - "getincrementaldecoder", "getreader", "getwriter", - - "encode", "decode", "iterencode", "iterdecode", - - "strict_errors", "ignore_errors", "replace_errors", - - "xmlcharrefreplace_errors", - - "backslashreplace_errors", "namereplace_errors", - - "register_error", "lookup_error"] -110 + __all__ = [ +110 ~ __all__ = [ 111 + "BOM", 112 + "BOM32_BE", 113 + "BOM32_LE", @@ -514,7 +461,6 @@ help: Apply an isort-style sorting to `__all__` 153 + "strict_errors", 154 + "xmlcharrefreplace_errors", 155 + ] -156 | | RUF022 [*] `__all__` is not sorted @@ -537,17 +483,14 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -125 | __all__: tuple[str, ...] = ( # a comment about the opening paren +125 ~ __all__: tuple[str, ...] = ( # a comment about the opening paren 126 + # multiline comment about "aaa" part 1 127 + # multiline comment about "aaa" part 2 128 + "aaa", -129 | # multiline comment about "bbb" part 1 -130 | # multiline comment about "bbb" part 2 -131 | "bbb", - - # multiline comment about "aaa" part 1 - - # multiline comment about "aaa" part 2 - - "aaa", -132 | ) +129 + # multiline comment about "bbb" part 1 +130 + # multiline comment about "bbb" part 2 +131 + "bbb", +132 + ) | note: This is an unsafe fix and may change runtime behavior @@ -569,15 +512,12 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -138 | __all__ = ( +138 ~ __all__ = ( 139 + "aadvark174", # the very long whitespace span before this comment is retained -140 | "aadvark237", - - "aadvark10092", - - "aadvark174", # the very long whitespace span before this comment is retained - - "aadvark532" # the even longer whitespace span before this comment is retained +140 + "aadvark237", 141 + "aadvark532", # the even longer whitespace span before this comment is retained 142 + "aadvark10092" -143 | ) +143 + ) | RUF022 [*] `__all__` is not sorted @@ -599,15 +539,13 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -145 | __all__.extend(( # comment0 +145 ~ __all__.extend(( # comment0 146 + # comment about bar 147 + "bar", # comment about bar -148 | # comment about foo - - "foo", # comment about foo - - # comment about bar - - "bar" # comment about bar +148 + # comment about foo 149 + "foo" # comment about foo -150 | # comment1 +150 + # comment1 +151 ~ )) # comment2 | note: This is an unsafe fix and may change runtime behavior @@ -628,15 +566,13 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -155 | ( # comment2 +155 ~ ( # comment2 156 + # comment about bar 157 + "bar", # comment about bar -158 | # comment about foo - - "foo", # comment about foo - - # comment about bar - - "bar" # comment about bar +158 + # comment about foo 159 + "foo" # comment about foo -160 | # comment3 +160 + # comment3 +161 ~ ) # comment4 | note: This is an unsafe fix and may change runtime behavior @@ -659,15 +595,13 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -164 | __all__.extend([ # comment0 +164 ~ __all__.extend([ # comment0 165 + # comment about bar 166 + "bar", # comment about bar -167 | # comment about foo - - "foo", # comment about foo - - # comment about bar - - "bar" # comment about bar +167 + # comment about foo 168 + "foo" # comment about foo -169 | # comment1 +169 + # comment1 +170 ~ ]) # comment2 | note: This is an unsafe fix and may change runtime behavior @@ -688,15 +622,13 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -174 | [ # comment2 +174 ~ [ # comment2 175 + # comment about bar 176 + "bar", # comment about bar -177 | # comment about foo - - "foo", # comment about foo - - # comment about bar - - "bar" # comment about bar +177 + # comment about foo 178 + "foo" # comment about foo -179 | # comment3 +179 + # comment3 +180 ~ ] # comment4 | note: This is an unsafe fix and may change runtime behavior @@ -716,17 +648,13 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -182 | - - __all__ = ["Style", "Treeview", - - # Extensions - - "LabeledScale", "OptionMenu", -183 + __all__ = [ +183 ~ __all__ = [ 184 + # Extensions 185 + "LabeledScale", 186 + "OptionMenu", 187 + "Style", 188 + "Treeview", -189 | ] +189 + ] | note: This is an unsafe fix and may change runtime behavior @@ -745,18 +673,13 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -187 | - - __all__ = ["Awaitable", "Coroutine", - - "AsyncIterable", "AsyncIterator", "AsyncGenerator", - - ] -188 + __all__ = [ +188 ~ __all__ = [ 189 + "AsyncGenerator", 190 + "AsyncIterable", 191 + "AsyncIterator", 192 + "Awaitable", 193 + "Coroutine", 194 + ] -195 | | RUF022 [*] `__all__` is not sorted @@ -776,12 +699,11 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -192 | __all__ = [ - - "foo", -193 | "bar", -194 | "baz", +192 ~ __all__ = [ +193 + "bar", +194 + "baz", 195 + "foo", -196 | ] +196 + ] | RUF022 `__all__` is not sorted @@ -848,12 +770,10 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -225 | __all__ = ( +225 ~ __all__ = ( 226 + "dumps", -227 | "loads", - - "dumps",) +227 + "loads", 228 + ) -229 | | RUF022 [*] `__all__` is not sorted @@ -871,12 +791,9 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -229 | __all__ = [ - - "loads", - - "dumps" , ] +229 ~ __all__ = [ 230 + "dumps", 231 + "loads" , ] -232 | | RUF022 [*] `__all__` is not sorted @@ -900,14 +817,17 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -232 | - - __all__ = ['xp', 'yp', - - 'canvas' -233 + __all__ = [ +233 ~ __all__ = [ 234 + 'canvas', 235 + 'xp', 236 + 'yp' -237 | +237 + +238 + # very strangely placed comment +239 + +240 + , +241 + +242 + # another strangely placed comment +243 + ] | RUF022 [*] `__all__` is not sorted @@ -931,15 +851,14 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -243 | __all__ = ( - - "foo" -244 | # strange comment 1 - - , -245 | # comment about bar - - "bar" +243 ~ __all__ = ( +244 + # strange comment 1 +245 + # comment about bar 246 + "bar", 247 + "foo" -248 | # strange comment 2 +248 + # strange comment 2 +249 + , +250 + ) | note: This is an unsafe fix and may change runtime behavior @@ -971,21 +890,21 @@ RUF022 [*] `__all__` is not sorted | help: Apply an isort-style sorting to `__all__` | -253 | __all__ = ( # comment about the opening paren - - # multiline strange comment 0a - - # multiline strange comment 0b - - "foo" # inline comment about foo -254 | # multiline strange comment 1a -255 | # multiline strange comment 1b - - , # comment about the comma?? +253 ~ __all__ = ( # comment about the opening paren +254 + # multiline strange comment 1a +255 + # multiline strange comment 1b 256 + # comment about the comma?? -257 | # comment about bar part a -258 | # comment about bar part b - - "bar" # inline comment about bar +257 + # comment about bar part a +258 + # comment about bar part b 259 + "bar", # inline comment about bar 260 + # multiline strange comment 0a 261 + # multiline strange comment 0b 262 + "foo" # inline comment about foo -263 | # strange multiline comment comment 2a +263 + # strange multiline comment comment 2a +264 + # strange multiline comment 2b +265 + , +266 + # strange multiline comment 3a +267 + # strange multiline comment 3b +268 ~ ) # comment about the closing paren | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF023_RUF023.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF023_RUF023.py.snap index e798afe9251fb..26dbd310ec43a 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF023_RUF023.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF023_RUF023.py.snap @@ -11,10 +11,8 @@ RUF023 [*] `Klass.__slots__` is not sorted | help: Apply a natural sort to `Klass.__slots__` | -5 | class Klass: - - __slots__ = ["d", "c", "b", "a"] # a comment that is untouched +6 - __slots__ = ["d", "c", "b", "a"] # a comment that is untouched 6 + __slots__ = ["a", "b", "c", "d"] # a comment that is untouched -7 | __slots__ = ("d", "c", "b", "a") | RUF023 [*] `Klass.__slots__` is not sorted @@ -29,10 +27,8 @@ RUF023 [*] `Klass.__slots__` is not sorted | help: Apply a natural sort to `Klass.__slots__` | -6 | __slots__ = ["d", "c", "b", "a"] # a comment that is untouched - - __slots__ = ("d", "c", "b", "a") +7 - __slots__ = ("d", "c", "b", "a") 7 + __slots__ = ("a", "b", "c", "d") -8 | | RUF023 [*] `Klass.__slots__` is not sorted @@ -47,10 +43,8 @@ RUF023 [*] `Klass.__slots__` is not sorted | help: Apply a natural sort to `Klass.__slots__` | -10 | # but unnecessary parens are not - - __slots__: set = {'b', "c", ((('a')))} +11 - __slots__: set = {'b', "c", ((('a')))} 11 + __slots__: set = {'a', 'b', "c"} -12 | # Trailing commas are also not retained for single-line definitions | RUF023 [*] `Klass.__slots__` is not sorted @@ -65,10 +59,8 @@ RUF023 [*] `Klass.__slots__` is not sorted | help: Apply a natural sort to `Klass.__slots__` | -13 | # (but they are in multiline definitions) - - __slots__: tuple = ("b", "c", "a",) +14 - __slots__: tuple = ("b", "c", "a",) 14 + __slots__: tuple = ("a", "b", "c") -15 | | RUF023 [*] `Klass2.__slots__` is not sorted @@ -83,10 +75,8 @@ RUF023 [*] `Klass2.__slots__` is not sorted | help: Apply a natural sort to `Klass2.__slots__` | -17 | if bool(): - - __slots__ = {"x": "docs for x", "m": "docs for m", "a": "docs for a"} +18 - __slots__ = {"x": "docs for x", "m": "docs for m", "a": "docs for a"} 18 + __slots__ = {"a": "docs for a", "m": "docs for m", "x": "docs for x"} -19 | else: | RUF023 [*] `Klass2.__slots__` is not sorted @@ -101,10 +91,8 @@ RUF023 [*] `Klass2.__slots__` is not sorted | help: Apply a natural sort to `Klass2.__slots__` | -19 | else: - - __slots__ = "foo3", "foo2", "foo1" # NB: an implicit tuple (without parens) +20 - __slots__ = "foo3", "foo2", "foo1" # NB: an implicit tuple (without parens) 20 + __slots__ = "foo1", "foo2", "foo3" # NB: an implicit tuple (without parens) -21 | | RUF023 [*] `Klass2.__slots__` is not sorted @@ -119,10 +107,8 @@ RUF023 [*] `Klass2.__slots__` is not sorted | help: Apply a natural sort to `Klass2.__slots__` | -21 | - - __slots__: list[str] = ["the", "three", "little", "pigs"] +22 - __slots__: list[str] = ["the", "three", "little", "pigs"] 22 + __slots__: list[str] = ["little", "pigs", "the", "three"] -23 | __slots__ = ("parenthesized_item"), "in", ("an_unparenthesized_tuple") | RUF023 [*] `Klass2.__slots__` is not sorted @@ -136,10 +122,8 @@ RUF023 [*] `Klass2.__slots__` is not sorted | help: Apply a natural sort to `Klass2.__slots__` | -22 | __slots__: list[str] = ["the", "three", "little", "pigs"] - - __slots__ = ("parenthesized_item"), "in", ("an_unparenthesized_tuple") +23 - __slots__ = ("parenthesized_item"), "in", ("an_unparenthesized_tuple") 23 + __slots__ = "an_unparenthesized_tuple", "in", "parenthesized_item" -24 | # we use natural sort, | RUF023 [*] `Klass2.__slots__` is not sorted @@ -154,10 +138,8 @@ RUF023 [*] `Klass2.__slots__` is not sorted | help: Apply a natural sort to `Klass2.__slots__` | -25 | # not alphabetical sort or "isort-style" sort - - __slots__ = {"aadvark237", "aadvark10092", "aadvark174", "aadvark532"} +26 - __slots__ = {"aadvark237", "aadvark10092", "aadvark174", "aadvark532"} 26 + __slots__ = {"aadvark174", "aadvark237", "aadvark532", "aadvark10092"} -27 | | RUF023 [*] `Klass3.__slots__` is not sorted @@ -178,17 +160,13 @@ RUF023 [*] `Klass3.__slots__` is not sorted | help: Apply a natural sort to `Klass3.__slots__` | -33 | __slots__ = ( - - "d0", +33 ~ __slots__ = ( 34 + # a comment regarding 'a0': 35 + "a0", 36 + "b0", -37 | "c0", # a comment regarding 'c0' - - "b0", - - # a comment regarding 'a0': - - "a0" +37 + "c0", # a comment regarding 'c0' 38 + "d0" -39 | ) +39 + ) | note: This is an unsafe fix and may change runtime behavior @@ -211,17 +189,13 @@ RUF023 [*] `Klass3.__slots__` is not sorted | help: Apply a natural sort to `Klass3.__slots__` | -40 | __slots__ = [ - - "d", +40 ~ __slots__ = [ 41 + # a comment regarding 'a': 42 + "a", 43 + "b", -44 | "c", # a comment regarding 'c' - - "b", - - # a comment regarding 'a': - - "a" +44 + "c", # a comment regarding 'c' 45 + "d" -46 | ] +46 + ] | note: This is an unsafe fix and may change runtime behavior @@ -244,22 +218,17 @@ RUF023 [*] `Klass4.__slots__` is not sorted | help: Apply a natural sort to `Klass4.__slots__` | -53 | # comment0 - - __slots__ = ("d", "a", # comment1 - - # comment2 - - "f", "b", - - "strangely", # comment3 - - # comment4 -54 + __slots__ = ( +54 ~ __slots__ = ( 55 + "a", 56 + "b", 57 + "d", # comment1 58 + # comment2 59 + "f", 60 + # comment4 -61 | "formatted", +61 + "formatted", 62 + "strangely", # comment3 -63 | # comment5 +63 + # comment5 +64 ~ ) # comment6 | note: This is an unsafe fix and may change runtime behavior @@ -283,15 +252,17 @@ RUF023 [*] `Klass4.__slots__` is not sorted | help: Apply a natural sort to `Klass4.__slots__` | -64 | __slots__ = [ # comment0 +64 ~ __slots__ = [ # comment0 65 + "ax", 66 + "bx", 67 + "cx", -68 | # comment1 -69 | # comment2 - - "dx", "cx", "bx", "ax" # comment3 +68 + # comment1 +69 + # comment2 70 + "dx" # comment3 -71 | # comment4 +71 + # comment4 +72 + # comment5 +73 + # comment6 +74 ~ ] # comment7 | note: This is an unsafe fix and may change runtime behavior @@ -342,49 +313,38 @@ RUF023 [*] `PurePath.__slots__` is not sorted | help: Apply a natural sort to `PurePath.__slots__` | -75 | __slots__ = ( - - # The `_raw_paths` slot stores unnormalized string paths. This is set - - # in the `__init__()` method. - - '_raw_paths', - - -76 | # The `_drv`, `_root` and `_tail_cached` slots store parsed and --------------------------------------------------------------------------------- -82 | # tail are normalized. - - '_drv', '_root', '_tail_cached', - - -83 + '_drv', -84 + # The `_hash` slot stores the hash of the case-normalized string -85 + # path. It's set when `__hash__()` is called for the first time. -86 + '_hash', -87 + # The `_parts_normcase_cached` slot stores the case-normalized -88 + # string path after splitting on path separators. It's set when the -89 + # `_parts_normcase` property is accessed for the first time. It's used -90 + # to implement comparison methods like `__lt__()`. -91 + '_parts_normcase_cached', -92 + # The `_raw_paths` slot stores unnormalized string paths. This is set -93 + # in the `__init__()` method. -94 + '_raw_paths', -95 + '_root', -96 | # The `_str` slot stores the string representation of the path, -97 | # computed from the drive, root and tail when `__str__()` is called -98 | # for the first time. It's used to implement `_str_normcase` -99 | '_str', - - -100 | # The `_str_normcase_cached` slot stores the string path with --------------------------------------------------------------------------------- -104 | '_str_normcase_cached', - - - - # The `_parts_normcase_cached` slot stores the case-normalized - - # string path after splitting on path separators. It's set when the - - # `_parts_normcase` property is accessed for the first time. It's used - - # to implement comparison methods like `__lt__()`. - - '_parts_normcase_cached', - - - - # The `_hash` slot stores the hash of the case-normalized string - - # path. It's set when `__hash__()` is called for the first time. - - '_hash', + 75 ~ __slots__ = ( + 76 + # The `_drv`, `_root` and `_tail_cached` slots store parsed and + 77 + # normalized parts of the path. They are set when any of the `drive`, + 78 + # `root` or `_tail` properties are accessed for the first time. The + 79 + # three-part division corresponds to the result of + 80 + # `os.path.splitroot()`, except that the tail is further split on path + 81 + # separators (i.e. it is a list of strings), and that the root and + 82 + # tail are normalized. + 83 + '_drv', + 84 + # The `_hash` slot stores the hash of the case-normalized string + 85 + # path. It's set when `__hash__()` is called for the first time. + 86 + '_hash', + 87 + # The `_parts_normcase_cached` slot stores the case-normalized + 88 + # string path after splitting on path separators. It's set when the + 89 + # `_parts_normcase` property is accessed for the first time. It's used + 90 + # to implement comparison methods like `__lt__()`. + 91 + '_parts_normcase_cached', + 92 + # The `_raw_paths` slot stores unnormalized string paths. This is set + 93 + # in the `__init__()` method. + 94 + '_raw_paths', + 95 + '_root', + 96 + # The `_str` slot stores the string representation of the path, + 97 + # computed from the drive, root and tail when `__str__()` is called + 98 + # for the first time. It's used to implement `_str_normcase` + 99 + '_str', +100 + # The `_str_normcase_cached` slot stores the string path with +101 + # normalized case. It is set when the `_str_normcase` property is +102 + # accessed for the first time. It's used to implement `__eq__()` +103 + # `__hash__()`, and `_parts_normcase` +104 + '_str_normcase_cached', 105 + '_tail_cached', -106 | ) +106 + ) | note: This is an unsafe fix and may change runtime behavior @@ -417,27 +377,20 @@ RUF023 [*] `ArgumentDescriptor.__slots__` is not sorted | help: Apply a natural sort to `ArgumentDescriptor.__slots__` | -113 | __slots__ = ( - - # name of descriptor record, also a module global name; a string - - 'name', - - +113 ~ __slots__ = ( 114 + # human-readable docs for this arg descriptor; a string 115 + 'doc', -116 | # length of argument, in bytes; an int; UP_TO_NEWLINE and -117 | # TAKEN_FROM_ARGUMENT{1,4,8} are negative values for variable-length -118 | # cases -119 | 'n', - - +116 + # length of argument, in bytes; an int; UP_TO_NEWLINE and +117 + # TAKEN_FROM_ARGUMENT{1,4,8} are negative values for variable-length +118 + # cases +119 + 'n', 120 + # name of descriptor record, also a module global name; a string 121 + 'name', -122 | # a function taking a file-like object, reading this kind of argument -123 | # from the object at the current position, advancing the current -124 | # position by n bytes, and returning the value of the argument -125 | 'reader', - - - - # human-readable docs for this arg descriptor; a string - - 'doc', -126 | ) +122 + # a function taking a file-like object, reading this kind of argument +123 + # from the object at the current position, advancing the current +124 + # position by n bytes, and returning the value of the argument +125 + 'reader', +126 + ) | note: This is an unsafe fix and may change runtime behavior @@ -515,15 +468,11 @@ RUF023 [*] `BezierBuilder.__slots__` is not sorted | help: Apply a natural sort to `BezierBuilder.__slots__` | -161 | class BezierBuilder: - - __slots__ = ('xp', 'yp', - - 'canvas',) -162 + __slots__ = ( +162 ~ __slots__ = ( 163 + 'canvas', 164 + 'xp', 165 + 'yp', 166 + ) -167 | | RUF023 [*] `BezierBuilder2.__slots__` is not sorted @@ -539,14 +488,10 @@ RUF023 [*] `BezierBuilder2.__slots__` is not sorted | help: Apply a natural sort to `BezierBuilder2.__slots__` | -165 | class BezierBuilder2: - - __slots__ = {'xp', 'yp', - - 'canvas' , } -166 + __slots__ = { +166 ~ __slots__ = { 167 + 'canvas', 168 + 'xp', 169 + 'yp' , } -170 | | RUF023 [*] `BezierBuilder3.__slots__` is not sorted @@ -569,14 +514,17 @@ RUF023 [*] `BezierBuilder3.__slots__` is not sorted | help: Apply a natural sort to `BezierBuilder3.__slots__` | -169 | class BezierBuilder3: - - __slots__ = ['xp', 'yp', - - 'canvas' -170 + __slots__ = [ +170 ~ __slots__ = [ 171 + 'canvas', 172 + 'xp', 173 + 'yp' -174 | +174 + +175 + # very strangely placed comment +176 + +177 + , +178 + +179 + # another strangely placed comment +180 + ] | RUF023 [*] `BezierBuilder4.__slots__` is not sorted @@ -599,15 +547,14 @@ RUF023 [*] `BezierBuilder4.__slots__` is not sorted | help: Apply a natural sort to `BezierBuilder4.__slots__` | -181 | __slots__ = ( - - "foo" -182 | # strange comment 1 - - , -183 | # comment about bar - - "bar" +181 ~ __slots__ = ( +182 + # strange comment 1 +183 + # comment about bar 184 + "bar", 185 + "foo" -186 | # strange comment 2 +186 + # strange comment 2 +187 + , +188 + ) | note: This is an unsafe fix and may change runtime behavior @@ -623,17 +570,12 @@ RUF023 [*] `BezierBuilder4.__slots__` is not sorted | |__________________^ help: Apply a natural sort to `BezierBuilder4.__slots__` | -190 | - - __slots__ = {"foo", "bar", - - "baz", "bingo" - - } -191 + __slots__ = { +191 ~ __slots__ = { 192 + "bar", 193 + "baz", 194 + "bingo", 195 + "foo" 196 + } -197 | | RUF023 [*] `VeryDRY.__slots__` is not sorted @@ -647,9 +589,7 @@ RUF023 [*] `VeryDRY.__slots__` is not sorted | help: Apply a natural sort to `VeryDRY.__slots__` | -198 | # since the `__slots__` binding is used by the `__match_args__` definition - - __slots__ = ("foo", "bar") +199 - __slots__ = ("foo", "bar") 199 + __slots__ = ("bar", "foo") -200 | __match_args__ = __slots__ | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF024_RUF024.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF024_RUF024.py.snap index 8b12e431e1d7a..ea600fe57d439 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF024_RUF024.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF024_RUF024.py.snap @@ -11,12 +11,10 @@ RUF024 [*] Do not pass mutable objects as values to `dict.fromkeys` 11 | dict.fromkeys(pierogi_fillings, {}) | help: Replace with comprehension - | -8 | # Errors. - - dict.fromkeys(pierogi_fillings, []) -9 + {key: [] for key in pierogi_fillings} -10 | dict.fromkeys(pierogi_fillings, list()) - | + | +9 - dict.fromkeys(pierogi_fillings, []) +9 + {key: [] for key in pierogi_fillings} + | note: This is an unsafe fix and may change runtime behavior RUF024 [*] Do not pass mutable objects as values to `dict.fromkeys` @@ -31,10 +29,8 @@ RUF024 [*] Do not pass mutable objects as values to `dict.fromkeys` | help: Replace with comprehension | -9 | dict.fromkeys(pierogi_fillings, []) - - dict.fromkeys(pierogi_fillings, list()) +10 - dict.fromkeys(pierogi_fillings, list()) 10 + {key: list() for key in pierogi_fillings} -11 | dict.fromkeys(pierogi_fillings, {}) | note: This is an unsafe fix and may change runtime behavior @@ -50,10 +46,8 @@ RUF024 [*] Do not pass mutable objects as values to `dict.fromkeys` | help: Replace with comprehension | -10 | dict.fromkeys(pierogi_fillings, list()) - - dict.fromkeys(pierogi_fillings, {}) +11 - dict.fromkeys(pierogi_fillings, {}) 11 + {key: {} for key in pierogi_fillings} -12 | dict.fromkeys(pierogi_fillings, set()) | note: This is an unsafe fix and may change runtime behavior @@ -69,10 +63,8 @@ RUF024 [*] Do not pass mutable objects as values to `dict.fromkeys` | help: Replace with comprehension | -11 | dict.fromkeys(pierogi_fillings, {}) - - dict.fromkeys(pierogi_fillings, set()) +12 - dict.fromkeys(pierogi_fillings, set()) 12 + {key: set() for key in pierogi_fillings} -13 | dict.fromkeys(pierogi_fillings, {"pre": "populated!"}) | note: This is an unsafe fix and may change runtime behavior @@ -88,10 +80,8 @@ RUF024 [*] Do not pass mutable objects as values to `dict.fromkeys` | help: Replace with comprehension | -12 | dict.fromkeys(pierogi_fillings, set()) - - dict.fromkeys(pierogi_fillings, {"pre": "populated!"}) +13 - dict.fromkeys(pierogi_fillings, {"pre": "populated!"}) 13 + {key: {"pre": "populated!"} for key in pierogi_fillings} -14 | dict.fromkeys(pierogi_fillings, dict()) | note: This is an unsafe fix and may change runtime behavior @@ -107,10 +97,8 @@ RUF024 [*] Do not pass mutable objects as values to `dict.fromkeys` | help: Replace with comprehension | -13 | dict.fromkeys(pierogi_fillings, {"pre": "populated!"}) - - dict.fromkeys(pierogi_fillings, dict()) +14 - dict.fromkeys(pierogi_fillings, dict()) 14 + {key: dict() for key in pierogi_fillings} -15 | import builtins | note: This is an unsafe fix and may change runtime behavior @@ -126,10 +114,8 @@ RUF024 [*] Do not pass mutable objects as values to `dict.fromkeys` | help: Replace with comprehension | -15 | import builtins - - builtins.dict.fromkeys(pierogi_fillings, dict()) +16 - builtins.dict.fromkeys(pierogi_fillings, dict()) 16 + {key: dict() for key in pierogi_fillings} -17 | | note: This is an unsafe fix and may change runtime behavior @@ -142,8 +128,7 @@ RUF024 [*] Do not pass mutable objects as values to `dict.fromkeys` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with comprehension | -38 | key_0 = "z" - - dict.fromkeys("ABC", list(key)) +39 - dict.fromkeys("ABC", list(key)) 39 + {key_1: list(key) for key_1 in "ABC"} | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF026_RUF026.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF026_RUF026.py.snap index b9a000ba5109d..4ececfaf647be 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF026_RUF026.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF026_RUF026.py.snap @@ -9,10 +9,8 @@ RUF026 [*] `default_factory` is a positional-only argument to `defaultdict` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `defaultdict(default_factory=int)` | -10 | def func(): - - defaultdict(default_factory=int) # RUF026 +11 - defaultdict(default_factory=int) # RUF026 11 + defaultdict(int) # RUF026 -12 | | note: This is an unsafe fix and may change runtime behavior @@ -24,10 +22,8 @@ RUF026 [*] `default_factory` is a positional-only argument to `defaultdict` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `defaultdict(default_factory=float)` | -14 | def func(): - - defaultdict(default_factory=float) # RUF026 +15 - defaultdict(default_factory=float) # RUF026 15 + defaultdict(float) # RUF026 -16 | | note: This is an unsafe fix and may change runtime behavior @@ -39,10 +35,8 @@ RUF026 [*] `default_factory` is a positional-only argument to `defaultdict` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `defaultdict(default_factory=dict)` | -18 | def func(): - - defaultdict(default_factory=dict) # RUF026 +19 - defaultdict(default_factory=dict) # RUF026 19 + defaultdict(dict) # RUF026 -20 | | note: This is an unsafe fix and may change runtime behavior @@ -54,10 +48,8 @@ RUF026 [*] `default_factory` is a positional-only argument to `defaultdict` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `defaultdict(default_factory=list)` | -22 | def func(): - - defaultdict(default_factory=list) # RUF026 +23 - defaultdict(default_factory=list) # RUF026 23 + defaultdict(list) # RUF026 -24 | | note: This is an unsafe fix and may change runtime behavior @@ -69,10 +61,8 @@ RUF026 [*] `default_factory` is a positional-only argument to `defaultdict` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `defaultdict(default_factory=tuple)` | -26 | def func(): - - defaultdict(default_factory=tuple) # RUF026 +27 - defaultdict(default_factory=tuple) # RUF026 27 + defaultdict(tuple) # RUF026 -28 | | note: This is an unsafe fix and may change runtime behavior @@ -85,10 +75,8 @@ RUF026 [*] `default_factory` is a positional-only argument to `defaultdict` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `defaultdict(default_factory=foo)` | -33 | - - defaultdict(default_factory=foo) # RUF026 +34 - defaultdict(default_factory=foo) # RUF026 34 + defaultdict(foo) # RUF026 -35 | | note: This is an unsafe fix and may change runtime behavior @@ -100,10 +88,8 @@ RUF026 [*] `default_factory` is a positional-only argument to `defaultdict` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `defaultdict(default_factory=lambda: 1)` | -37 | def func(): - - defaultdict(default_factory=lambda: 1) # RUF026 +38 - defaultdict(default_factory=lambda: 1) # RUF026 38 + defaultdict(lambda: 1) # RUF026 -39 | | note: This is an unsafe fix and may change runtime behavior @@ -116,10 +102,8 @@ RUF026 [*] `default_factory` is a positional-only argument to `defaultdict` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `defaultdict(default_factory=deque)` | -43 | - - defaultdict(default_factory=deque) # RUF026 +44 - defaultdict(default_factory=deque) # RUF026 44 + defaultdict(deque) # RUF026 -45 | | note: This is an unsafe fix and may change runtime behavior @@ -132,10 +116,8 @@ RUF026 [*] `default_factory` is a positional-only argument to `defaultdict` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `defaultdict(default_factory=MyCallable())` | -51 | - - defaultdict(default_factory=MyCallable()) # RUF026 +52 - defaultdict(default_factory=MyCallable()) # RUF026 52 + defaultdict(MyCallable()) # RUF026 -53 | | note: This is an unsafe fix and may change runtime behavior @@ -147,10 +129,8 @@ RUF026 [*] `default_factory` is a positional-only argument to `defaultdict` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `defaultdict(default_factory=tuple)` | -55 | def func(): - - defaultdict(default_factory=tuple, member=1) # RUF026 +56 - defaultdict(default_factory=tuple, member=1) # RUF026 56 + defaultdict(tuple, member=1) # RUF026 -57 | | note: This is an unsafe fix and may change runtime behavior @@ -162,10 +142,8 @@ RUF026 [*] `default_factory` is a positional-only argument to `defaultdict` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `defaultdict(default_factory=tuple)` | -59 | def func(): - - defaultdict(member=1, default_factory=tuple) # RUF026 +60 - defaultdict(member=1, default_factory=tuple) # RUF026 60 + defaultdict(tuple, member=1) # RUF026 -61 | | note: This is an unsafe fix and may change runtime behavior @@ -177,10 +155,8 @@ RUF026 [*] `default_factory` is a positional-only argument to `defaultdict` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `defaultdict(default_factory=tuple)` | -63 | def func(): - - defaultdict(member=1, default_factory=tuple,) # RUF026 +64 - defaultdict(member=1, default_factory=tuple,) # RUF026 64 + defaultdict(tuple, member=1,) # RUF026 -65 | | note: This is an unsafe fix and may change runtime behavior @@ -195,11 +171,9 @@ RUF026 [*] `default_factory` is a positional-only argument to `defaultdict` | |_____^ help: Replace with `defaultdict(default_factory=tuple)` | -68 | defaultdict( - - member=1, - - default_factory=tuple, +69 - member=1, +70 - default_factory=tuple, 69 + tuple, member=1, -70 | ) # RUF026 | note: This is an unsafe fix and may change runtime behavior @@ -214,10 +188,8 @@ RUF026 [*] `default_factory` is a positional-only argument to `defaultdict` | |_____^ help: Replace with `defaultdict(default_factory=tuple)` | -75 | defaultdict( - - default_factory=tuple, - - member=1, +76 - default_factory=tuple, +77 - member=1, 76 + tuple, member=1, -77 | ) # RUF026 | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF027_RUF027_0.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF027_RUF027_0.py.snap index 5c3d0ab42b529..aa0c97a8b5957 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF027_RUF027_0.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF027_RUF027_0.py.snap @@ -10,11 +10,8 @@ RUF027 [*] Possible f-string without an `f` prefix | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add `f` prefix | -4 | - - print("but don't ignore this: {val}") # RUF027 -5 + print(f"but don't ignore this: {val}") # RUF027 -6 | - | +5 | print(f"but don't ignore this: {val}") # RUF027 + | + note: This is an unsafe fix and may change runtime behavior RUF027 [*] Possible f-string without an `f` prefix @@ -28,11 +25,8 @@ RUF027 [*] Possible f-string without an `f` prefix | help: Add `f` prefix | -9 | a = 4 - - b = "{a}" # RUF027 -10 + b = f"{a}" # RUF027 -11 | c = "{a} {b} f'{val}' " # RUF027 - | +10 | b = f"{a}" # RUF027 + | + note: This is an unsafe fix and may change runtime behavior RUF027 [*] Possible f-string without an `f` prefix @@ -44,11 +38,8 @@ RUF027 [*] Possible f-string without an `f` prefix | ^^^^^^^^^^^^^^^^^^^ help: Add `f` prefix | -10 | b = "{a}" # RUF027 - - c = "{a} {b} f'{val}' " # RUF027 -11 + c = f"{a} {b} f'{val}' " # RUF027 -12 | - | +11 | c = f"{a} {b} f'{val}' " # RUF027 + | + note: This is an unsafe fix and may change runtime behavior RUF027 [*] Possible f-string without an `f` prefix @@ -62,11 +53,8 @@ RUF027 [*] Possible f-string without an `f` prefix | help: Add `f` prefix | -20 | a = 4 - - b = r"raw string with formatting: {a}" # RUF027 -21 + b = fr"raw string with formatting: {a}" # RUF027 -22 | c = r"raw string with \backslashes\ and \"escaped quotes\": {a}" # RUF027 - | +21 | b = fr"raw string with formatting: {a}" # RUF027 + | + note: This is an unsafe fix and may change runtime behavior RUF027 [*] Possible f-string without an `f` prefix @@ -78,11 +66,8 @@ RUF027 [*] Possible f-string without an `f` prefix | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add `f` prefix | -21 | b = r"raw string with formatting: {a}" # RUF027 - - c = r"raw string with \backslashes\ and \"escaped quotes\": {a}" # RUF027 -22 + c = fr"raw string with \backslashes\ and \"escaped quotes\": {a}" # RUF027 -23 | - | +22 | c = fr"raw string with \backslashes\ and \"escaped quotes\": {a}" # RUF027 + | + note: This is an unsafe fix and may change runtime behavior RUF027 [*] Possible f-string without an `f` prefix @@ -96,11 +81,8 @@ RUF027 [*] Possible f-string without an `f` prefix | help: Add `f` prefix | -26 | a = 4 - - print("Hello, {name}!") # RUF027 -27 + print(f"Hello, {name}!") # RUF027 -28 | print("The test value we're using today is {a}") # RUF027 - | +27 | print(f"Hello, {name}!") # RUF027 + | + note: This is an unsafe fix and may change runtime behavior RUF027 [*] Possible f-string without an `f` prefix @@ -112,11 +94,8 @@ RUF027 [*] Possible f-string without an `f` prefix | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add `f` prefix | -27 | print("Hello, {name}!") # RUF027 - - print("The test value we're using today is {a}") # RUF027 -28 + print(f"The test value we're using today is {a}") # RUF027 -29 | - | +28 | print(f"The test value we're using today is {a}") # RUF027 + | + note: This is an unsafe fix and may change runtime behavior RUF027 [*] Possible f-string without an `f` prefix @@ -128,11 +107,8 @@ RUF027 [*] Possible f-string without an `f` prefix | ^^^^^ help: Add `f` prefix | -32 | a = 4 - - print(do_nothing(do_nothing("{a}"))) # RUF027 -33 + print(do_nothing(do_nothing(f"{a}"))) # RUF027 -34 | - | +33 | print(do_nothing(do_nothing(f"{a}"))) # RUF027 + | + note: This is an unsafe fix and may change runtime behavior RUF027 [*] Possible f-string without an `f` prefix @@ -147,11 +123,8 @@ RUF027 [*] Possible f-string without an `f` prefix | help: Add `f` prefix | -38 | c = a - - single_line = """ {a} """ # RUF027 -39 + single_line = f""" {a} """ # RUF027 -40 | # RUF027 - | +39 | single_line = f""" {a} """ # RUF027 + | + note: This is an unsafe fix and may change runtime behavior RUF027 [*] Possible f-string without an `f` prefix @@ -166,11 +139,8 @@ RUF027 [*] Possible f-string without an `f` prefix | |_______^ help: Add `f` prefix | -40 | # RUF027 - - multi_line = a = """b { # comment -41 + multi_line = a = f"""b { # comment -42 | c} d - | +41 | multi_line = a = f"""b { # comment + | + note: This is an unsafe fix and may change runtime behavior RUF027 [*] Possible f-string without an `f` prefix @@ -185,11 +155,8 @@ RUF027 [*] Possible f-string without an `f` prefix | |_____^ help: Add `f` prefix | -48 | # RUF027 - - b = " {\ -49 + b = f" {\ -50 | a} \ - | +49 | b = f" {\ + | + note: This is an unsafe fix and may change runtime behavior RUF027 [*] Possible f-string without an `f` prefix @@ -203,11 +170,8 @@ RUF027 [*] Possible f-string without an `f` prefix | help: Add `f` prefix | -55 | a = 4 - - b = "{a}" "+" "{b}" r" \\ " # RUF027 for the first part only -56 + b = f"{a}" "+" "{b}" r" \\ " # RUF027 for the first part only -57 | print(f"{a}" "{a}" f"{b}") # RUF027 - | +56 | b = f"{a}" "+" "{b}" r" \\ " # RUF027 for the first part only + | + note: This is an unsafe fix and may change runtime behavior RUF027 [*] Possible f-string without an `f` prefix @@ -219,11 +183,8 @@ RUF027 [*] Possible f-string without an `f` prefix | ^^^^^ help: Add `f` prefix | -56 | b = "{a}" "+" "{b}" r" \\ " # RUF027 for the first part only - - print(f"{a}" "{a}" f"{b}") # RUF027 -57 + print(f"{a}" f"{a}" f"{b}") # RUF027 -58 | - | +57 | print(f"{a}" f"{a}" f"{b}") # RUF027 + | + note: This is an unsafe fix and may change runtime behavior RUF027 [*] Possible f-string without an `f` prefix @@ -235,11 +196,8 @@ RUF027 [*] Possible f-string without an `f` prefix | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Add `f` prefix | -61 | a = 4 - - b = "\"not escaped:\" '{a}' \"escaped:\": '{{c}}'" # RUF027 -62 + b = f"\"not escaped:\" '{a}' \"escaped:\": '{{c}}'" # RUF027 -63 | - | +62 | b = f"\"not escaped:\" '{a}' \"escaped:\": '{{c}}'" # RUF027 + | + note: This is an unsafe fix and may change runtime behavior RUF027 [*] Possible f-string without an `f` prefix @@ -254,11 +212,8 @@ RUF027 [*] Possible f-string without an `f` prefix | help: Add `f` prefix | -69 | last = "Appleseed" - - value.method("{first} {last}") # RUF027 -70 + value.method(f"{first} {last}") # RUF027 -71 | - | +70 | value.method(f"{first} {last}") # RUF027 + | + note: This is an unsafe fix and may change runtime behavior RUF027 [*] Possible f-string without an `f` prefix @@ -273,11 +228,8 @@ RUF027 [*] Possible f-string without an `f` prefix | help: Add `f` prefix | -73 | a = 4 - - b = "{a:b} {a:^5}" -74 + b = f"{a:b} {a:^5}" -75 | - | +74 | b = f"{a:b} {a:^5}" + | + note: This is an unsafe fix and may change runtime behavior RUF027 [*] Possible f-string without an `f` prefix @@ -292,11 +244,8 @@ RUF027 [*] Possible f-string without an `f` prefix | help: Add `f` prefix | -91 | x = "test" - - print("Hello {'\\n'}{x}") # Should not trigger RUF027 for Python < 3.12 -92 + print(f"Hello {'\\n'}{x}") # Should not trigger RUF027 for Python < 3.12 -93 | - | +92 | print(f"Hello {'\\n'}{x}") # Should not trigger RUF027 for Python < 3.12 + | + note: This is an unsafe fix and may change runtime behavior RUF027 [*] Possible f-string without an `f` prefix @@ -313,11 +262,8 @@ RUF027 [*] Possible f-string without an `f` prefix | help: Add `f` prefix | -97 | x = "!" - - print("""{x # } -98 + print(f"""{x # } -99 | }""") - | +98 | print(f"""{x # } + | + note: This is an unsafe fix and may change runtime behavior RUF027 [*] Possible f-string without an `f` prefix @@ -331,11 +277,8 @@ RUF027 [*] Possible f-string without an `f` prefix | help: Add `f` prefix | -104 | x = "world" - - print("Hello {'#'}{x}") # RUF027: `#` is inside a string, not a comment -105 + print(f"Hello {'#'}{x}") # RUF027: `#` is inside a string, not a comment -106 | print("Hello {\"#\"}{x}") # RUF027: same, double-quoted - | +105 | print(f"Hello {'#'}{x}") # RUF027: `#` is inside a string, not a comment + | + note: This is an unsafe fix and may change runtime behavior RUF027 [*] Possible f-string without an `f` prefix @@ -349,11 +292,8 @@ RUF027 [*] Possible f-string without an `f` prefix | help: Add `f` prefix | -111 | n = 255 - - print("Hex: {n:#x}") # RUF027: `#` is in format spec, not a comment -112 + print(f"Hex: {n:#x}") # RUF027: `#` is in format spec, not a comment -113 | print("Oct: {n:#o}") # RUF027: same - | +112 | print(f"Hex: {n:#x}") # RUF027: `#` is in format spec, not a comment + | + note: This is an unsafe fix and may change runtime behavior RUF027 [*] Possible f-string without an `f` prefix @@ -368,9 +308,6 @@ RUF027 [*] Possible f-string without an `f` prefix | help: Add `f` prefix | -112 | print("Hex: {n:#x}") # RUF027: `#` is in format spec, not a comment - - print("Oct: {n:#o}") # RUF027: same -113 + print(f"Oct: {n:#o}") # RUF027: same -114 | - | +113 | print(f"Oct: {n:#o}") # RUF027: same + | + note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF028_RUF028.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF028_RUF028.py.snap index f32c717ea7eda..d389150abcaac 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF028_RUF028.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF028_RUF028.py.snap @@ -13,9 +13,7 @@ RUF028 [*] This suppression comment is invalid because it cannot be in an expres | help: Remove this comment | -2 | test_list = [ - - # fmt: off -3 | 1, +3 - # fmt: off | note: This is an unsafe fix and may change runtime behavior @@ -30,9 +28,7 @@ RUF028 [*] This suppression comment is invalid because it cannot be on its own l | help: Remove this comment | -11 | def fmt_skip_on_own_line(): - - # fmt: skip -12 | pass # fmt: skip +12 - # fmt: skip | note: This is an unsafe fix and may change runtime behavior @@ -47,9 +43,7 @@ RUF028 [*] This suppression comment is invalid because it cannot be after a deco | help: Remove this comment | -16 | @fmt_skip_on_own_line - - # fmt: off -17 | @fmt_off_between_lists +17 - # fmt: off | note: This is an unsafe fix and may change runtime behavior @@ -64,9 +58,7 @@ RUF028 [*] This suppression comment is invalid because it cannot be after a deco | help: Remove this comment | -23 | @fmt_off_between_decorators - - # fmt: off -24 | class FmtOffBetweenClassDecorators: +24 - # fmt: off | note: This is an unsafe fix and may change runtime behavior @@ -82,9 +74,7 @@ RUF028 [*] This suppression comment is invalid because it cannot be directly abo | help: Remove this comment | -32 | print(x) - - # fmt: off -33 | else: +33 - # fmt: off | note: This is an unsafe fix and may change runtime behavior @@ -100,9 +90,7 @@ RUF028 [*] This suppression comment is invalid because it cannot be directly abo | help: Remove this comment | -38 | # fmt: off - - # fmt: off -39 | else: +39 - # fmt: off | note: This is an unsafe fix and may change runtime behavior @@ -118,9 +106,7 @@ RUF028 [*] This suppression comment is invalid because it cannot be directly abo | help: Remove this comment | -44 | # fmt: on - - # fmt: off -45 | else: +45 - # fmt: off | note: This is an unsafe fix and may change runtime behavior @@ -136,9 +122,7 @@ RUF028 [*] This suppression comment is invalid because it cannot be after a deco | help: Remove this comment | -51 | @classmethod - - # fmt: off -52 | def cls_method_a( +52 - # fmt: off | note: This is an unsafe fix and may change runtime behavior @@ -154,9 +138,7 @@ RUF028 [*] This suppression comment is invalid because it cannot be in an expres | help: Remove this comment | -53 | def cls_method_a( - - # fmt: off -54 | cls, +54 - # fmt: off | note: This is an unsafe fix and may change runtime behavior @@ -171,10 +153,8 @@ RUF028 [*] This suppression comment is invalid because it cannot be at the end o | help: Remove this comment | -61 | # fmt: off - - val = 5 # fmt: on +62 - val = 5 # fmt: on 62 + val = 5 -63 | pass # fmt: on | note: This is an unsafe fix and may change runtime behavior @@ -187,9 +167,7 @@ RUF028 [*] This suppression comment is invalid because it cannot be at the end o | ^^^^^^^^^ help: Remove this comment | -62 | val = 5 # fmt: on - - pass # fmt: on +63 - pass # fmt: on 63 + pass -64 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF030_RUF030.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF030_RUF030.py.snap index 5da2b5d855f56..e6a1a28d90184 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF030_RUF030.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF030_RUF030.py.snap @@ -13,10 +13,8 @@ RUF030 [*] `print()` call in `assert` statement is likely unintentional | help: Remove `print` | -5 | # - single StringLiteral - - assert True, print("This print is not intentional.") +6 - assert True, print("This print is not intentional.") 6 + assert True, "This print is not intentional." -7 | | note: This is an unsafe fix and may change runtime behavior @@ -32,10 +30,8 @@ RUF030 [*] `print()` call in `assert` statement is likely unintentional | help: Remove `print` | -10 | # - single StringLiteral - - assert True, print("This print" " is not intentional.") +11 - assert True, print("This print" " is not intentional.") 11 + assert True, "This print is not intentional." -12 | | note: This is an unsafe fix and may change runtime behavior @@ -51,10 +47,8 @@ RUF030 [*] `print()` call in `assert` statement is likely unintentional | help: Remove `print` | -15 | # - single StringLiteral concatenated with " " - - assert True, print("This print", "is not intentional") +16 - assert True, print("This print", "is not intentional") 16 + assert True, "This print is not intentional" -17 | | note: This is an unsafe fix and may change runtime behavior @@ -70,10 +64,8 @@ RUF030 [*] `print()` call in `assert` statement is likely unintentional | help: Remove `print` | -20 | # - single stringliteral concatenated with " " only between `print` and `is` - - assert True, print("This " "print", "is not intentional.") +21 - assert True, print("This " "print", "is not intentional.") 21 + assert True, "This print is not intentional." -22 | | note: This is an unsafe fix and may change runtime behavior @@ -89,10 +81,8 @@ RUF030 [*] `print()` call in `assert` statement is likely unintentional | help: Remove `print` | -25 | # - single FString concatenated with " " - - assert True, print("This", print.__name__, "is not intentional.") +26 - assert True, print("This", print.__name__, "is not intentional.") 26 + assert True, f"This {print.__name__} is not intentional." -27 | | note: This is an unsafe fix and may change runtime behavior @@ -108,10 +98,8 @@ RUF030 [*] `print()` call in `assert` statement is likely unintentional | help: Remove `print` | -30 | # - single StringLiteral concatenated with " " - - assert True, print("This print", 'is not intentional', """and should be removed""") +31 - assert True, print("This print", 'is not intentional', """and should be removed""") 31 + assert True, "This print is not intentional and should be removed" -32 | | note: This is an unsafe fix and may change runtime behavior @@ -127,10 +115,8 @@ RUF030 [*] `print()` call in `assert` statement is likely unintentional | help: Remove `print` | -35 | # - single StringLiteral concatenated with " " and escaped brackets - - assert True, print("This print", 'is not "intentional"', """and "should" be 'removed'""") +36 - assert True, print("This print", 'is not "intentional"', """and "should" be 'removed'""") 36 + assert True, "This print is not \"intentional\" and \"should\" be 'removed'" -37 | | note: This is an unsafe fix and may change runtime behavior @@ -146,10 +132,8 @@ RUF030 [*] `print()` call in `assert` statement is likely unintentional | help: Remove `print` | -40 | # - single StringLiteral concatenated with "|" - - assert True, print("This print", "is not intentional", sep="|") +41 - assert True, print("This print", "is not intentional", sep="|") 41 + assert True, "This print|is not intentional" -42 | | note: This is an unsafe fix and may change runtime behavior @@ -165,10 +149,8 @@ RUF030 [*] `print()` call in `assert` statement is likely unintentional | help: Remove `print` | -45 | # - single StringLiteral concatenated with " " - - assert True, print("This print", "is not intentional", sep=None) +46 - assert True, print("This print", "is not intentional", sep=None) 46 + assert True, "This print is not intentional" -47 | | note: This is an unsafe fix and may change runtime behavior @@ -184,10 +166,8 @@ RUF030 [*] `print()` call in `assert` statement is likely unintentional | help: Remove `print` | -50 | # - single FString concatenated with "{U00A0}" - - assert True, print("This print", "is not intentional", sep=U00A0) +51 - assert True, print("This print", "is not intentional", sep=U00A0) 51 + assert True, f"This print{U00A0}is not intentional" -52 | | note: This is an unsafe fix and may change runtime behavior @@ -203,10 +183,8 @@ RUF030 [*] `print()` call in `assert` statement is likely unintentional | help: Remove `print` | -55 | # - single StringLiteral - - assert True, print(f"This f-string is just a literal.") +56 - assert True, print(f"This f-string is just a literal.") 56 + assert True, "This f-string is just a literal." -57 | | note: This is an unsafe fix and may change runtime behavior @@ -222,10 +200,8 @@ RUF030 [*] `print()` call in `assert` statement is likely unintentional | help: Remove `print` | -60 | # - single FString concatenated with " " - - assert True, print("This print", f"is not {'intentional':s}") +61 - assert True, print("This print", f"is not {'intentional':s}") 61 + assert True, f"This print is not {'intentional':s}" -62 | | note: This is an unsafe fix and may change runtime behavior @@ -241,10 +217,8 @@ RUF030 [*] `print()` call in `assert` statement is likely unintentional | help: Remove `print` | -65 | # - single FString concatenated with "|" - - assert True, print("This print", f"is not {'intentional':s}", sep="|") +66 - assert True, print("This print", f"is not {'intentional':s}", sep="|") 66 + assert True, f"This print|is not {'intentional':s}" -67 | | note: This is an unsafe fix and may change runtime behavior @@ -260,10 +234,8 @@ RUF030 [*] `print()` call in `assert` statement is likely unintentional | help: Remove `print` | -70 | # - single FString - - assert True, print(f"This print is not {'intentional':s}") +71 - assert True, print(f"This print is not {'intentional':s}") 71 + assert True, f"This print is not {'intentional':s}" -72 | | note: This is an unsafe fix and may change runtime behavior @@ -279,10 +251,8 @@ RUF030 [*] `print()` call in `assert` statement is likely unintentional | help: Remove `print` | -75 | # - single FString - - assert True, print(f"This print is not {'intentional':s}", sep="|") +76 - assert True, print(f"This print is not {'intentional':s}", sep="|") 76 + assert True, f"This print is not {'intentional':s}" -77 | | note: This is an unsafe fix and may change runtime behavior @@ -298,10 +268,8 @@ RUF030 [*] `print()` call in `assert` statement is likely unintentional | help: Remove `print` | -82 | maintainer = "John Doe" - - assert True, print("Unreachable due to", condition, f", ask {maintainer} for advice", sep=U00A0) +83 - assert True, print("Unreachable due to", condition, f", ask {maintainer} for advice", sep=U00A0) 83 + assert True, f"Unreachable due to{U00A0}{condition}{U00A0}, ask {maintainer} for advice" -84 | | note: This is an unsafe fix and may change runtime behavior @@ -317,10 +285,8 @@ RUF030 [*] `print()` call in `assert` statement is likely unintentional | help: Remove `print` | -87 | # - `msg` entirely removed from assertion - - assert True, print() +88 - assert True, print() 88 + assert True -89 | | note: This is an unsafe fix and may change runtime behavior @@ -336,10 +302,8 @@ RUF030 [*] `print()` call in `assert` statement is likely unintentional | help: Remove `print` | -92 | # - `msg` entirely removed from assertion - - assert True, print(sep=" ") +93 - assert True, print(sep=" ") 93 + assert True -94 | | note: This is an unsafe fix and may change runtime behavior @@ -352,8 +316,7 @@ RUF030 [*] `print()` call in `assert` statement is likely unintentional | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove `print` | -107 | # - single StringLiteral - - assert True, builtins.print("This print should be removed.") +108 - assert True, builtins.print("This print should be removed.") 108 + assert True, "This print should be removed." | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF031_RUF031.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF031_RUF031.py.snap index 367f7cd1a88fa..28f418be83dcf 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF031_RUF031.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF031_RUF031.py.snap @@ -12,10 +12,8 @@ RUF031 [*] Avoid parentheses for tuples in subscripts | help: Remove parentheses | -1 | d = {(1,2):"a",(3,4):"b",(5,6,7):"c",(8,):"d"} - - d[(1,2)] +2 - d[(1,2)] 2 + d[1,2] -3 | d[( | RUF031 [*] Avoid parentheses for tuples in subscripts @@ -34,14 +32,9 @@ RUF031 [*] Avoid parentheses for tuples in subscripts | help: Remove parentheses | -2 | d[(1,2)] - - d[( -3 + d[ -4 | 1, -5 | 2 - - )] -6 + ] -7 | d[ +3 ~ d[ +4 + 1, +5 + 2 | RUF031 [*] Avoid parentheses for tuples in subscripts @@ -56,10 +49,8 @@ RUF031 [*] Avoid parentheses for tuples in subscripts | help: Remove parentheses | -10 | ] - - d[(2,4)] +11 - d[(2,4)] 11 + d[2,4] -12 | d[(5,6,7)] | RUF031 [*] Avoid parentheses for tuples in subscripts @@ -74,10 +65,8 @@ RUF031 [*] Avoid parentheses for tuples in subscripts | help: Remove parentheses | -11 | d[(2,4)] - - d[(5,6,7)] +12 - d[(5,6,7)] 12 + d[5,6,7] -13 | d[(8,)] | RUF031 [*] Avoid parentheses for tuples in subscripts @@ -92,10 +81,8 @@ RUF031 [*] Avoid parentheses for tuples in subscripts | help: Remove parentheses | -12 | d[(5,6,7)] - - d[(8,)] +13 - d[(8,)] 13 + d[8,] -14 | d[tuple(1,2)] | RUF031 [*] Avoid parentheses for tuples in subscripts @@ -109,11 +96,8 @@ RUF031 [*] Avoid parentheses for tuples in subscripts | help: Remove parentheses | -19 | e = {((1,2),(3,4)):"a"} - - e[((1,2),(3,4))] -20 | e[(1,2),(3,4)] -21 + e[(1,2),(3,4)] -22 | +20 - e[((1,2),(3,4))] +20 + e[(1,2),(3,4)] | RUF031 [*] Avoid parentheses for tuples in subscripts @@ -126,10 +110,8 @@ RUF031 [*] Avoid parentheses for tuples in subscripts | help: Remove parentheses | -23 | token_features[ - - (window_position, feature_name) +24 - (window_position, feature_name) 24 + window_position, feature_name -25 | ] = self._extract_raw_features_from_token | RUF031 [*] Avoid parentheses for tuples in subscripts @@ -143,10 +125,8 @@ RUF031 [*] Avoid parentheses for tuples in subscripts | help: Remove parentheses | -27 | d[1,] - - d[(1,)] +28 - d[(1,)] 28 + d[1,] -29 | d[()] # empty tuples should be ignored | RUF031 [*] Avoid parentheses for tuples in subscripts @@ -161,8 +141,6 @@ RUF031 [*] Avoid parentheses for tuples in subscripts | help: Remove parentheses | -35 | # https://github.com/astral-sh/ruff/issues/12776 - - d[(*foo,bar)] +36 - d[(*foo,bar)] 36 + d[*foo,bar] -37 | | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF032_RUF032.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF032_RUF032.py.snap index 386dbed26c2da..de514485e220e 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF032_RUF032.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF032_RUF032.py.snap @@ -13,10 +13,8 @@ RUF032 [*] `Decimal()` called with float literal argument | help: Replace with string literal | -5 | - - decimal.Decimal(0.0) # Should error +6 - decimal.Decimal(0.0) # Should error 6 + decimal.Decimal("0.0") # Should error -7 | | note: This is an unsafe fix and may change runtime behavior @@ -32,10 +30,8 @@ RUF032 [*] `Decimal()` called with float literal argument | help: Replace with string literal | -11 | - - decimal.Decimal(10.0) # Should error +12 - decimal.Decimal(10.0) # Should error 12 + decimal.Decimal("10.0") # Should error -13 | | note: This is an unsafe fix and may change runtime behavior @@ -51,10 +47,8 @@ RUF032 [*] `Decimal()` called with float literal argument | help: Replace with string literal | -17 | - - decimal.Decimal(-10.0) # Should error +18 - decimal.Decimal(-10.0) # Should error 18 + decimal.Decimal("-10.0") # Should error -19 | | note: This is an unsafe fix and may change runtime behavior @@ -70,10 +64,8 @@ RUF032 [*] `Decimal()` called with float literal argument | help: Replace with string literal | -32 | - - val = Decimal(0.0) # Should error +33 - val = Decimal(0.0) # Should error 33 + val = Decimal("0.0") # Should error -34 | | note: This is an unsafe fix and may change runtime behavior @@ -89,10 +81,8 @@ RUF032 [*] `Decimal()` called with float literal argument | help: Replace with string literal | -38 | - - val = Decimal(10.0) # Should error +39 - val = Decimal(10.0) # Should error 39 + val = Decimal("10.0") # Should error -40 | | note: This is an unsafe fix and may change runtime behavior @@ -108,10 +98,8 @@ RUF032 [*] `Decimal()` called with float literal argument | help: Replace with string literal | -44 | - - val = Decimal(-10.0) # Should error +45 - val = Decimal(-10.0) # Should error 45 + val = Decimal("-10.0") # Should error -46 | | note: This is an unsafe fix and may change runtime behavior @@ -127,10 +115,8 @@ RUF032 [*] `Decimal()` called with float literal argument | help: Replace with string literal | -55 | - - val = Decimal(++4.0) # Suggest `Decimal("4.0")` +56 - val = Decimal(++4.0) # Suggest `Decimal("4.0")` 56 + val = Decimal("4.0") # Suggest `Decimal("4.0")` -57 | | note: This is an unsafe fix and may change runtime behavior @@ -143,10 +129,8 @@ RUF032 [*] `Decimal()` called with float literal argument | ^^^^^^^^^^^ help: Replace with string literal | -57 | - - val = Decimal(-+--++--4.0) # Suggest `Decimal("-4.0")` +58 - val = Decimal(-+--++--4.0) # Suggest `Decimal("-4.0")` 58 + val = Decimal("-4.0") # Suggest `Decimal("-4.0")` -59 | | note: This is an unsafe fix and may change runtime behavior @@ -162,10 +146,8 @@ RUF032 [*] `Decimal()` called with float literal argument | help: Replace with string literal | -87 | - - val = decimal.Decimal(0.0) # Should error +88 - val = decimal.Decimal(0.0) # Should error 88 + val = decimal.Decimal("0.0") # Should error -89 | | note: This is an unsafe fix and may change runtime behavior @@ -181,10 +163,8 @@ RUF032 [*] `Decimal()` called with float literal argument | help: Replace with string literal | -91 | - - val = decimal.Decimal(10.0) # Should error +92 - val = decimal.Decimal(10.0) # Should error 92 + val = decimal.Decimal("10.0") # Should error -93 | | note: This is an unsafe fix and may change runtime behavior @@ -200,9 +180,7 @@ RUF032 [*] `Decimal()` called with float literal argument | help: Replace with string literal | -95 | - - val = decimal.Decimal(-10.0) # Should error +96 - val = decimal.Decimal(-10.0) # Should error 96 + val = decimal.Decimal("-10.0") # Should error -97 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF033_RUF033.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF033_RUF033.py.snap index 4581b195a4406..8c432bc619ef1 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF033_RUF033.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF033_RUF033.py.snap @@ -28,11 +28,12 @@ RUF033 [*] `__post_init__` method with argument defaults | ^^ help: Use `dataclasses.InitVar` instead | + 1 ~ from dataclasses import InitVar, dataclass + 2 | + … 24 | class Foo: - - def __post_init__(self, bar = 11, baz = 11) -> None: ... 25 + bar: InitVar = 11 -26 + def __post_init__(self, bar, baz = 11) -> None: ... -27 | +26 ~ def __post_init__(self, bar, baz = 11) -> None: ... | note: This is an unsafe fix and may change runtime behavior @@ -45,11 +46,12 @@ RUF033 [*] `__post_init__` method with argument defaults | ^^ help: Use `dataclasses.InitVar` instead | + 1 ~ from dataclasses import InitVar, dataclass + 2 | + … 24 | class Foo: - - def __post_init__(self, bar = 11, baz = 11) -> None: ... 25 + baz: InitVar = 11 -26 + def __post_init__(self, bar = 11, baz) -> None: ... -27 | +26 ~ def __post_init__(self, bar = 11, baz) -> None: ... | note: This is an unsafe fix and may change runtime behavior @@ -62,11 +64,12 @@ RUF033 [*] `__post_init__` method with argument defaults | ^^ help: Use `dataclasses.InitVar` instead | + 1 ~ from dataclasses import InitVar, dataclass + 2 | + … 45 | class Foo: - - def __post_init__(self, bar: int = 11, baz: Something[Whatever | None] = 11) -> None: ... 46 + bar: InitVar[int] = 11 -47 + def __post_init__(self, bar: int, baz: Something[Whatever | None] = 11) -> None: ... -48 | +47 ~ def __post_init__(self, bar: int, baz: Something[Whatever | None] = 11) -> None: ... | note: This is an unsafe fix and may change runtime behavior @@ -79,11 +82,12 @@ RUF033 [*] `__post_init__` method with argument defaults | ^^ help: Use `dataclasses.InitVar` instead | + 1 ~ from dataclasses import InitVar, dataclass + 2 | + … 45 | class Foo: - - def __post_init__(self, bar: int = 11, baz: Something[Whatever | None] = 11) -> None: ... 46 + baz: InitVar[Something[Whatever | None]] = 11 -47 + def __post_init__(self, bar: int = 11, baz: Something[Whatever | None]) -> None: ... -48 | +47 ~ def __post_init__(self, bar: int = 11, baz: Something[Whatever | None]) -> None: ... | note: This is an unsafe fix and may change runtime behavior @@ -96,11 +100,12 @@ RUF033 [*] `__post_init__` method with argument defaults | ^^ help: Use `dataclasses.InitVar` instead | + 1 ~ from dataclasses import InitVar, dataclass + 2 | + … 58 | - - def __post_init__(self, bar: int = 11, baz: int = 12) -> None: ... 59 + bar: InitVar[int] = 11 -60 + def __post_init__(self, bar: int, baz: int = 12) -> None: ... -61 | +60 ~ def __post_init__(self, bar: int, baz: int = 12) -> None: ... | note: This is an unsafe fix and may change runtime behavior @@ -113,11 +118,12 @@ RUF033 [*] `__post_init__` method with argument defaults | ^^ help: Use `dataclasses.InitVar` instead | + 1 ~ from dataclasses import InitVar, dataclass + 2 | + … 58 | - - def __post_init__(self, bar: int = 11, baz: int = 12) -> None: ... 59 + baz: InitVar[int] = 12 -60 + def __post_init__(self, bar: int = 11, baz: int) -> None: ... -61 | +60 ~ def __post_init__(self, bar: int = 11, baz: int) -> None: ... | note: This is an unsafe fix and may change runtime behavior @@ -150,11 +156,12 @@ RUF033 [*] `__post_init__` method with argument defaults | help: Use `dataclasses.InitVar` instead | + 1 ~ from dataclasses import InitVar, dataclass + 2 | + … 72 | class Foo: - - def __post_init__(self, bar: int = (x := 1)) -> None: 73 + bar: InitVar[int] = (x := 1) -74 + def __post_init__(self, bar: int) -> None: -75 | pass +74 ~ def __post_init__(self, bar: int) -> None: | note: This is an unsafe fix and may change runtime behavior @@ -170,13 +177,14 @@ RUF033 [*] `__post_init__` method with argument defaults | help: Use `dataclasses.InitVar` instead | + 1 ~ from dataclasses import InitVar, dataclass + 2 | + … 78 | class Foo: 79 + bar: InitVar[int] = (x := 1) 80 | def __post_init__( 81 | self, - - bar: int = (x := 1) # comment -82 + bar: int # comment -83 | , +82 ~ bar: int # comment | note: This is an unsafe fix and may change runtime behavior @@ -192,15 +200,16 @@ RUF033 [*] `__post_init__` method with argument defaults | help: Use `dataclasses.InitVar` instead | + 1 ~ from dataclasses import InitVar, dataclass + 2 | + … 78 | class Foo: 79 + baz: InitVar[int] = (y := 2) 80 | def __post_init__( 81 | self, 82 | bar: int = (x := 1) # comment 83 | , - - baz: int = (y := 2), # comment -84 + baz: int, # comment -85 | foo = (a := 1) # comment +84 ~ baz: int, # comment | note: This is an unsafe fix and may change runtime behavior @@ -216,14 +225,16 @@ RUF033 [*] `__post_init__` method with argument defaults | help: Use `dataclasses.InitVar` instead | + 1 ~ from dataclasses import InitVar, dataclass + 2 | + … 78 | class Foo: 79 + foo: InitVar = (a := 1) 80 | def __post_init__( --------------------------------------------------------------------------------- +81 | self, + … 84 | baz: int = (y := 2), # comment - - foo = (a := 1) # comment -85 + foo # comment -86 | , +85 ~ foo # comment | note: This is an unsafe fix and may change runtime behavior @@ -239,14 +250,16 @@ RUF033 [*] `__post_init__` method with argument defaults | help: Use `dataclasses.InitVar` instead | + 1 ~ from dataclasses import InitVar, dataclass + 2 | + … 78 | class Foo: 79 + faz: InitVar = (b := 2) 80 | def __post_init__( --------------------------------------------------------------------------------- +81 | self, + … 86 | , - - faz = (b := 2), # comment -87 + faz, # comment -88 | ) -> None: +87 ~ faz, # comment | note: This is an unsafe fix and may change runtime behavior @@ -262,13 +275,14 @@ RUF033 [*] `__post_init__` method with argument defaults | help: Use `dataclasses.InitVar` instead | + 1 ~ from dataclasses import InitVar, dataclass + 2 | + … 92 | class Foo: 93 + bar: InitVar[int] = 1 94 | def __post_init__( 95 | self, - - bar: int = 1, # comment -96 + bar: int, # comment -97 | baz: int = 2, # comment +96 ~ bar: int, # comment | note: This is an unsafe fix and may change runtime behavior @@ -284,14 +298,15 @@ RUF033 [*] `__post_init__` method with argument defaults | help: Use `dataclasses.InitVar` instead | + 1 ~ from dataclasses import InitVar, dataclass + 2 | + … 92 | class Foo: 93 + baz: InitVar[int] = 2 94 | def __post_init__( 95 | self, 96 | bar: int = 1, # comment - - baz: int = 2, # comment -97 + baz: int, # comment -98 | ) -> None: +97 ~ baz: int, # comment | note: This is an unsafe fix and may change runtime behavior @@ -307,13 +322,14 @@ RUF033 [*] `__post_init__` method with argument defaults | help: Use `dataclasses.InitVar` instead | + 1 ~ from dataclasses import InitVar, dataclass + 2 | + … 102 | class Foo: 103 + arg1: InitVar[int] = (1) 104 | def __post_init__( 105 | self, - - arg1: int = (1) # comment -106 + arg1: int # comment -107 | , +106 ~ arg1: int # comment | note: This is an unsafe fix and may change runtime behavior @@ -329,15 +345,16 @@ RUF033 [*] `__post_init__` method with argument defaults | help: Use `dataclasses.InitVar` instead | + 1 ~ from dataclasses import InitVar, dataclass + 2 | + … 102 | class Foo: 103 + arg2: InitVar[int] = ((1)) 104 | def __post_init__( 105 | self, 106 | arg1: int = (1) # comment 107 | , - - arg2: int = ((1)) # comment -108 + arg2: int # comment -109 | , +108 ~ arg2: int # comment | note: This is an unsafe fix and may change runtime behavior @@ -353,14 +370,16 @@ RUF033 [*] `__post_init__` method with argument defaults | help: Use `dataclasses.InitVar` instead | + 1 ~ from dataclasses import InitVar, dataclass + 2 | + … 102 | class Foo: 103 + arg2: InitVar[int] = (i for i in range(10)) 104 | def __post_init__( --------------------------------------------------------------------------------- +105 | self, + … 109 | , - - arg2: int = (i for i in range(10)) # comment -110 + arg2: int # comment -111 | , +110 ~ arg2: int # comment | note: This is an unsafe fix and may change runtime behavior @@ -376,13 +395,14 @@ RUF033 [*] `__post_init__` method with argument defaults | help: Use `dataclasses.InitVar` instead | + 1 ~ from dataclasses import InitVar, dataclass + 2 | + … 118 | class Foo: 119 + bar: InitVar[int] = (yield from range(5)) 120 | def __post_init__( 121 | self, - - bar: (int) = (yield from range(5)) # comment -122 + bar: (int) # comment -123 | , +122 ~ bar: (int) # comment | note: This is an unsafe fix and may change runtime behavior @@ -401,15 +421,15 @@ RUF033 [*] `__post_init__` method with argument defaults | help: Use `dataclasses.InitVar` instead | + 1 ~ from dataclasses import InitVar, dataclass + 2 | + … 130 | class C: - - def __post_init__(self, x: tuple[int, ...] = ( 131 + x: InitVar[tuple[int, ...]] = ( -132 | 1, -133 | 2, - - )) -> None: +132 + 1, +133 + 2, 134 + ) -135 + def __post_init__(self, x: tuple[int, ...]) -> None: -136 | self.x = x +135 ~ def __post_init__(self, x: tuple[int, ...]) -> None: | note: This is an unsafe fix and may change runtime behavior @@ -426,13 +446,13 @@ RUF033 [*] `__post_init__` method with argument defaults | help: Use `dataclasses.InitVar` instead | + 1 ~ from dataclasses import InitVar, dataclass + 2 | + … 139 | class D: - - def __post_init__(self, x: int = """ - - """) -> None: 140 + x: InitVar[int] = """ 141 + """ -142 + def __post_init__(self, x: int) -> None: -143 | self.x = x +142 ~ def __post_init__(self, x: int) -> None: | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF036_RUF036.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF036_RUF036.py.snap index 4cb441be43f93..44f3de4a7ef90 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF036_RUF036.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF036_RUF036.py.snap @@ -10,10 +10,8 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -3 | - - def func1(arg: None | int): +4 - def func1(arg: None | int): 4 + def func1(arg: int | None): -5 | ... | RUF036 [*] `None` not at the end of the type union. @@ -25,10 +23,8 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -7 | - - def func2() -> None | int: +8 - def func2() -> None | int: 8 + def func2() -> int | None: -9 | ... | RUF036 `None` not at the end of the type union. @@ -49,10 +45,8 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -15 | - - def func4(arg: U[None, int]): +16 - def func4(arg: U[None, int]): 16 + def func4(arg: U[int, None]): -17 | ... | RUF036 [*] `None` not at the end of the type union. @@ -64,10 +58,8 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -19 | - - def func5() -> U[None, int]: +20 - def func5() -> U[None, int]: 20 + def func5() -> U[int, None]: -21 | ... | RUF036 [*] `None` not at the end of the type union. @@ -79,10 +71,8 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -23 | - - def func6(arg: U[None, None, int]): +24 - def func6(arg: U[None, None, int]): 24 + def func6(arg: U[int, None, None]): -25 | ... | RUF036 [*] `None` not at the end of the type union. @@ -100,14 +90,12 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -28 | # Comments in annotation (unsafe fix) - - def func7() -> U[ - - None, - - # comment - - int - - ]: +29 - def func7() -> U[ +30 - None, +31 - # comment +32 - int +33 - ]: 29 + def func7() -> U[int, None]: -30 | ... | note: This is an unsafe fix and may change runtime behavior @@ -149,10 +137,8 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -50 | # Multiple annotations in the same function - - def func11(x: None | int) -> None | int: +51 - def func11(x: None | int) -> None | int: 51 + def func11(x: int | None) -> None | int: -52 | ... | RUF036 [*] `None` not at the end of the type union. @@ -165,10 +151,8 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -50 | # Multiple annotations in the same function - - def func11(x: None | int) -> None | int: +51 - def func11(x: None | int) -> None | int: 51 + def func11(x: None | int) -> int | None: -52 | ... | RUF036 [*] `None` not at the end of the type union. @@ -181,10 +165,8 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -55 | # With default argument (from poetry ecosystem check) - - def func12(io: None | int = None) -> int | None: +56 - def func12(io: None | int = None) -> int | None: 56 + def func12(io: int | None = None) -> int | None: -57 | ... | RUF036 [*] `None` not at the end of the type union. @@ -197,10 +179,8 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -60 | # 3+ member PEP 604 chains - - def func13(arg: None | int | str): +61 - def func13(arg: None | int | str): 61 + def func13(arg: int | str | None): -62 | ... | RUF036 [*] `None` not at the end of the type union. @@ -212,10 +192,8 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -64 | - - def func14(arg: None | int | str | bytes): +65 - def func14(arg: None | int | str | bytes): 65 + def func14(arg: int | str | bytes | None): -66 | ... | RUF036 [*] `None` not at the end of the type union. @@ -228,10 +206,8 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -69 | # Preserve token boundaries when fixing annotations. - - def func15(arg: None | (int)and 2): +70 - def func15(arg: None | (int)and 2): 70 + def func15(arg: int | None and 2): -71 | ... | RUF036 [*] `None` not at the end of the type union. @@ -243,8 +219,6 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -73 | - - def func16(arg: 2 or(None) | int): +74 - def func16(arg: 2 or(None) | int): 74 + def func16(arg: 2 or int | None): -75 | ... | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF036_RUF036.pyi.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF036_RUF036.pyi.snap index 6d331b79a8dfd..d4a6a678b90f1 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF036_RUF036.pyi.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF036_RUF036.pyi.snap @@ -11,10 +11,8 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -3 | - - def func1(arg: None | int): ... +4 - def func1(arg: None | int): ... 4 + def func1(arg: int | None): ... -5 | | RUF036 [*] `None` not at the end of the type union. @@ -29,10 +27,8 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -5 | - - def func2() -> None | int: ... +6 - def func2() -> None | int: ... 6 + def func2() -> int | None: ... -7 | | RUF036 `None` not at the end of the type union. @@ -59,10 +55,8 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -9 | - - def func4(arg: U[None, int]): ... +10 - def func4(arg: U[None, int]): ... 10 + def func4(arg: U[int, None]): ... -11 | | RUF036 [*] `None` not at the end of the type union. @@ -77,10 +71,8 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -11 | - - def func5() -> U[None, int]: ... +12 - def func5() -> U[None, int]: ... 12 + def func5() -> U[int, None]: ... -13 | | RUF036 [*] `None` not at the end of the type union. @@ -95,10 +87,8 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -13 | - - def func6(arg: U[None, None, int]): ... +14 - def func6(arg: U[None, None, int]): ... 14 + def func6(arg: U[int, None, None]): ... -15 | | RUF036 `None` not at the end of the type union. @@ -135,10 +125,8 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -21 | # Multiple annotations in the same function - - def func9(x: None | int) -> None | int: ... +22 - def func9(x: None | int) -> None | int: ... 22 + def func9(x: int | None) -> None | int: ... -23 | | RUF036 [*] `None` not at the end of the type union. @@ -152,10 +140,8 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -21 | # Multiple annotations in the same function - - def func9(x: None | int) -> None | int: ... +22 - def func9(x: None | int) -> None | int: ... 22 + def func9(x: None | int) -> int | None: ... -23 | | RUF036 [*] `None` not at the end of the type union. @@ -169,10 +155,8 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -24 | # 3+ member PEP 604 chains - - def func10(arg: None | int | str): ... +25 - def func10(arg: None | int | str): ... 25 + def func10(arg: int | str | None): ... -26 | | RUF036 [*] `None` not at the end of the type union. @@ -187,8 +171,6 @@ RUF036 [*] `None` not at the end of the type union. | help: Move `None` to the end of the type union | -26 | - - def func11(arg: None | int | str | bytes): ... +27 - def func11(arg: None | int | str | bytes): ... 27 + def func11(arg: int | str | bytes | None): ... -28 | | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF037_RUF037.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF037_RUF037.py.snap index a5b357425ca59..e2e283a5e633d 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF037_RUF037.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF037_RUF037.py.snap @@ -9,10 +9,8 @@ RUF037 [*] Unnecessary empty iterable within a deque call | ^^^^^^^^^^^^^^^^^^^^^ help: Replace with `deque()` | -5 | def f(): - - queue = collections.deque([]) # RUF037 +6 - queue = collections.deque([]) # RUF037 6 + queue = collections.deque() # RUF037 -7 | | RUF037 [*] Unnecessary empty iterable within a deque call @@ -23,10 +21,8 @@ RUF037 [*] Unnecessary empty iterable within a deque call | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `deque(maxlen=...)` | -9 | def f(): - - queue = collections.deque([], maxlen=10) # RUF037 +10 - queue = collections.deque([], maxlen=10) # RUF037 10 + queue = collections.deque(maxlen=10) # RUF037 -11 | | RUF037 [*] Unnecessary empty iterable within a deque call @@ -37,10 +33,8 @@ RUF037 [*] Unnecessary empty iterable within a deque call | ^^^^^^^^^ help: Replace with `deque()` | -13 | def f(): - - queue = deque([]) # RUF037 +14 - queue = deque([]) # RUF037 14 + queue = deque() # RUF037 -15 | | RUF037 [*] Unnecessary empty iterable within a deque call @@ -51,10 +45,8 @@ RUF037 [*] Unnecessary empty iterable within a deque call | ^^^^^^^^^ help: Replace with `deque()` | -17 | def f(): - - queue = deque(()) # RUF037 +18 - queue = deque(()) # RUF037 18 + queue = deque() # RUF037 -19 | | RUF037 [*] Unnecessary empty iterable within a deque call @@ -65,10 +57,8 @@ RUF037 [*] Unnecessary empty iterable within a deque call | ^^^^^^^^^ help: Replace with `deque()` | -21 | def f(): - - queue = deque({}) # RUF037 +22 - queue = deque({}) # RUF037 22 + queue = deque() # RUF037 -23 | | RUF037 [*] Unnecessary empty iterable within a deque call @@ -79,10 +69,8 @@ RUF037 [*] Unnecessary empty iterable within a deque call | ^^^^^^^^^^^^ help: Replace with `deque()` | -25 | def f(): - - queue = deque(set()) # RUF037 +26 - queue = deque(set()) # RUF037 26 + queue = deque() # RUF037 -27 | | RUF037 [*] Unnecessary empty iterable within a deque call @@ -93,10 +81,8 @@ RUF037 [*] Unnecessary empty iterable within a deque call | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `deque(maxlen=...)` | -29 | def f(): - - queue = collections.deque([], maxlen=10) # RUF037 +30 - queue = collections.deque([], maxlen=10) # RUF037 30 + queue = collections.deque(maxlen=10) # RUF037 -31 | | RUF037 [*] Unnecessary empty iterable within a deque call @@ -107,10 +93,8 @@ RUF037 [*] Unnecessary empty iterable within a deque call | ^^^^^^^^^^^ help: Replace with `deque()` | -60 | def f(): - - x = 0 or(deque)([]) +61 - x = 0 or(deque)([]) 61 + x = 0 or(deque)() -62 | | RUF037 Unnecessary empty iterable within a deque call @@ -136,10 +120,8 @@ RUF037 [*] Unnecessary empty iterable within a deque call | help: Replace with `deque()` | -66 | deque([], *[10]) # RUF037 but no fix - - deque([], **{"maxlen": 10}) # RUF037 +67 - deque([], **{"maxlen": 10}) # RUF037 67 + deque(**{"maxlen": 10}) # RUF037 -68 | deque([], foo=1) # RUF037 | note: This is an unsafe fix and may change runtime behavior @@ -152,10 +134,8 @@ RUF037 [*] Unnecessary empty iterable within a deque call | ^^^^^^^^^^^^^^^^ help: Replace with `deque()` | -67 | deque([], **{"maxlen": 10}) # RUF037 - - deque([], foo=1) # RUF037 +68 - deque([], foo=1) # RUF037 68 + deque(foo=1) # RUF037 -69 | | note: This is an unsafe fix and may change runtime behavior @@ -172,14 +152,12 @@ RUF037 [*] Unnecessary empty iterable within a deque call | |_________^ help: Replace with `deque(maxlen=...)` | -79 | def f(): - - deque( # a comment in deque, deleted - - [ # a comment _in_ the list, deleted - - ], # a comment after the list, deleted - - maxlen=10, # a comment on maxlen, deleted - - ) # only this is preserved +80 - deque( # a comment in deque, deleted +81 - [ # a comment _in_ the list, deleted +82 - ], # a comment after the list, deleted +83 - maxlen=10, # a comment on maxlen, deleted +84 - ) # only this is preserved 80 + deque(maxlen=10) # only this is preserved -81 | | note: This is an unsafe fix and may change runtime behavior @@ -192,10 +170,8 @@ RUF037 [*] Unnecessary empty iterable within a deque call | ^^^^^^^^^^^^^ help: Replace with `deque(maxlen=...)` | -88 | def f(): - - deque([], 10) +89 - deque([], 10) 89 + deque(maxlen=10) -90 | | RUF037 [*] Unnecessary empty iterable within a deque call @@ -209,10 +185,8 @@ RUF037 [*] Unnecessary empty iterable within a deque call | help: Replace with `deque()` | -92 | def f(): - - deque([], iterable=[]) +93 - deque([], iterable=[]) 93 + deque([]) -94 | | note: This is an unsafe fix and may change runtime behavior @@ -227,10 +201,8 @@ RUF037 [*] Unnecessary empty iterable within a deque call | help: Replace with `deque()` | -95 | # https://github.com/astral-sh/ruff/issues/18854 - - deque("") +96 - deque("") 96 + deque() -97 | deque(b"") | RUF037 [*] Unnecessary empty iterable within a deque call @@ -245,10 +217,8 @@ RUF037 [*] Unnecessary empty iterable within a deque call | help: Replace with `deque()` | -96 | deque("") - - deque(b"") +97 - deque(b"") 97 + deque() -98 | deque(f"") | RUF037 [*] Unnecessary empty iterable within a deque call @@ -263,10 +233,8 @@ RUF037 [*] Unnecessary empty iterable within a deque call | help: Replace with `deque()` | -97 | deque(b"") - - deque(f"") +98 - deque(f"") 98 + deque() -99 | deque(f"" "") | RUF037 [*] Unnecessary empty iterable within a deque call @@ -280,12 +248,10 @@ RUF037 [*] Unnecessary empty iterable within a deque call 101 | deque("abc") # OK | help: Replace with `deque()` - | -98 | deque(f"") - - deque(f"" "") -99 + deque() -100 | deque(f"" f"") - | + | +99 - deque(f"" "") +99 + deque() + | RUF037 [*] Unnecessary empty iterable within a deque call --> RUF037.py:100:1 @@ -299,10 +265,8 @@ RUF037 [*] Unnecessary empty iterable within a deque call | help: Replace with `deque()` | -99 | deque(f"" "") - - deque(f"" f"") +100 - deque(f"" f"") 100 + deque() -101 | deque("abc") # OK | RUF037 [*] Unnecessary empty iterable within a deque call @@ -316,10 +280,8 @@ RUF037 [*] Unnecessary empty iterable within a deque call | help: Replace with `deque()` | -106 | # https://github.com/astral-sh/ruff/issues/19951 - - deque(t"") +107 - deque(t"") 107 + deque() -108 | deque(t"" t"") | RUF037 [*] Unnecessary empty iterable within a deque call @@ -333,10 +295,8 @@ RUF037 [*] Unnecessary empty iterable within a deque call | help: Replace with `deque()` | -107 | deque(t"") - - deque(t"" t"") +108 - deque(t"" t"") 108 + deque() -109 | deque(t"{""}") # OK | RUF037 [*] Unnecessary empty iterable within a deque call @@ -350,8 +310,6 @@ RUF037 [*] Unnecessary empty iterable within a deque call | help: Replace with `deque()` | -111 | # https://github.com/astral-sh/ruff/issues/20050 - - deque(f"{""}") # RUF037 +112 - deque(f"{""}") # RUF037 112 + deque() # RUF037 -113 | | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF038_RUF038.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF038_RUF038.py.snap index 5be263b7f986b..c06c665c3b2cb 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF038_RUF038.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF038_RUF038.py.snap @@ -10,10 +10,8 @@ RUF038 [*] `Literal[True, False]` can be replaced with `bool` | help: Replace with `bool` | -3 | - - def func1(arg1: Literal[True, False]): +4 - def func1(arg1: Literal[True, False]): 4 + def func1(arg1: bool): -5 | ... | note: This is an unsafe fix and may change runtime behavior @@ -26,10 +24,8 @@ RUF038 [*] `Literal[True, False]` can be replaced with `bool` | help: Replace with `bool` | -7 | - - def func2(arg1: Literal[True, False, True]): +8 - def func2(arg1: Literal[True, False, True]): 8 + def func2(arg1: bool): -9 | ... | note: This is an unsafe fix and may change runtime behavior @@ -42,10 +38,8 @@ RUF038 [*] `Literal[True, False]` can be replaced with `bool` | help: Replace with `bool` | -11 | - - def func3() -> Literal[True, False]: +12 - def func3() -> Literal[True, False]: 12 + def func3() -> bool: -13 | ... | note: This is an unsafe fix and may change runtime behavior @@ -58,10 +52,8 @@ RUF038 [*] `Literal[True, False]` can be replaced with `bool` | help: Replace with `bool` | -15 | - - def func4(arg1: Literal[True, False] | bool): +16 - def func4(arg1: Literal[True, False] | bool): 16 + def func4(arg1: bool | bool): -17 | ... | note: This is an unsafe fix and may change runtime behavior @@ -74,10 +66,8 @@ RUF038 [*] `Literal[True, False]` can be replaced with `bool` | help: Replace with `bool` | -19 | - - def func5(arg1: Literal[False, True]): +20 - def func5(arg1: Literal[False, True]): 20 + def func5(arg1: bool): -21 | ... | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF038_RUF038.pyi.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF038_RUF038.pyi.snap index 5f2bdbbfe4736..b7db63b75f602 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF038_RUF038.pyi.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF038_RUF038.pyi.snap @@ -11,10 +11,8 @@ RUF038 [*] `Literal[True, False]` can be replaced with `bool` | help: Replace with `bool` | -3 | - - def func1(arg1: Literal[True, False]): ... +4 - def func1(arg1: Literal[True, False]): ... 4 + def func1(arg1: bool): ... -5 | | note: This is an unsafe fix and may change runtime behavior @@ -30,10 +28,8 @@ RUF038 [*] `Literal[True, False]` can be replaced with `bool` | help: Replace with `bool` | -5 | - - def func2(arg1: Literal[True, False, True]): ... +6 - def func2(arg1: Literal[True, False, True]): ... 6 + def func2(arg1: bool): ... -7 | | note: This is an unsafe fix and may change runtime behavior @@ -49,10 +45,8 @@ RUF038 [*] `Literal[True, False]` can be replaced with `bool` | help: Replace with `bool` | -7 | - - def func3() -> Literal[True, False]: ... +8 - def func3() -> Literal[True, False]: ... 8 + def func3() -> bool: ... -9 | | note: This is an unsafe fix and may change runtime behavior @@ -68,10 +62,8 @@ RUF038 [*] `Literal[True, False]` can be replaced with `bool` | help: Replace with `bool` | -9 | - - def func4(arg1: Literal[True, False] | bool): ... +10 - def func4(arg1: Literal[True, False] | bool): ... 10 + def func4(arg1: bool | bool): ... -11 | | note: This is an unsafe fix and may change runtime behavior @@ -87,10 +79,8 @@ RUF038 [*] `Literal[True, False]` can be replaced with `bool` | help: Replace with `bool` | -11 | - - def func5(arg1: Literal[False, True]): ... +12 - def func5(arg1: Literal[False, True]): ... 12 + def func5(arg1: bool): ... -13 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF041_RUF041.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF041_RUF041.py.snap index f5a3966ef0295..00ad447d547d1 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF041_RUF041.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF041_RUF041.py.snap @@ -11,10 +11,8 @@ RUF041 [*] Unnecessary nested `Literal` | help: Replace with flattened `Literal` | -5 | - - y: Literal[1, print("hello"), 3, Literal[4, 1]] +6 - y: Literal[1, print("hello"), 3, Literal[4, 1]] 6 + y: Literal[1, print("hello"), 3, 4, 1] -7 | Literal[1, Literal[1]] | RUF041 [*] Unnecessary nested `Literal` @@ -28,10 +26,8 @@ RUF041 [*] Unnecessary nested `Literal` | help: Replace with flattened `Literal` | -6 | y: Literal[1, print("hello"), 3, Literal[4, 1]] - - Literal[1, Literal[1]] +7 - Literal[1, Literal[1]] 7 + Literal[1, 1] -8 | Literal[1, 2, Literal[1, 2]] | RUF041 [*] Unnecessary nested `Literal` @@ -46,10 +42,8 @@ RUF041 [*] Unnecessary nested `Literal` | help: Replace with flattened `Literal` | -7 | Literal[1, Literal[1]] - - Literal[1, 2, Literal[1, 2]] +8 - Literal[1, 2, Literal[1, 2]] 8 + Literal[1, 2, 1, 2] -9 | Literal[1, Literal[1], Literal[1]] | RUF041 [*] Unnecessary nested `Literal` @@ -63,12 +57,10 @@ RUF041 [*] Unnecessary nested `Literal` 11 | t.Literal[1, t.Literal[2, t.Literal[1]]] | help: Replace with flattened `Literal` - | -8 | Literal[1, 2, Literal[1, 2]] - - Literal[1, Literal[1], Literal[1]] -9 + Literal[1, 1, 1] -10 | Literal[1, Literal[2], Literal[2]] - | + | +9 - Literal[1, Literal[1], Literal[1]] +9 + Literal[1, 1, 1] + | RUF041 [*] Unnecessary nested `Literal` --> RUF041.py:10:1 @@ -82,10 +74,8 @@ RUF041 [*] Unnecessary nested `Literal` | help: Replace with flattened `Literal` | -9 | Literal[1, Literal[1], Literal[1]] - - Literal[1, Literal[2], Literal[2]] +10 - Literal[1, Literal[2], Literal[2]] 10 + Literal[1, 2, 2] -11 | t.Literal[1, t.Literal[2, t.Literal[1]]] | RUF041 [*] Unnecessary nested `Literal` @@ -100,10 +90,8 @@ RUF041 [*] Unnecessary nested `Literal` | help: Replace with flattened `Literal` | -10 | Literal[1, Literal[2], Literal[2]] - - t.Literal[1, t.Literal[2, t.Literal[1]]] +11 - t.Literal[1, t.Literal[2, t.Literal[1]]] 11 + t.Literal[1, 2, 1] -12 | Literal[ | RUF041 [*] Unnecessary nested `Literal` @@ -123,15 +111,13 @@ RUF041 [*] Unnecessary nested `Literal` | help: Replace with flattened `Literal` | -11 | t.Literal[1, t.Literal[2, t.Literal[1]]] - - Literal[ - - 1, # comment 1 - - Literal[ # another comment - - 1 # yet another comment - - ] - - ] # once +12 - Literal[ +13 - 1, # comment 1 +14 - Literal[ # another comment +15 - 1 # yet another comment +16 - ] +17 - ] # once 12 + Literal[1, 1] # once -13 | | note: This is an unsafe fix and may change runtime behavior @@ -146,10 +132,8 @@ RUF041 [*] Unnecessary nested `Literal` | help: Replace with flattened `Literal` | -19 | # Ensure issue is only raised once, even on nested literals - - MyType = Literal["foo", Literal[True, False, True], "bar"] +20 - MyType = Literal["foo", Literal[True, False, True], "bar"] 20 + MyType = Literal["foo", True, False, True, "bar"] -21 | | RUF041 [*] Unnecessary nested `Literal` @@ -163,10 +147,8 @@ RUF041 [*] Unnecessary nested `Literal` | help: Replace with flattened `Literal` | -22 | # nested literals, all equivalent to `Literal[1]` - - Literal[Literal[1]] +23 - Literal[Literal[1]] 23 + Literal[1] -24 | Literal[Literal[Literal[1], Literal[1]]] | RUF041 [*] Unnecessary nested `Literal` @@ -180,10 +162,8 @@ RUF041 [*] Unnecessary nested `Literal` | help: Replace with flattened `Literal` | -23 | Literal[Literal[1]] - - Literal[Literal[Literal[1], Literal[1]]] +24 - Literal[Literal[Literal[1], Literal[1]]] 24 + Literal[1, 1] -25 | Literal[Literal[1], Literal[Literal[Literal[1]]]] | RUF041 [*] Unnecessary nested `Literal` @@ -198,8 +178,6 @@ RUF041 [*] Unnecessary nested `Literal` | help: Replace with flattened `Literal` | -24 | Literal[Literal[Literal[1], Literal[1]]] - - Literal[Literal[1], Literal[Literal[Literal[1]]]] +25 - Literal[Literal[1], Literal[Literal[Literal[1]]]] 25 + Literal[1, 1] -26 | | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF041_RUF041.pyi.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF041_RUF041.pyi.snap index 91dea500b99e9..4ec1c8613f2e6 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF041_RUF041.pyi.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF041_RUF041.pyi.snap @@ -11,10 +11,8 @@ RUF041 [*] Unnecessary nested `Literal` | help: Replace with flattened `Literal` | -5 | - - y: Literal[1, print("hello"), 3, Literal[4, 1]] +6 - y: Literal[1, print("hello"), 3, Literal[4, 1]] 6 + y: Literal[1, print("hello"), 3, 4, 1] -7 | Literal[1, Literal[1]] | RUF041 [*] Unnecessary nested `Literal` @@ -28,10 +26,8 @@ RUF041 [*] Unnecessary nested `Literal` | help: Replace with flattened `Literal` | -6 | y: Literal[1, print("hello"), 3, Literal[4, 1]] - - Literal[1, Literal[1]] +7 - Literal[1, Literal[1]] 7 + Literal[1, 1] -8 | Literal[1, 2, Literal[1, 2]] | RUF041 [*] Unnecessary nested `Literal` @@ -46,10 +42,8 @@ RUF041 [*] Unnecessary nested `Literal` | help: Replace with flattened `Literal` | -7 | Literal[1, Literal[1]] - - Literal[1, 2, Literal[1, 2]] +8 - Literal[1, 2, Literal[1, 2]] 8 + Literal[1, 2, 1, 2] -9 | Literal[1, Literal[1], Literal[1]] | RUF041 [*] Unnecessary nested `Literal` @@ -63,12 +57,10 @@ RUF041 [*] Unnecessary nested `Literal` 11 | t.Literal[1, t.Literal[2, t.Literal[1]]] | help: Replace with flattened `Literal` - | -8 | Literal[1, 2, Literal[1, 2]] - - Literal[1, Literal[1], Literal[1]] -9 + Literal[1, 1, 1] -10 | Literal[1, Literal[2], Literal[2]] - | + | +9 - Literal[1, Literal[1], Literal[1]] +9 + Literal[1, 1, 1] + | RUF041 [*] Unnecessary nested `Literal` --> RUF041.pyi:10:1 @@ -82,10 +74,8 @@ RUF041 [*] Unnecessary nested `Literal` | help: Replace with flattened `Literal` | -9 | Literal[1, Literal[1], Literal[1]] - - Literal[1, Literal[2], Literal[2]] +10 - Literal[1, Literal[2], Literal[2]] 10 + Literal[1, 2, 2] -11 | t.Literal[1, t.Literal[2, t.Literal[1]]] | RUF041 [*] Unnecessary nested `Literal` @@ -100,10 +90,8 @@ RUF041 [*] Unnecessary nested `Literal` | help: Replace with flattened `Literal` | -10 | Literal[1, Literal[2], Literal[2]] - - t.Literal[1, t.Literal[2, t.Literal[1]]] +11 - t.Literal[1, t.Literal[2, t.Literal[1]]] 11 + t.Literal[1, 2, 1] -12 | Literal[ | RUF041 [*] Unnecessary nested `Literal` @@ -123,15 +111,13 @@ RUF041 [*] Unnecessary nested `Literal` | help: Replace with flattened `Literal` | -11 | t.Literal[1, t.Literal[2, t.Literal[1]]] - - Literal[ - - 1, # comment 1 - - Literal[ # another comment - - 1 # yet another comment - - ] - - ] # once +12 - Literal[ +13 - 1, # comment 1 +14 - Literal[ # another comment +15 - 1 # yet another comment +16 - ] +17 - ] # once 12 + Literal[1, 1] # once -13 | | note: This is an unsafe fix and may change runtime behavior @@ -146,10 +132,8 @@ RUF041 [*] Unnecessary nested `Literal` | help: Replace with flattened `Literal` | -19 | # Ensure issue is only raised once, even on nested literals - - MyType = Literal["foo", Literal[True, False, True], "bar"] +20 - MyType = Literal["foo", Literal[True, False, True], "bar"] 20 + MyType = Literal["foo", True, False, True, "bar"] -21 | | RUF041 [*] Unnecessary nested `Literal` @@ -163,10 +147,8 @@ RUF041 [*] Unnecessary nested `Literal` | help: Replace with flattened `Literal` | -22 | # nested literals, all equivalent to `Literal[1]` - - Literal[Literal[1]] +23 - Literal[Literal[1]] 23 + Literal[1] -24 | Literal[Literal[Literal[1], Literal[1]]] | RUF041 [*] Unnecessary nested `Literal` @@ -180,10 +162,8 @@ RUF041 [*] Unnecessary nested `Literal` | help: Replace with flattened `Literal` | -23 | Literal[Literal[1]] - - Literal[Literal[Literal[1], Literal[1]]] +24 - Literal[Literal[Literal[1], Literal[1]]] 24 + Literal[1, 1] -25 | Literal[Literal[1], Literal[Literal[Literal[1]]]] | RUF041 [*] Unnecessary nested `Literal` @@ -198,8 +178,6 @@ RUF041 [*] Unnecessary nested `Literal` | help: Replace with flattened `Literal` | -24 | Literal[Literal[Literal[1], Literal[1]]] - - Literal[Literal[1], Literal[Literal[Literal[1]]]] +25 - Literal[Literal[1], Literal[Literal[Literal[1]]]] 25 + Literal[1, 1] -26 | | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF046_RUF046.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF046_RUF046.py.snap index cd45cd92f83b2..f743b0f15e149 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF046_RUF046.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF046_RUF046.py.snap @@ -13,10 +13,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -9 | - - int(id()) +10 - int(id()) 10 + id() -11 | int(len([])) | RUF046 [*] Value being cast to `int` is already an integer @@ -30,10 +28,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -10 | int(id()) - - int(len([])) +11 - int(len([])) 11 + len([]) -12 | int(ord(foo)) | RUF046 [*] Value being cast to `int` is already an integer @@ -48,10 +44,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -11 | int(len([])) - - int(ord(foo)) +12 - int(ord(foo)) 12 + ord(foo) -13 | int(hash(foo, bar)) | RUF046 [*] Value being cast to `int` is already an integer @@ -65,10 +59,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -12 | int(ord(foo)) - - int(hash(foo, bar)) +13 - int(hash(foo, bar)) 13 + hash(foo, bar) -14 | int(int('')) | RUF046 [*] Value being cast to `int` is already an integer @@ -83,10 +75,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -13 | int(hash(foo, bar)) - - int(int('')) +14 - int(int('')) 14 + int('') -15 | | RUF046 [*] Value being cast to `int` is already an integer @@ -101,10 +91,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -15 | - - int(math.comb()) +16 - int(math.comb()) 16 + math.comb() -17 | int(math.factorial()) | RUF046 [*] Value being cast to `int` is already an integer @@ -118,10 +106,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -16 | int(math.comb()) - - int(math.factorial()) +17 - int(math.factorial()) 17 + math.factorial() -18 | int(math.gcd()) | RUF046 [*] Value being cast to `int` is already an integer @@ -136,10 +122,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -17 | int(math.factorial()) - - int(math.gcd()) +18 - int(math.gcd()) 18 + math.gcd() -19 | int(math.lcm()) | RUF046 [*] Value being cast to `int` is already an integer @@ -154,10 +138,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -18 | int(math.gcd()) - - int(math.lcm()) +19 - int(math.lcm()) 19 + math.lcm() -20 | int(math.isqrt()) | RUF046 [*] Value being cast to `int` is already an integer @@ -171,10 +153,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -19 | int(math.lcm()) - - int(math.isqrt()) +20 - int(math.isqrt()) 20 + math.isqrt() -21 | int(math.perm()) | RUF046 [*] Value being cast to `int` is already an integer @@ -189,10 +169,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -20 | int(math.isqrt()) - - int(math.perm()) +21 - int(math.perm()) 21 + math.perm() -22 | | RUF046 [*] Value being cast to `int` is already an integer @@ -206,10 +184,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -22 | - - int(round(1, 0)) +23 - int(round(1, 0)) 23 + round(1, 0) -24 | int(round(1, 10)) | RUF046 [*] Value being cast to `int` is already an integer @@ -223,10 +199,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -23 | int(round(1, 0)) - - int(round(1, 10)) +24 - int(round(1, 10)) 24 + round(1, 10) -25 | | RUF046 [*] Value being cast to `int` is already an integer @@ -240,10 +214,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -25 | - - int(round(1)) +26 - int(round(1)) 26 + round(1) -27 | int(round(1, None)) | RUF046 [*] Value being cast to `int` is already an integer @@ -257,10 +229,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -26 | int(round(1)) - - int(round(1, None)) +27 - int(round(1, None)) 27 + round(1, None) -28 | | RUF046 [*] Value being cast to `int` is already an integer @@ -274,10 +244,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -28 | - - int(round(1.)) +29 - int(round(1.)) 29 + round(1.) -30 | int(round(1., None)) | RUF046 [*] Value being cast to `int` is already an integer @@ -291,10 +259,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -29 | int(round(1.)) - - int(round(1., None)) +30 - int(round(1., None)) 30 + round(1., None) -31 | | RUF046 [*] Value being cast to `int` is already an integer @@ -309,10 +275,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -31 | - - int(1) +32 - int(1) 32 + 1 -33 | int(v := 1) | RUF046 [*] Value being cast to `int` is already an integer @@ -326,10 +290,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -32 | int(1) - - int(v := 1) +33 - int(v := 1) 33 + (v := 1) -34 | int(~1) | RUF046 [*] Value being cast to `int` is already an integer @@ -344,10 +306,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -33 | int(v := 1) - - int(~1) +34 - int(~1) 34 + ~1 -35 | int(-1) | RUF046 [*] Value being cast to `int` is already an integer @@ -361,10 +321,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -34 | int(~1) - - int(-1) +35 - int(-1) 35 + -1 -36 | int(+1) | RUF046 [*] Value being cast to `int` is already an integer @@ -379,10 +337,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -35 | int(-1) - - int(+1) +36 - int(+1) 36 + +1 -37 | | RUF046 [*] Value being cast to `int` is already an integer @@ -397,10 +353,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -37 | - - int(1 + 1) +38 - int(1 + 1) 38 + 1 + 1 -39 | int(1 - 1) | RUF046 [*] Value being cast to `int` is already an integer @@ -414,10 +368,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -38 | int(1 + 1) - - int(1 - 1) +39 - int(1 - 1) 39 + 1 - 1 -40 | int(1 * 1) | RUF046 [*] Value being cast to `int` is already an integer @@ -432,10 +384,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -39 | int(1 - 1) - - int(1 * 1) +40 - int(1 * 1) 40 + 1 * 1 -41 | int(1 % 1) | RUF046 [*] Value being cast to `int` is already an integer @@ -450,10 +400,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -40 | int(1 * 1) - - int(1 % 1) +41 - int(1 % 1) 41 + 1 % 1 -42 | int(1 ** 1) | RUF046 [*] Value being cast to `int` is already an integer @@ -468,10 +416,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -41 | int(1 % 1) - - int(1 ** 1) +42 - int(1 ** 1) 42 + 1 ** 1 -43 | int(1 << 1) | RUF046 [*] Value being cast to `int` is already an integer @@ -486,10 +432,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -42 | int(1 ** 1) - - int(1 << 1) +43 - int(1 << 1) 43 + 1 << 1 -44 | int(1 >> 1) | RUF046 [*] Value being cast to `int` is already an integer @@ -504,10 +448,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -43 | int(1 << 1) - - int(1 >> 1) +44 - int(1 >> 1) 44 + 1 >> 1 -45 | int(1 | 1) | RUF046 [*] Value being cast to `int` is already an integer @@ -522,10 +464,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -44 | int(1 >> 1) - - int(1 | 1) +45 - int(1 | 1) 45 + 1 | 1 -46 | int(1 ^ 1) | RUF046 [*] Value being cast to `int` is already an integer @@ -540,10 +480,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -45 | int(1 | 1) - - int(1 ^ 1) +46 - int(1 ^ 1) 46 + 1 ^ 1 -47 | int(1 & 1) | RUF046 [*] Value being cast to `int` is already an integer @@ -557,10 +495,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -46 | int(1 ^ 1) - - int(1 & 1) +47 - int(1 & 1) 47 + 1 & 1 -48 | int(1 // 1) | RUF046 [*] Value being cast to `int` is already an integer @@ -575,10 +511,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -47 | int(1 & 1) - - int(1 // 1) +48 - int(1 // 1) 48 + 1 // 1 -49 | | RUF046 [*] Value being cast to `int` is already an integer @@ -593,10 +527,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -49 | - - int(1 if ... else 2) +50 - int(1 if ... else 2) 50 + 1 if ... else 2 -51 | | RUF046 [*] Value being cast to `int` is already an integer @@ -610,10 +542,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -51 | - - int(1 and 0) +52 - int(1 and 0) 52 + 1 and 0 -53 | int(0 or -1) | RUF046 [*] Value being cast to `int` is already an integer @@ -624,10 +554,8 @@ RUF046 [*] Value being cast to `int` is already an integer | ^^^^^^^^^^^^ help: Remove unnecessary `int` call | -52 | int(1 and 0) - - int(0 or -1) +53 - int(0 or -1) 53 + 0 or -1 -54 | | RUF046 [*] Value being cast to `int` is already an integer @@ -639,10 +567,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -55 | - - if int(1 + 2) * 3: +56 - if int(1 + 2) * 3: 56 + if (1 + 2) * 3: -57 | ... | RUF046 [*] Value being cast to `int` is already an integer @@ -657,10 +583,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -61 | - - int(math.ceil()) +62 - int(math.ceil()) 62 + math.ceil() -63 | int(math.floor()) | note: This is an unsafe fix and may change runtime behavior @@ -674,10 +598,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -62 | int(math.ceil()) - - int(math.floor()) +63 - int(math.floor()) 63 + math.floor() -64 | int(math.trunc()) | note: This is an unsafe fix and may change runtime behavior @@ -693,10 +615,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -63 | int(math.floor()) - - int(math.trunc()) +64 - int(math.trunc()) 64 + math.trunc() -65 | | note: This is an unsafe fix and may change runtime behavior @@ -711,10 +631,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -65 | - - int(round(inferred_int, 0)) +66 - int(round(inferred_int, 0)) 66 + round(inferred_int, 0) -67 | int(round(inferred_int, 10)) | note: This is an unsafe fix and may change runtime behavior @@ -729,10 +647,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -66 | int(round(inferred_int, 0)) - - int(round(inferred_int, 10)) +67 - int(round(inferred_int, 10)) 67 + round(inferred_int, 10) -68 | | note: This is an unsafe fix and may change runtime behavior @@ -747,10 +663,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -68 | - - int(round(inferred_int)) +69 - int(round(inferred_int)) 69 + round(inferred_int) -70 | int(round(inferred_int, None)) | note: This is an unsafe fix and may change runtime behavior @@ -765,10 +679,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -69 | int(round(inferred_int)) - - int(round(inferred_int, None)) +70 - int(round(inferred_int, None)) 70 + round(inferred_int, None) -71 | | note: This is an unsafe fix and may change runtime behavior @@ -783,10 +695,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -71 | - - int(round(inferred_float)) +72 - int(round(inferred_float)) 72 + round(inferred_float) -73 | int(round(inferred_float, None)) | note: This is an unsafe fix and may change runtime behavior @@ -801,10 +711,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -72 | int(round(inferred_float)) - - int(round(inferred_float, None)) +73 - int(round(inferred_float, None)) 73 + round(inferred_float, None) -74 | | note: This is an unsafe fix and may change runtime behavior @@ -819,10 +727,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -74 | - - int(round(unknown)) +75 - int(round(unknown)) 75 + round(unknown) -76 | int(round(unknown, None)) | note: This is an unsafe fix and may change runtime behavior @@ -834,10 +740,8 @@ RUF046 [*] Value being cast to `int` is already an integer | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove unnecessary `int` call | -75 | int(round(unknown)) - - int(round(unknown, None)) +76 - int(round(unknown, None)) 76 + round(unknown, None) -77 | | note: This is an unsafe fix and may change runtime behavior @@ -854,10 +758,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -157 | - - int(1 + 158 + (1 + -159 | 1) +159 + 1) | RUF046 [*] Value being cast to `int` is already an integer @@ -873,12 +775,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -160 | - - int(round(1, - - 0)) 161 + round(1, 162 + 0) -163 | | RUF046 [*] Value being cast to `int` is already an integer @@ -894,10 +792,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -167 | # See https://github.com/astral-sh/ruff/issues/15263 - - int(round 168 + (round -169 | (1)) +169 + (1)) | RUF046 [*] Value being cast to `int` is already an integer @@ -915,14 +811,9 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -170 | - - int(round # a comment 171 + (round # a comment -172 | # and another comment - - (10) - - ) +172 + # and another comment 173 + (10)) -174 | | RUF046 [*] Value being cast to `int` is already an integer @@ -937,10 +828,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -175 | - - int(round (17)) # this is safe without parens +176 - int(round (17)) # this is safe without parens 176 + round (17) # this is safe without parens -177 | | RUF046 [*] Value being cast to `int` is already an integer @@ -957,13 +846,9 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -177 | - - int( round ( 178 + round ( -179 | 17 - - )) # this is also safe without parens -180 + ) # this is also safe without parens -181 | +179 + 17 +180 ~ ) # this is also safe without parens | RUF046 [*] Value being cast to `int` is already an integer @@ -980,13 +865,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -181 | - - int((round) # Comment - - (42) - - ) 182 + ((round) # Comment 183 + (42)) -184 | | RUF046 [*] Value being cast to `int` is already an integer @@ -1003,12 +883,8 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -185 | - - int((round # Comment 186 + (round # Comment -187 | )(42) - - ) -188 | +187 + )(42) | RUF046 [*] Value being cast to `int` is already an integer @@ -1028,14 +904,10 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -189 | - - int( # Unsafe fix because of this comment -190 | ( # Comment -191 | (round -192 | ) # Comment -193 | )(42) - - ) -194 | +190 + ( # Comment +191 + (round +192 + ) # Comment +193 + )(42) | note: This is an unsafe fix and may change runtime behavior @@ -1055,15 +927,9 @@ RUF046 [*] Value being cast to `int` is already an integer | help: Remove unnecessary `int` call | -196 | - - int( - - round( 197 + round( -198 | 42 - - ) # unsafe fix because of this comment - - ) +198 + 42 199 + ) -200 | | note: This is an unsafe fix and may change runtime behavior @@ -1081,14 +947,8 @@ RUF046 [*] Value being cast to `int` is already an integer | |_^ help: Remove unnecessary `int` call | -202 | - - int( - - round( 203 + round( -204 | 42 - - ) - - # unsafe fix because of this comment - - ) +204 + 42 205 + ) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF046_RUF046_CR.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF046_RUF046_CR.py.snap index 1b56a758d3c31..64531f25db137 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF046_RUF046_CR.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF046_RUF046_CR.py.snap @@ -9,4 +9,6 @@ RUF046 [*] Value being cast to `int` is already an integer | |______^ help: Remove unnecessary `int` call | - - int(- 1 + (- 2 | 1) # Carriage return as newline | +1 - int(-␍ 1) # Carriage return as newline␍ +1 + (-␍ 1) # Carriage return as newline␍ + | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF046_RUF046_LF.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF046_RUF046_LF.py.snap index fc945a5b783cf..dc3ecb176c31a 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF046_RUF046_LF.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF046_RUF046_LF.py.snap @@ -10,8 +10,6 @@ RUF046 [*] Value being cast to `int` is already an integer | |______^ help: Remove unnecessary `int` call | -1 | # \n as newline - - int(- 2 + (- -3 | 1) +3 + 1) | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF047_RUF047_for.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF047_RUF047_for.py.snap index 8d32c11f2f1c9..666749dd1951e 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF047_RUF047_for.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF047_RUF047_for.py.snap @@ -11,10 +11,8 @@ RUF047 [*] Empty `else` clause | |________^ help: Remove the `else` clause | -5 | break - - else: - - pass -6 | +6 - else: +7 - pass | RUF047 [*] Empty `else` clause @@ -27,8 +25,6 @@ RUF047 [*] Empty `else` clause | |_______^ help: Remove the `else` clause | -11 | belongs_to() # `for` - - else: - - ... -12 | +12 - else: +13 - ... | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF047_RUF047_if.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF047_RUF047_if.py.snap index 54b74d7ff33f4..5fe5b0d34220a 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF047_RUF047_if.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF047_RUF047_if.py.snap @@ -11,10 +11,8 @@ RUF047 [*] Empty `else` clause | |________^ help: Remove the `else` clause | -4 | condition_is_not_evaluated() - - else: - - pass -5 | +5 - else: +6 - pass | RUF047 [*] Empty `else` clause @@ -27,10 +25,8 @@ RUF047 [*] Empty `else` clause | |_______^ help: Remove the `else` clause | -10 | belongs_to() # `if` - - else: - - ... -11 | +11 - else: +12 - ... | RUF047 [*] Empty `else` clause @@ -43,10 +39,8 @@ RUF047 [*] Empty `else` clause | |________^ help: Remove the `else` clause | -18 | as_if() - - else: - - pass -19 | +19 - else: +20 - pass | RUF047 [*] Empty `else` clause @@ -62,10 +56,8 @@ RUF047 [*] Empty `else` clause | help: Remove the `else` clause | -25 | # `if` - - else: - - pass -26 | +26 - else: +27 - pass | RUF047 [*] Empty `else` clause @@ -78,10 +70,8 @@ RUF047 [*] Empty `else` clause | |________^ help: Remove the `else` clause | -31 | # `if` - - else: - - pass -32 | +32 - else: +33 - pass | RUF047 [*] Empty `else` clause @@ -92,9 +82,7 @@ RUF047 [*] Empty `else` clause | ^^^^^^^^^ help: Remove the `else` clause | -43 | if of_course: this() - - else: ... -44 | +44 - else: ... | RUF047 [*] Empty `else` clause @@ -106,9 +94,7 @@ RUF047 [*] Empty `else` clause | ^^^^^^^^^ help: Remove the `else` clause | -48 | this() # comment - - else: ... -49 | +49 - else: ... | RUF047 [*] Empty `else` clause @@ -121,8 +107,6 @@ RUF047 [*] Empty `else` clause | |___________^ help: Remove the `else` clause | -54 | b() - - else: - - ... -55 | +55 - else: +56 - ... | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF047_RUF047_try.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF047_RUF047_try.py.snap index 8e40273a77a18..c7453603d3c4e 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF047_RUF047_try.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF047_RUF047_try.py.snap @@ -11,10 +11,8 @@ RUF047 [*] Empty `else` clause | |________^ help: Remove the `else` clause | -6 | pass - - else: - - pass -7 | +7 - else: +8 - pass | RUF047 [*] Empty `else` clause @@ -27,8 +25,6 @@ RUF047 [*] Empty `else` clause | |_______^ help: Remove the `else` clause | -16 | to() # `except` - - else: - - ... -17 | +17 - else: +18 - ... | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF047_RUF047_while.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF047_RUF047_while.py.snap index e219f2ae8959c..9468e523c9b0f 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF047_RUF047_while.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF047_RUF047_while.py.snap @@ -11,10 +11,8 @@ RUF047 [*] Empty `else` clause | |________^ help: Remove the `else` clause | -5 | break - - else: - - pass -6 | +6 - else: +7 - pass | RUF047 [*] Empty `else` clause @@ -27,8 +25,6 @@ RUF047 [*] Empty `else` clause | |_______^ help: Remove the `else` clause | -11 | belongs_to() # `for` - - else: - - ... -12 | +12 - else: +13 - ... | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF050_RUF050.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF050_RUF050.py.snap index e36bfb7344a77..e475b29523e5a 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF050_RUF050.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF050_RUF050.py.snap @@ -13,10 +13,8 @@ RUF050 [*] Empty `if` statement | help: Remove the `if` statement | -3 | # Simple if with pass - - if True: - - pass -4 | +4 - if True: +5 - pass | RUF050 [*] Empty `if` statement @@ -30,12 +28,10 @@ RUF050 [*] Empty `if` statement 11 | # Side-effect-free condition (comparison) | help: Remove the `if` statement - | -7 | # Simple if with ellipsis - - if True: - - ... -8 | - | + | + 8 - if True: + 9 - ... + | RUF050 [*] Empty `if` statement --> RUF050.py:13:1 @@ -50,10 +46,8 @@ RUF050 [*] Empty `if` statement | help: Remove the `if` statement | -12 | import sys - - if sys.version_info >= (3, 11): - - pass -13 | +13 - if sys.version_info >= (3, 11): +14 - pass | RUF050 [*] Empty `if` statement @@ -68,10 +62,8 @@ RUF050 [*] Empty `if` statement | help: Remove the `if` statement | -16 | # Side-effect-free condition (boolean operator) - - if x and y: - - pass -17 | +17 - if x and y: +18 - pass | RUF050 [*] Empty `if` statement @@ -87,11 +79,9 @@ RUF050 [*] Empty `if` statement | help: Remove the `if` statement | -21 | def nested(): - - if a: - - pass +22 - if a: +23 - pass 22 + pass -23 | | RUF050 [*] Empty `if` statement @@ -105,9 +95,7 @@ RUF050 [*] Empty `if` statement | help: Remove the `if` statement | -25 | # Single-line form (pass) - - if True: pass -26 | +26 - if True: pass | RUF050 [*] Empty `if` statement @@ -121,9 +109,7 @@ RUF050 [*] Empty `if` statement | help: Remove the `if` statement | -28 | # Single-line form (ellipsis) - - if True: ... -29 | +29 - if True: ... | RUF050 [*] Empty `if` statement @@ -139,11 +125,9 @@ RUF050 [*] Empty `if` statement | help: Remove the `if` statement | -31 | # Multiple pass statements - - if True: - - pass - - pass -32 | +32 - if True: +33 - pass +34 - pass | RUF050 [*] Empty `if` statement @@ -159,11 +143,9 @@ RUF050 [*] Empty `if` statement | help: Remove the `if` statement | -36 | # Mixed pass and ellipsis - - if True: - - pass - - ... -37 | +37 - if True: +38 - pass +39 - ... | RUF050 [*] Empty `if` statement @@ -176,11 +158,9 @@ RUF050 [*] Empty `if` statement | |____________^ help: Remove the `if` statement | -42 | with pytest.raises(ValueError, match=msg): - - if obj1: - - pass +43 - if obj1: +44 - pass 43 + pass -44 | | RUF050 [*] Empty `if` statement @@ -195,11 +175,9 @@ RUF050 [*] Empty `if` statement | help: Remove the `if` statement | -49 | # Function call - - if foo(): - - pass +50 - if foo(): +51 - pass 50 + foo() -51 | | RUF050 [*] Empty `if` statement @@ -214,11 +192,9 @@ RUF050 [*] Empty `if` statement | help: Remove the `if` statement | -53 | # Method call - - if bar.baz(): - - pass +54 - if bar.baz(): +55 - pass 54 + bar.baz() -55 | | RUF050 [*] Empty `if` statement @@ -233,11 +209,9 @@ RUF050 [*] Empty `if` statement | help: Remove the `if` statement | -57 | # Nested call in boolean operator - - if x and foo(): - - pass +58 - if x and foo(): +59 - pass 58 + x and foo() -59 | | RUF050 [*] Empty `if` statement @@ -255,15 +229,10 @@ RUF050 [*] Empty `if` statement | help: Remove the `if` statement | -61 | # Multiline expression that needs outer parentheses - - if ( 62 + ( -63 | id(0) -64 | + 0 - - ): - - pass +63 + id(0) +64 + + 0 65 + ) -66 | | RUF050 [*] Empty `if` statement @@ -281,15 +250,10 @@ RUF050 [*] Empty `if` statement | help: Remove the `if` statement | -68 | # Multiline call stays a single expression statement - - if foo( 69 + foo( -70 | 1, -71 | 2, - - ): - - pass +70 + 1, +71 + 2, 72 + ) -73 | | RUF050 [*] Empty `if` statement @@ -304,11 +268,9 @@ RUF050 [*] Empty `if` statement | help: Remove the `if` statement | -75 | # Walrus operator with call - - if (x := foo()): - - pass +76 - if (x := foo()): +77 - pass 76 + (x := foo()) -77 | | RUF050 [*] Empty `if` statement @@ -323,11 +285,9 @@ RUF050 [*] Empty `if` statement | help: Remove the `if` statement | -79 | # Walrus operator without call - - if (x := y): - - pass +80 - if (x := y): +81 - pass 80 + (x := y) -81 | | RUF050 [*] Empty `if` statement @@ -340,9 +300,7 @@ RUF050 [*] Empty `if` statement | |____________^ help: Remove the `if` statement | -84 | class Foo: - - if foo(): - - pass +85 - if foo(): +86 - pass 85 + foo() -86 | | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF051_RUF051.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF051_RUF051.py.snap index 257e61a09ec35..b1efd54a4d38a 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF051_RUF051.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF051_RUF051.py.snap @@ -12,11 +12,9 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -6 | - - if k in d: # Bare name - - del d[k] +7 - if k in d: # Bare name +8 - del d[k] 7 + d.pop(k, None) -8 | | note: This is an unsafe fix and may change runtime behavior @@ -31,11 +29,9 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -9 | - - if '' in d: # String - - del d[""] # Different quotes +10 - if '' in d: # String +11 - del d[""] # Different quotes 10 + d.pop('', None) # Different quotes -11 | | note: This is an unsafe fix and may change runtime behavior @@ -52,13 +48,11 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -12 | - - if b"" in d: # Bytes - - del d[ # Multiline slice - - b'''''' # Triple quotes - - ] +13 - if b"" in d: # Bytes +14 - del d[ # Multiline slice +15 - b'''''' # Triple quotes +16 - ] 13 + d.pop(b"", None) -14 | | note: This is an unsafe fix and may change runtime behavior @@ -74,10 +68,8 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -17 | - - if 0 in d: del d[0] # Single-line statement +18 - if 0 in d: del d[0] # Single-line statement 18 + d.pop(0, None) # Single-line statement -19 | | RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` @@ -91,11 +83,9 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -19 | - - if 3j in d: # Complex - - del d[3j] +20 - if 3j in d: # Complex +21 - del d[3j] 20 + d.pop(3j, None) -21 | | note: This is an unsafe fix and may change runtime behavior @@ -110,11 +100,9 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -22 | - - if 0.1234 in d: # Float - - del d[.1_2_3_4] # Number separators and shorthand syntax +23 - if 0.1234 in d: # Float +24 - del d[.1_2_3_4] # Number separators and shorthand syntax 23 + d.pop(0.1234, None) # Number separators and shorthand syntax -24 | | note: This is an unsafe fix and may change runtime behavior @@ -129,11 +117,9 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -25 | - - if True in d: # True - - del d[True] +26 - if True in d: # True +27 - del d[True] 26 + d.pop(True, None) -27 | | note: This is an unsafe fix and may change runtime behavior @@ -148,11 +134,9 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -28 | - - if False in d: # False - - del d[False] +29 - if False in d: # False +30 - del d[False] 29 + d.pop(False, None) -30 | | note: This is an unsafe fix and may change runtime behavior @@ -170,14 +154,12 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -31 | - - if None in d: # None - - del d[ - - # Comment in the middle - - None - - ] +32 - if None in d: # None +33 - del d[ +34 - # Comment in the middle +35 - None +36 - ] 32 + d.pop(None, None) -33 | | note: This is an unsafe fix and may change runtime behavior @@ -194,13 +176,11 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -37 | - - if ... in d: # Ellipsis - - del d[ - - # Comment in the middle, indented - - ...] +38 - if ... in d: # Ellipsis +39 - del d[ +40 - # Comment in the middle, indented +41 - ...] 38 + d.pop(..., None) -39 | | note: This is an unsafe fix and may change runtime behavior @@ -215,11 +195,9 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -42 | - - if "a" "bc" in d: # String concatenation - - del d['abc'] +43 - if "a" "bc" in d: # String concatenation +44 - del d['abc'] 43 + d.pop("a" "bc", None) -44 | | note: This is an unsafe fix and may change runtime behavior @@ -234,11 +212,9 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -45 | - - if r"\foo" in d: # Raw string - - del d['\\foo'] +46 - if r"\foo" in d: # Raw string +47 - del d['\\foo'] 46 + d.pop(r"\foo", None) -47 | | note: This is an unsafe fix and may change runtime behavior @@ -253,11 +229,9 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -48 | - - if b'yt' b'es' in d: # Bytes concatenation - - del d[rb"""ytes"""] # Raw bytes +49 - if b'yt' b'es' in d: # Bytes concatenation +50 - del d[rb"""ytes"""] # Raw bytes 49 + d.pop(b'yt' b'es', None) # Raw bytes -50 | | note: This is an unsafe fix and may change runtime behavior @@ -273,12 +247,10 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -51 | - - if k in d: - - # comment that gets dropped - - del d[k] +52 - if k in d: +53 - # comment that gets dropped +54 - del d[k] 52 + d.pop(k, None) -53 | | note: This is an unsafe fix and may change runtime behavior @@ -293,11 +265,9 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -57 | - - if k in d: - - del d[k] +58 - if k in d: +59 - del d[k] 58 + d.pop(k, None) -59 | | RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` @@ -311,11 +281,9 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -60 | - - if '' in d: - - del d[""] +61 - if '' in d: +62 - del d[""] 61 + d.pop('', None) -62 | | RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` @@ -331,13 +299,11 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -63 | - - if b"" in d: - - del d[ - - b'''''' - - ] +64 - if b"" in d: +65 - del d[ +66 - b'''''' +67 - ] 64 + d.pop(b"", None) -65 | | RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` @@ -352,10 +318,8 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -68 | - - if 0 in d: del d[0] +69 - if 0 in d: del d[0] 69 + d.pop(0, None) -70 | | RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` @@ -369,11 +333,9 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -70 | - - if 3j in d: - - del d[3j] +71 - if 3j in d: +72 - del d[3j] 71 + d.pop(3j, None) -72 | | RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` @@ -387,11 +349,9 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -73 | - - if 0.1234 in d: - - del d[.1_2_3_4] +74 - if 0.1234 in d: +75 - del d[.1_2_3_4] 74 + d.pop(0.1234, None) -75 | | RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` @@ -405,11 +365,9 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -76 | - - if True in d: - - del d[True] +77 - if True in d: +78 - del d[True] 77 + d.pop(True, None) -78 | | RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` @@ -423,11 +381,9 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -79 | - - if False in d: - - del d[False] +80 - if False in d: +81 - del d[False] 80 + d.pop(False, None) -81 | | RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` @@ -443,13 +399,11 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -82 | - - if None in d: - - del d[ - - None - - ] +83 - if None in d: +84 - del d[ +85 - None +86 - ] 83 + d.pop(None, None) -84 | | RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` @@ -464,12 +418,10 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -87 | - - if ... in d: - - del d[ - - ...] +88 - if ... in d: +89 - del d[ +90 - ...] 88 + d.pop(..., None) -89 | | RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` @@ -483,11 +435,9 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -91 | - - if "a" "bc" in d: - - del d['abc'] +92 - if "a" "bc" in d: +93 - del d['abc'] 92 + d.pop("a" "bc", None) -93 | | RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` @@ -501,11 +451,9 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | help: Replace `if` statement with `.pop(..., None)` | -94 | - - if r"\foo" in d: - - del d['\\foo'] +95 - if r"\foo" in d: +96 - del d['\\foo'] 95 + d.pop(r"\foo", None) -96 | | RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` @@ -516,9 +464,7 @@ RUF051 [*] Use `pop` instead of `key in dict` followed by `del dict[key]` | ^^^^^^^^^^^^^^^^^^^ help: Replace `if` statement with `.pop(..., None)` | -97 | - - if b'yt' b'es' in d: - - del d[rb"""ytes"""] # This should not make the fix unsafe +98 - if b'yt' b'es' in d: +99 - del d[rb"""ytes"""] # This should not make the fix unsafe 98 + d.pop(b'yt' b'es', None) # This should not make the fix unsafe -99 | | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF052_RUF052_0.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF052_RUF052_0.py.snap index 6a1e7232f79ee..6da1c659a3393 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF052_RUF052_0.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF052_RUF052_0.py.snap @@ -12,12 +12,8 @@ RUF052 [*] Local dummy variable `_var` is accessed | help: Remove leading underscores | -91 | def fun(self): - - _var = "method variable" # [RUF052] - - return _var -92 + var = "method variable" # [RUF052] -93 + return var -94 | +92 ~ var = "method variable" # [RUF052] +93 ~ return var | note: This is an unsafe fix and may change runtime behavior @@ -31,12 +27,8 @@ RUF052 [*] Local dummy variable `_list` is accessed | help: Prefer using trailing underscores to avoid shadowing a built-in | -98 | def fun(): - - _list = "built-in" # [RUF052] - - return _list -99 + list_ = "built-in" # [RUF052] -100 + return list_ -101 | + 99 ~ list_ = "built-in" # [RUF052] +100 ~ return list_ | note: This is an unsafe fix and may change runtime behavior @@ -51,12 +43,8 @@ RUF052 [*] Local dummy variable `_x` is accessed | help: Prefer using trailing underscores to avoid shadowing a variable | -105 | global x - - _x = "shadows global" # [RUF052] - - return _x -106 + x_ = "shadows global" # [RUF052] -107 + return x_ -108 | +106 ~ x_ = "shadows global" # [RUF052] +107 ~ return x_ | note: This is an unsafe fix and may change runtime behavior @@ -72,12 +60,8 @@ RUF052 [*] Local dummy variable `_x` is accessed | help: Prefer using trailing underscores to avoid shadowing a variable | -112 | nonlocal x - - _x = "shadows nonlocal" # [RUF052] - - return _x -113 + x_ = "shadows nonlocal" # [RUF052] -114 + return x_ -115 | bar() +113 ~ x_ = "shadows nonlocal" # [RUF052] +114 ~ return x_ | note: This is an unsafe fix and may change runtime behavior @@ -92,12 +76,8 @@ RUF052 [*] Local dummy variable `_x` is accessed | help: Prefer using trailing underscores to avoid shadowing a variable | -119 | x = "local" - - _x = "shadows local" # [RUF052] - - return _x -120 + x_ = "shadows local" # [RUF052] -121 + return x_ -122 | +120 ~ x_ = "shadows local" # [RUF052] +121 ~ return x_ | note: This is an unsafe fix and may change runtime behavior @@ -155,15 +135,11 @@ RUF052 [*] Local dummy variable `_P` is accessed | help: Remove leading underscores | -152 | - - _P = ParamSpec("_P") -153 + P = ParamSpec("P") +153 ~ P = ParamSpec("P") 154 | _T = TypeVar(name="_T", covariant=True, bound=int|str) --------------------------------------------------------------------------------- + … 161 | - - print(_T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -162 + print(_T, P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -163 | +162 ~ print(_T, P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) | note: This is an unsafe fix and may change runtime behavior @@ -178,15 +154,11 @@ RUF052 [*] Local dummy variable `_T` is accessed | help: Remove leading underscores | -153 | _P = ParamSpec("_P") - - _T = TypeVar(name="_T", covariant=True, bound=int|str) -154 + T = TypeVar(name="T", covariant=True, bound=int|str) +154 ~ T = TypeVar(name="T", covariant=True, bound=int|str) 155 | _NT = NamedTuple("_NT", [("foo", int)]) --------------------------------------------------------------------------------- + … 161 | - - print(_T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -162 + print(T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -163 | +162 ~ print(T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) | note: This is an unsafe fix and may change runtime behavior @@ -202,15 +174,11 @@ RUF052 [*] Local dummy variable `_NT` is accessed | help: Remove leading underscores | -154 | _T = TypeVar(name="_T", covariant=True, bound=int|str) - - _NT = NamedTuple("_NT", [("foo", int)]) -155 + NT = NamedTuple("NT", [("foo", int)]) +155 ~ NT = NamedTuple("NT", [("foo", int)]) 156 | _E = Enum("_E", ["a", "b", "c"]) --------------------------------------------------------------------------------- + … 161 | - - print(_T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -162 + print(_T, _P, NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -163 | +162 ~ print(_T, _P, NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) | note: This is an unsafe fix and may change runtime behavior @@ -226,15 +194,11 @@ RUF052 [*] Local dummy variable `_E` is accessed | help: Remove leading underscores | -155 | _NT = NamedTuple("_NT", [("foo", int)]) - - _E = Enum("_E", ["a", "b", "c"]) -156 + E = Enum("E", ["a", "b", "c"]) +156 ~ E = Enum("E", ["a", "b", "c"]) 157 | _NT2 = namedtuple("_NT2", ['x', 'y', 'z']) --------------------------------------------------------------------------------- + … 161 | - - print(_T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -162 + print(_T, _P, _NT, E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -163 | +162 ~ print(_T, _P, _NT, E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) | note: This is an unsafe fix and may change runtime behavior @@ -250,16 +214,11 @@ RUF052 [*] Local dummy variable `_NT2` is accessed | help: Remove leading underscores | -156 | _E = Enum("_E", ["a", "b", "c"]) - - _NT2 = namedtuple("_NT2", ['x', 'y', 'z']) -157 + NT2 = namedtuple("NT2", ['x', 'y', 'z']) +157 ~ NT2 = namedtuple("NT2", ['x', 'y', 'z']) 158 | _NT3 = namedtuple(typename="_NT3", field_names=['x', 'y', 'z']) -159 | _DynamicClass = type("_DynamicClass", (), {}) -160 | _NotADynamicClass = type("_NotADynamicClass") + … 161 | - - print(_T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -162 + print(_T, _P, _NT, _E, NT2, _NT3, _DynamicClass, _NotADynamicClass) -163 | +162 ~ print(_T, _P, _NT, _E, NT2, _NT3, _DynamicClass, _NotADynamicClass) | note: This is an unsafe fix and may change runtime behavior @@ -275,15 +234,11 @@ RUF052 [*] Local dummy variable `_NT3` is accessed | help: Remove leading underscores | -157 | _NT2 = namedtuple("_NT2", ['x', 'y', 'z']) - - _NT3 = namedtuple(typename="_NT3", field_names=['x', 'y', 'z']) -158 + NT3 = namedtuple(typename="NT3", field_names=['x', 'y', 'z']) +158 ~ NT3 = namedtuple(typename="NT3", field_names=['x', 'y', 'z']) 159 | _DynamicClass = type("_DynamicClass", (), {}) 160 | _NotADynamicClass = type("_NotADynamicClass") 161 | - - print(_T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -162 + print(_T, _P, _NT, _E, _NT2, NT3, _DynamicClass, _NotADynamicClass) -163 | +162 ~ print(_T, _P, _NT, _E, _NT2, NT3, _DynamicClass, _NotADynamicClass) | note: This is an unsafe fix and may change runtime behavior @@ -298,14 +253,10 @@ RUF052 [*] Local dummy variable `_DynamicClass` is accessed | help: Remove leading underscores | -158 | _NT3 = namedtuple(typename="_NT3", field_names=['x', 'y', 'z']) - - _DynamicClass = type("_DynamicClass", (), {}) -159 + DynamicClass = type("DynamicClass", (), {}) +159 ~ DynamicClass = type("DynamicClass", (), {}) 160 | _NotADynamicClass = type("_NotADynamicClass") 161 | - - print(_T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -162 + print(_T, _P, _NT, _E, _NT2, _NT3, DynamicClass, _NotADynamicClass) -163 | +162 ~ print(_T, _P, _NT, _E, _NT2, _NT3, DynamicClass, _NotADynamicClass) | note: This is an unsafe fix and may change runtime behavior @@ -321,13 +272,9 @@ RUF052 [*] Local dummy variable `_NotADynamicClass` is accessed | help: Remove leading underscores | -159 | _DynamicClass = type("_DynamicClass", (), {}) - - _NotADynamicClass = type("_NotADynamicClass") -160 + NotADynamicClass = type("_NotADynamicClass") +160 ~ NotADynamicClass = type("_NotADynamicClass") 161 | - - print(_T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -162 + print(_T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, NotADynamicClass) -163 | +162 ~ print(_T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, NotADynamicClass) | note: This is an unsafe fix and may change runtime behavior @@ -342,15 +289,11 @@ RUF052 [*] Local dummy variable `_dummy_var` is accessed | help: Prefer using trailing underscores to avoid shadowing a variable | -181 | def foo(): - - _dummy_var = 42 -182 + dummy_var_ = 42 +182 ~ dummy_var_ = 42 183 | 184 | def bar(): 185 | dummy_var = 43 - - print(_dummy_var) -186 + print(dummy_var_) -187 | +186 ~ print(dummy_var_) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF052_RUF052_1.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF052_RUF052_1.py.snap index 2ae8ce6851152..3785139a575a7 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF052_RUF052_1.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF052_RUF052_1.py.snap @@ -11,12 +11,8 @@ RUF052 [*] Local dummy variable `_item` is accessed | help: Remove leading underscores | -20 | # Should detect used dummy variable - - for _item in my_list: - - print(_item["foo"]) # RUF052: Local dummy variable `_item` is accessed -21 + for item in my_list: -22 + print(item["foo"]) # RUF052: Local dummy variable `_item` is accessed -23 | +21 ~ for item in my_list: +22 ~ print(item["foo"]) # RUF052: Local dummy variable `_item` is accessed | note: This is an unsafe fix and may change runtime behavior @@ -30,12 +26,8 @@ RUF052 [*] Local dummy variable `_index` is accessed | help: Remove leading underscores | -24 | # Should detect used dummy variable - - for _index, _value in enumerate(my_list): - - result = _index + _value["foo"] # RUF052: Both `_index` and `_value` are accessed -25 + for index, _value in enumerate(my_list): -26 + result = index + _value["foo"] # RUF052: Both `_index` and `_value` are accessed -27 | +25 ~ for index, _value in enumerate(my_list): +26 ~ result = index + _value["foo"] # RUF052: Both `_index` and `_value` are accessed | note: This is an unsafe fix and may change runtime behavior @@ -49,12 +41,8 @@ RUF052 [*] Local dummy variable `_value` is accessed | help: Remove leading underscores | -24 | # Should detect used dummy variable - - for _index, _value in enumerate(my_list): - - result = _index + _value["foo"] # RUF052: Both `_index` and `_value` are accessed -25 + for _index, value in enumerate(my_list): -26 + result = _index + value["foo"] # RUF052: Both `_index` and `_value` are accessed -27 | +25 ~ for _index, value in enumerate(my_list): +26 ~ result = _index + value["foo"] # RUF052: Both `_index` and `_value` are accessed | note: This is an unsafe fix and may change runtime behavior @@ -69,10 +57,8 @@ RUF052 [*] Local dummy variable `_item` is accessed | help: Remove leading underscores | -32 | # Should detect used dummy variable - - result = [_item["foo"] for _item in my_list] # RUF052: Local dummy variable `_item` is accessed +33 - result = [_item["foo"] for _item in my_list] # RUF052: Local dummy variable `_item` is accessed 33 + result = [item["foo"] for item in my_list] # RUF052: Local dummy variable `_item` is accessed -34 | | note: This is an unsafe fix and may change runtime behavior @@ -86,10 +72,8 @@ RUF052 [*] Local dummy variable `_item` is accessed | help: Remove leading underscores | -35 | # Should detect used dummy variable in nested comprehension - - nested = [[_item["foo"] for _item in _sublist] for _sublist in [my_list, my_list]] +36 - nested = [[_item["foo"] for _item in _sublist] for _sublist in [my_list, my_list]] 36 + nested = [[item["foo"] for item in _sublist] for _sublist in [my_list, my_list]] -37 | # RUF052: Both `_item` and `_sublist` are accessed | note: This is an unsafe fix and may change runtime behavior @@ -103,10 +87,8 @@ RUF052 [*] Local dummy variable `_sublist` is accessed | help: Remove leading underscores | -35 | # Should detect used dummy variable in nested comprehension - - nested = [[_item["foo"] for _item in _sublist] for _sublist in [my_list, my_list]] +36 - nested = [[_item["foo"] for _item in _sublist] for _sublist in [my_list, my_list]] 36 + nested = [[_item["foo"] for _item in sublist] for sublist in [my_list, my_list]] -37 | # RUF052: Both `_item` and `_sublist` are accessed | note: This is an unsafe fix and may change runtime behavior @@ -120,10 +102,8 @@ RUF052 [*] Local dummy variable `_item` is accessed | help: Remove leading underscores | -39 | # Should detect with conditions - - filtered = [_item["foo"] for _item in my_list if _item["foo"] > 0] +40 - filtered = [_item["foo"] for _item in my_list if _item["foo"] > 0] 40 + filtered = [item["foo"] for item in my_list if item["foo"] > 0] -41 | # RUF052: Local dummy variable `_item` is accessed | note: This is an unsafe fix and may change runtime behavior @@ -137,10 +117,8 @@ RUF052 [*] Local dummy variable `_item` is accessed | help: Remove leading underscores | -47 | # Should detect used dummy variable - - result = {_item["key"]: _item["value"] for _item in my_list} +48 - result = {_item["key"]: _item["value"] for _item in my_list} 48 + result = {item["key"]: item["value"] for item in my_list} -49 | # RUF052: Local dummy variable `_item` is accessed | note: This is an unsafe fix and may change runtime behavior @@ -154,10 +132,8 @@ RUF052 [*] Local dummy variable `_index` is accessed | help: Remove leading underscores | -51 | # Should detect with enumerate - - indexed = {_index: _item["value"] for _index, _item in enumerate(my_list)} +52 - indexed = {_index: _item["value"] for _index, _item in enumerate(my_list)} 52 + indexed = {index: _item["value"] for index, _item in enumerate(my_list)} -53 | # RUF052: Both `_index` and `_item` are accessed | note: This is an unsafe fix and may change runtime behavior @@ -171,10 +147,8 @@ RUF052 [*] Local dummy variable `_item` is accessed | help: Remove leading underscores | -51 | # Should detect with enumerate - - indexed = {_index: _item["value"] for _index, _item in enumerate(my_list)} +52 - indexed = {_index: _item["value"] for _index, _item in enumerate(my_list)} 52 + indexed = {_index: item["value"] for _index, item in enumerate(my_list)} -53 | # RUF052: Both `_index` and `_item` are accessed | note: This is an unsafe fix and may change runtime behavior @@ -189,10 +163,8 @@ RUF052 [*] Local dummy variable `_inner` is accessed | help: Remove leading underscores | -55 | # Should detect in nested dict comprehension - - nested = {_outer: {_inner["key"]: _inner["value"] for _inner in sublist} +56 - nested = {_outer: {_inner["key"]: _inner["value"] for _inner in sublist} 56 + nested = {_outer: {inner["key"]: inner["value"] for inner in sublist} -57 | for _outer, sublist in enumerate([my_list])} | note: This is an unsafe fix and may change runtime behavior @@ -207,12 +179,8 @@ RUF052 [*] Local dummy variable `_outer` is accessed | help: Remove leading underscores | -55 | # Should detect in nested dict comprehension - - nested = {_outer: {_inner["key"]: _inner["value"] for _inner in sublist} - - for _outer, sublist in enumerate([my_list])} -56 + nested = {outer: {_inner["key"]: _inner["value"] for _inner in sublist} -57 + for outer, sublist in enumerate([my_list])} -58 | # RUF052: `_outer`, `_inner` are accessed +56 ~ nested = {outer: {_inner["key"]: _inner["value"] for _inner in sublist} +57 ~ for outer, sublist in enumerate([my_list])} | note: This is an unsafe fix and may change runtime behavior @@ -226,10 +194,8 @@ RUF052 [*] Local dummy variable `_item` is accessed | help: Remove leading underscores | -64 | # Should detect used dummy variable - - unique_values = {_item["foo"] for _item in my_list} +65 - unique_values = {_item["foo"] for _item in my_list} 65 + unique_values = {item["foo"] for item in my_list} -66 | # RUF052: Local dummy variable `_item` is accessed | note: This is an unsafe fix and may change runtime behavior @@ -243,10 +209,8 @@ RUF052 [*] Local dummy variable `_item` is accessed | help: Remove leading underscores | -68 | # Should detect with conditions - - filtered_set = {_item["foo"] for _item in my_list if _item["foo"] > 0} +69 - filtered_set = {_item["foo"] for _item in my_list if _item["foo"] > 0} 69 + filtered_set = {item["foo"] for item in my_list if item["foo"] > 0} -70 | # RUF052: Local dummy variable `_item` is accessed | note: This is an unsafe fix and may change runtime behavior @@ -260,10 +224,8 @@ RUF052 [*] Local dummy variable `_item` is accessed | help: Remove leading underscores | -72 | # Should detect with complex expression - - processed = {_item["foo"] * 2 for _item in my_list} +73 - processed = {_item["foo"] * 2 for _item in my_list} 73 + processed = {item["foo"] * 2 for item in my_list} -74 | # RUF052: Local dummy variable `_item` is accessed | note: This is an unsafe fix and may change runtime behavior @@ -277,10 +239,8 @@ RUF052 [*] Local dummy variable `_item` is accessed | help: Remove leading underscores | -80 | # Should detect used dummy variable - - gen = (_item["foo"] for _item in my_list) +81 - gen = (_item["foo"] for _item in my_list) 81 + gen = (item["foo"] for item in my_list) -82 | # RUF052: Local dummy variable `_item` is accessed | note: This is an unsafe fix and may change runtime behavior @@ -294,10 +254,8 @@ RUF052 [*] Local dummy variable `_item` is accessed | help: Remove leading underscores | -84 | # Should detect when passed to function - - total = sum(_item["foo"] for _item in my_list) +85 - total = sum(_item["foo"] for _item in my_list) 85 + total = sum(item["foo"] for item in my_list) -86 | # RUF052: Local dummy variable `_item` is accessed | note: This is an unsafe fix and may change runtime behavior @@ -311,10 +269,8 @@ RUF052 [*] Local dummy variable `_x` is accessed | help: Remove leading underscores | -88 | # Should detect with multiple generators - - pairs = ((_x, _y) for _x in range(3) for _y in range(3) if _x != _y) +89 - pairs = ((_x, _y) for _x in range(3) for _y in range(3) if _x != _y) 89 + pairs = ((x, _y) for x in range(3) for _y in range(3) if x != _y) -90 | # RUF052: Both `_x` and `_y` are accessed | note: This is an unsafe fix and may change runtime behavior @@ -328,10 +284,8 @@ RUF052 [*] Local dummy variable `_y` is accessed | help: Remove leading underscores | -88 | # Should detect with multiple generators - - pairs = ((_x, _y) for _x in range(3) for _y in range(3) if _x != _y) +89 - pairs = ((_x, _y) for _x in range(3) for _y in range(3) if _x != _y) 89 + pairs = ((_x, y) for _x in range(3) for y in range(3) if _x != y) -90 | # RUF052: Both `_x` and `_y` are accessed | note: This is an unsafe fix and may change runtime behavior @@ -345,10 +299,8 @@ RUF052 [*] Local dummy variable `_inner` is accessed | help: Remove leading underscores | -92 | # Should detect in nested generator - - nested_gen = (sum(_inner["foo"] for _inner in sublist) for _sublist in [my_list] for sublist in _sublist) +93 - nested_gen = (sum(_inner["foo"] for _inner in sublist) for _sublist in [my_list] for sublist in _sublist) 93 + nested_gen = (sum(inner["foo"] for inner in sublist) for _sublist in [my_list] for sublist in _sublist) -94 | # RUF052: `_inner` and `_sublist` are accessed | note: This is an unsafe fix and may change runtime behavior @@ -362,10 +314,8 @@ RUF052 [*] Local dummy variable `_sublist` is accessed | help: Prefer using trailing underscores to avoid shadowing a variable | -92 | # Should detect in nested generator - - nested_gen = (sum(_inner["foo"] for _inner in sublist) for _sublist in [my_list] for sublist in _sublist) +93 - nested_gen = (sum(_inner["foo"] for _inner in sublist) for _sublist in [my_list] for sublist in _sublist) 93 + nested_gen = (sum(_inner["foo"] for _inner in sublist) for sublist_ in [my_list] for sublist in sublist_) -94 | # RUF052: `_inner` and `_sublist` are accessed | note: This is an unsafe fix and may change runtime behavior @@ -381,10 +331,8 @@ RUF052 [*] Local dummy variable `_val` is accessed | help: Remove leading underscores | -101 | result = [ - - {_key: [_val * 2 for _val in _record["items"]] for _key in ["doubled"]} +102 - {_key: [_val * 2 for _val in _record["items"]] for _key in ["doubled"]} 102 + {_key: [val * 2 for val in _record["items"]] for _key in ["doubled"]} -103 | for _record in data | note: This is an unsafe fix and may change runtime behavior @@ -400,10 +348,8 @@ RUF052 [*] Local dummy variable `_key` is accessed | help: Remove leading underscores | -101 | result = [ - - {_key: [_val * 2 for _val in _record["items"]] for _key in ["doubled"]} +102 - {_key: [_val * 2 for _val in _record["items"]] for _key in ["doubled"]} 102 + {key: [_val * 2 for _val in _record["items"]] for key in ["doubled"]} -103 | for _record in data | note: This is an unsafe fix and may change runtime behavior @@ -419,12 +365,8 @@ RUF052 [*] Local dummy variable `_record` is accessed | help: Remove leading underscores | -101 | result = [ - - {_key: [_val * 2 for _val in _record["items"]] for _key in ["doubled"]} - - for _record in data -102 + {_key: [_val * 2 for _val in record["items"]] for _key in ["doubled"]} -103 + for record in data -104 | ] +102 ~ {_key: [_val * 2 for _val in record["items"]] for _key in ["doubled"]} +103 ~ for record in data | note: This is an unsafe fix and may change runtime behavior @@ -438,9 +380,7 @@ RUF052 [*] Local dummy variable `_item` is accessed | help: Remove leading underscores | -107 | # Should detect in generator passed to list constructor - - gen_list = list(_item["items"][0] for _item in data) +108 - gen_list = list(_item["items"][0] for _item in data) 108 + gen_list = list(item["items"][0] for item in data) -109 | # RUF052: Local dummy variable `_item` is accessed | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF053_RUF053.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF053_RUF053.py.snap index ec5fcd2256cab..20cc3872b734f 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF053_RUF053.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF053_RUF053.py.snap @@ -13,10 +13,8 @@ RUF053 [*] Class with type parameter list inherits from `Generic` | help: Remove `Generic` base class | -22 | - - class C[T](Generic[_A]): ... +23 - class C[T](Generic[_A]): ... 23 + class C[T, _A]: ... -24 | class C[T](Generic[_B], str): ... | note: This is an unsafe fix and may change runtime behavior @@ -31,10 +29,8 @@ RUF053 [*] Class with type parameter list inherits from `Generic` | help: Remove `Generic` base class | -23 | class C[T](Generic[_A]): ... - - class C[T](Generic[_B], str): ... +24 - class C[T](Generic[_B], str): ... 24 + class C[T, _B: int](str): ... -25 | class C[T](int, Generic[_C]): ... | note: This is an unsafe fix and may change runtime behavior @@ -50,10 +46,8 @@ RUF053 [*] Class with type parameter list inherits from `Generic` | help: Remove `Generic` base class | -24 | class C[T](Generic[_B], str): ... - - class C[T](int, Generic[_C]): ... +25 - class C[T](int, Generic[_C]): ... 25 + class C[T, _C: (str, bytes)](int): ... -26 | class C[T](bytes, Generic[_D], bool): ... # TODO: Type parameter defaults | note: This is an unsafe fix and may change runtime behavior @@ -104,10 +98,8 @@ RUF053 [*] Class with type parameter list inherits from `Generic` | help: Remove `Generic` base class | -29 | - - class C[*Ts](Generic[*_As]): ... +30 - class C[*Ts](Generic[*_As]): ... 30 + class C[*Ts, *_As]: ... -31 | class C[*Ts](Generic[Unpack[_As]]): ... | note: This is an unsafe fix and may change runtime behavior @@ -122,10 +114,8 @@ RUF053 [*] Class with type parameter list inherits from `Generic` | help: Remove `Generic` base class | -30 | class C[*Ts](Generic[*_As]): ... - - class C[*Ts](Generic[Unpack[_As]]): ... +31 - class C[*Ts](Generic[Unpack[_As]]): ... 31 + class C[*Ts, *_As]: ... -32 | class C[*Ts](Generic[Unpack[_Bs]], tuple[*Bs]): ... | note: This is an unsafe fix and may change runtime behavior @@ -159,10 +149,8 @@ RUF053 [*] Class with type parameter list inherits from `Generic` | help: Remove `Generic` base class | -35 | - - class C[**P](Generic[_P1]): ... +36 - class C[**P](Generic[_P1]): ... 36 + class C[**P, **_P1]: ... -37 | class C[**P](Generic[_P2]): ... | note: This is an unsafe fix and may change runtime behavior @@ -192,10 +180,8 @@ RUF053 [*] Class with type parameter list inherits from `Generic` | ^^^^^^^^^^^^^^ help: Remove `Generic` base class | -40 | - - class C[T](Generic[T, _A]): ... +41 - class C[T](Generic[T, _A]): ... 41 + class C[T, _A]: ... -42 | | note: This is an unsafe fix and may change runtime behavior @@ -216,10 +202,8 @@ RUF053 [*] Class with type parameter list inherits from `Generic` | ^^^^^^^^^^^^^^ help: Remove `Generic` base class | -50 | class C(Generic[_B]): - - class D[T](Generic[_B, T]): ... +51 - class D[T](Generic[_B, T]): ... 51 + class D[T, _B: int]: ... -52 | | note: This is an unsafe fix and may change runtime behavior @@ -242,10 +226,8 @@ RUF053 [*] Class with type parameter list inherits from `Generic` | help: Remove `Generic` base class | -59 | # Others will be reported/fixed in following iterations. - - class C[T](Generic[_C], Generic[_D]): ... +60 - class C[T](Generic[_C], Generic[_D]): ... 60 + class C[T, _C: (str, bytes)](Generic[_D]): ... -61 | class C[T, _C: (str, bytes)](Generic[_D]): ... # TODO: Type parameter defaults | note: This is an unsafe fix and may change runtime behavior @@ -342,10 +324,8 @@ RUF053 [*] Class with type parameter list inherits from `Generic` | help: Remove `Generic` base class | -76 | - - class C[T](Generic[_A, _A]): ... +77 - class C[T](Generic[_A, _A]): ... 77 + class C[T, _A]: ... -78 | class C[T](Generic[_A, Unpack[_As]]): ... | note: This is an unsafe fix and may change runtime behavior @@ -359,10 +339,8 @@ RUF053 [*] Class with type parameter list inherits from `Generic` | help: Remove `Generic` base class | -77 | class C[T](Generic[_A, _A]): ... - - class C[T](Generic[_A, Unpack[_As]]): ... +78 - class C[T](Generic[_A, Unpack[_As]]): ... 78 + class C[T, _A, *_As]: ... -79 | class C[T](Generic[*_As, _A]): ... | note: This is an unsafe fix and may change runtime behavior @@ -375,10 +353,8 @@ RUF053 [*] Class with type parameter list inherits from `Generic` | ^^^^^^^^^^^^^^^^^ help: Remove `Generic` base class | -78 | class C[T](Generic[_A, Unpack[_As]]): ... - - class C[T](Generic[*_As, _A]): ... +79 - class C[T](Generic[*_As, _A]): ... 79 + class C[T, *_As, _A]: ... -80 | | note: This is an unsafe fix and may change runtime behavior @@ -410,10 +386,8 @@ RUF053 [*] Class with type parameter list inherits from `Generic` | ^^^^^^^^^^^ help: Remove `Generic` base class | -90 | # See also the `_Z` example above. - - class C[T](Generic[_G]): ... # Should be moved down below eventually +91 - class C[T](Generic[_G]): ... # Should be moved down below eventually 91 + class C[T, _G: (str, a := int)]: ... # Should be moved down below eventually -92 | | note: This is an unsafe fix and may change runtime behavior @@ -427,10 +401,8 @@ RUF053 [*] Class with type parameter list inherits from `Generic` | help: Remove `Generic` base class | -94 | # Single-element constraints should not be converted to a bound. - - class C[T: (str,)](Generic[_A]): ... +95 - class C[T: (str,)](Generic[_A]): ... 95 + class C[T: (str), _A]: ... -96 | class C[T: [a]](Generic[_A]): ... | note: This is an unsafe fix and may change runtime behavior @@ -443,9 +415,7 @@ RUF053 [*] Class with type parameter list inherits from `Generic` | ^^^^^^^^^^^ help: Remove `Generic` base class | -95 | class C[T: (str,)](Generic[_A]): ... - - class C[T: [a]](Generic[_A]): ... +96 - class C[T: [a]](Generic[_A]): ... 96 + class C[T: [a], _A]: ... -97 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF056_RUF056.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF056_RUF056.py.snap index e5b79cbc856cb..ea27183c31a7f 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF056_RUF056.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF056_RUF056.py.snap @@ -12,10 +12,8 @@ RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test posi | help: Remove falsy fallback from `dict.get()` | -116 | # dict.get in ternary expression - - value = "not found" if my_dict.get("key", False) else "default" # [RUF056] +117 - value = "not found" if my_dict.get("key", False) else "default" # [RUF056] 117 + value = "not found" if my_dict.get("key") else "default" # [RUF056] -118 | | RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test positions. The default fallback `None` is already falsy. @@ -28,10 +26,8 @@ RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test posi | help: Remove falsy fallback from `dict.get()` | -119 | # dict.get in an if statement - - if my_dict.get("key", False): # [RUF056] +120 - if my_dict.get("key", False): # [RUF056] 120 + if my_dict.get("key"): # [RUF056] -121 | pass | RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test positions. The default fallback `None` is already falsy. @@ -44,10 +40,8 @@ RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test posi | help: Remove falsy fallback from `dict.get()` | -123 | # dict.get in compound if statement - - if True and my_dict.get("key", False): # [RUF056] +124 - if True and my_dict.get("key", False): # [RUF056] 124 + if True and my_dict.get("key"): # [RUF056] -125 | pass | RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test positions. The default fallback `None` is already falsy. @@ -61,10 +55,8 @@ RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test posi | help: Remove falsy fallback from `dict.get()` | -126 | - - if my_dict.get("key", False) or True: # [RUF056] +127 - if my_dict.get("key", False) or True: # [RUF056] 127 + if my_dict.get("key") or True: # [RUF056] -128 | pass | RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test positions. The default fallback `None` is already falsy. @@ -78,10 +70,8 @@ RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test posi | help: Remove falsy fallback from `dict.get()` | -130 | # dict.get in an assert statement - - assert my_dict.get("key", False) # [RUF056] +131 - assert my_dict.get("key", False) # [RUF056] 131 + assert my_dict.get("key") # [RUF056] -132 | | RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test positions. The default fallback `None` is already falsy. @@ -94,10 +84,8 @@ RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test posi | help: Remove falsy fallback from `dict.get()` | -133 | # dict.get in a while statement - - while my_dict.get("key", False): # [RUF056] +134 - while my_dict.get("key", False): # [RUF056] 134 + while my_dict.get("key"): # [RUF056] -135 | pass | RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test positions. The default fallback `None` is already falsy. @@ -111,10 +99,8 @@ RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test posi | help: Remove falsy fallback from `dict.get()` | -137 | # dict.get in unary not expression - - value = not my_dict.get("key", False) # [RUF056] +138 - value = not my_dict.get("key", False) # [RUF056] 138 + value = not my_dict.get("key") # [RUF056] -139 | | RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test positions. The default fallback `None` is already falsy. @@ -128,10 +114,8 @@ RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test posi | help: Remove falsy fallback from `dict.get()` | -140 | # testing all falsy fallbacks - - value = not my_dict.get("key", False) # [RUF056] +141 - value = not my_dict.get("key", False) # [RUF056] 141 + value = not my_dict.get("key") # [RUF056] -142 | value = not my_dict.get("key", []) # [RUF056] | RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test positions. The default fallback `None` is already falsy. @@ -146,10 +130,8 @@ RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test posi | help: Remove falsy fallback from `dict.get()` | -141 | value = not my_dict.get("key", False) # [RUF056] - - value = not my_dict.get("key", []) # [RUF056] +142 - value = not my_dict.get("key", []) # [RUF056] 142 + value = not my_dict.get("key") # [RUF056] -143 | value = not my_dict.get("key", list()) # [RUF056] | RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test positions. The default fallback `None` is already falsy. @@ -164,10 +146,8 @@ RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test posi | help: Remove falsy fallback from `dict.get()` | -142 | value = not my_dict.get("key", []) # [RUF056] - - value = not my_dict.get("key", list()) # [RUF056] +143 - value = not my_dict.get("key", list()) # [RUF056] 143 + value = not my_dict.get("key") # [RUF056] -144 | value = not my_dict.get("key", {}) # [RUF056] | RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test positions. The default fallback `None` is already falsy. @@ -182,10 +162,8 @@ RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test posi | help: Remove falsy fallback from `dict.get()` | -143 | value = not my_dict.get("key", list()) # [RUF056] - - value = not my_dict.get("key", {}) # [RUF056] +144 - value = not my_dict.get("key", {}) # [RUF056] 144 + value = not my_dict.get("key") # [RUF056] -145 | value = not my_dict.get("key", dict()) # [RUF056] | RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test positions. The default fallback `None` is already falsy. @@ -200,10 +178,8 @@ RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test posi | help: Remove falsy fallback from `dict.get()` | -144 | value = not my_dict.get("key", {}) # [RUF056] - - value = not my_dict.get("key", dict()) # [RUF056] +145 - value = not my_dict.get("key", dict()) # [RUF056] 145 + value = not my_dict.get("key") # [RUF056] -146 | value = not my_dict.get("key", set()) # [RUF056] | RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test positions. The default fallback `None` is already falsy. @@ -218,10 +194,8 @@ RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test posi | help: Remove falsy fallback from `dict.get()` | -145 | value = not my_dict.get("key", dict()) # [RUF056] - - value = not my_dict.get("key", set()) # [RUF056] +146 - value = not my_dict.get("key", set()) # [RUF056] 146 + value = not my_dict.get("key") # [RUF056] -147 | value = not my_dict.get("key", None) # [RUF056] | RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test positions. The default fallback `None` is already falsy. @@ -236,10 +210,8 @@ RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test posi | help: Remove falsy fallback from `dict.get()` | -146 | value = not my_dict.get("key", set()) # [RUF056] - - value = not my_dict.get("key", None) # [RUF056] +147 - value = not my_dict.get("key", None) # [RUF056] 147 + value = not my_dict.get("key") # [RUF056] -148 | value = not my_dict.get("key", 0) # [RUF056] | RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test positions. The default fallback `None` is already falsy. @@ -254,10 +226,8 @@ RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test posi | help: Remove falsy fallback from `dict.get()` | -147 | value = not my_dict.get("key", None) # [RUF056] - - value = not my_dict.get("key", 0) # [RUF056] +148 - value = not my_dict.get("key", 0) # [RUF056] 148 + value = not my_dict.get("key") # [RUF056] -149 | value = not my_dict.get("key", 0.0) # [RUF056] | RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test positions. The default fallback `None` is already falsy. @@ -271,10 +241,8 @@ RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test posi | help: Remove falsy fallback from `dict.get()` | -148 | value = not my_dict.get("key", 0) # [RUF056] - - value = not my_dict.get("key", 0.0) # [RUF056] +149 - value = not my_dict.get("key", 0.0) # [RUF056] 149 + value = not my_dict.get("key") # [RUF056] -150 | value = not my_dict.get("key", "") # [RUF056] | RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test positions. The default fallback `None` is already falsy. @@ -289,10 +257,8 @@ RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test posi | help: Remove falsy fallback from `dict.get()` | -149 | value = not my_dict.get("key", 0.0) # [RUF056] - - value = not my_dict.get("key", "") # [RUF056] +150 - value = not my_dict.get("key", "") # [RUF056] 150 + value = not my_dict.get("key") # [RUF056] -151 | | RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test positions. The default fallback `None` is already falsy. @@ -306,11 +272,9 @@ RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test posi | help: Remove falsy fallback from `dict.get()` | -152 | # testing invalid dict.get call with inline comment - - value = not my_dict.get("key", # comment1 - - [] # comment2 +153 - value = not my_dict.get("key", # comment1 +154 - [] # comment2 153 + value = not my_dict.get("key" # comment2 -154 | ) # [RUF056] | note: This is an unsafe fix and may change runtime behavior @@ -440,7 +404,6 @@ RUF056 [*] Avoid providing a falsy fallback to `dict.get()` in boolean test posi | ^^^^^ help: Remove falsy fallback from `dict.get()` | -190 | d = {} - - not d.get("key", (False)) +191 - not d.get("key", (False)) 191 + not d.get("key") | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF057_RUF057.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF057_RUF057.py.snap index 6cfe46c7360b0..dc47de213132c 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF057_RUF057.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF057_RUF057.py.snap @@ -11,10 +11,8 @@ RUF057 [*] Value being rounded is already an integer | help: Remove unnecessary `round` call | -5 | - - round(42) # Error (safe) +6 - round(42) # Error (safe) 6 + 42 # Error (safe) -7 | round(42, None) # Error (safe) | RUF057 [*] Value being rounded is already an integer @@ -28,10 +26,8 @@ RUF057 [*] Value being rounded is already an integer | help: Remove unnecessary `round` call | -6 | round(42) # Error (safe) - - round(42, None) # Error (safe) +7 - round(42, None) # Error (safe) 7 + 42 # Error (safe) -8 | round(42, 2) # Error (safe) | RUF057 [*] Value being rounded is already an integer @@ -46,10 +42,8 @@ RUF057 [*] Value being rounded is already an integer | help: Remove unnecessary `round` call | -7 | round(42, None) # Error (safe) - - round(42, 2) # Error (safe) +8 - round(42, 2) # Error (safe) 8 + 42 # Error (safe) -9 | round(42, -2) # No error | RUF057 [*] Value being rounded is already an integer @@ -62,10 +56,8 @@ RUF057 [*] Value being rounded is already an integer | help: Remove unnecessary `round` call | -23 | - - round(4 + 2) # Error (safe) +24 - round(4 + 2) # Error (safe) 24 + 4 + 2 # Error (safe) -25 | round(4 + 2, None) # Error (safe) | RUF057 [*] Value being rounded is already an integer @@ -79,10 +71,8 @@ RUF057 [*] Value being rounded is already an integer | help: Remove unnecessary `round` call | -24 | round(4 + 2) # Error (safe) - - round(4 + 2, None) # Error (safe) +25 - round(4 + 2, None) # Error (safe) 25 + 4 + 2 # Error (safe) -26 | round(4 + 2, 2) # Error (safe) | RUF057 [*] Value being rounded is already an integer @@ -97,10 +87,8 @@ RUF057 [*] Value being rounded is already an integer | help: Remove unnecessary `round` call | -25 | round(4 + 2, None) # Error (safe) - - round(4 + 2, 2) # Error (safe) +26 - round(4 + 2, 2) # Error (safe) 26 + 4 + 2 # Error (safe) -27 | round(4 + 2, -2) # No error | RUF057 [*] Value being rounded is already an integer @@ -113,10 +101,8 @@ RUF057 [*] Value being rounded is already an integer | help: Remove unnecessary `round` call | -41 | - - round(inferred_int) # Error (unsafe) +42 - round(inferred_int) # Error (unsafe) 42 + inferred_int # Error (unsafe) -43 | round(inferred_int, None) # Error (unsafe) | note: This is an unsafe fix and may change runtime behavior @@ -131,10 +117,8 @@ RUF057 [*] Value being rounded is already an integer | help: Remove unnecessary `round` call | -42 | round(inferred_int) # Error (unsafe) - - round(inferred_int, None) # Error (unsafe) +43 - round(inferred_int, None) # Error (unsafe) 43 + inferred_int # Error (unsafe) -44 | round(inferred_int, 2) # Error (unsafe) | note: This is an unsafe fix and may change runtime behavior @@ -150,10 +134,8 @@ RUF057 [*] Value being rounded is already an integer | help: Remove unnecessary `round` call | -43 | round(inferred_int, None) # Error (unsafe) - - round(inferred_int, 2) # Error (unsafe) +44 - round(inferred_int, 2) # Error (unsafe) 44 + inferred_int # Error (unsafe) -45 | round(inferred_int, -2) # No error | note: This is an unsafe fix and may change runtime behavior @@ -170,10 +152,8 @@ RUF057 [*] Value being rounded is already an integer | help: Remove unnecessary `round` call | -70 | # See https://github.com/astral-sh/ruff/issues/15598 - - round(- 71 + (- -72 | 1) +72 + 1) | RUF057 [*] Value being rounded is already an integer @@ -190,13 +170,8 @@ RUF057 [*] Value being rounded is already an integer | help: Remove unnecessary `round` call | -72 | 1) - - round(1 - - *1 - - ) 73 + (1 74 + *1) -75 | | RUF057 [*] Value being rounded is already an integer @@ -212,11 +187,10 @@ RUF057 [*] Value being rounded is already an integer | help: Remove unnecessary `round` call | -77 | # fix should be unsafe if comment is in call range - - round(# a comment -78 | 17 - - ) -79 | round( +78 - round(# a comment +79 - 17 +80 - ) +78 + 17 | note: This is an unsafe fix and may change runtime behavior @@ -234,11 +208,9 @@ RUF057 [*] Value being rounded is already an integer | help: Remove unnecessary `round` call | -80 | ) - - round( - - 17 # a comment - - ) +81 - round( +82 - 17 # a comment +83 - ) 81 + 17 -82 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF058_RUF058_0.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF058_RUF058_0.py.snap index ef85a191e3d57..3b5d33e2bab15 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF058_RUF058_0.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF058_RUF058_0.py.snap @@ -12,10 +12,8 @@ RUF058 [*] `itertools.starmap` called on `zip` iterable | help: Use `map` instead | -6 | - - starmap(func, zip()) +7 - starmap(func, zip()) 7 + map(func, []) -8 | starmap(func, zip([])) | RUF058 [*] `itertools.starmap` called on `zip` iterable @@ -26,10 +24,8 @@ RUF058 [*] `itertools.starmap` called on `zip` iterable | ^^^^^^^^^^^^^^^^^^^^^^ help: Use `map` instead | -7 | starmap(func, zip()) - - starmap(func, zip([])) +8 - starmap(func, zip([])) 8 + map(func, []) -9 | | RUF058 [*] `itertools.starmap` called on `zip` iterable @@ -39,10 +35,8 @@ RUF058 [*] `itertools.starmap` called on `zip` iterable | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use `map` instead | -10 | - - starmap(func, zip(a, b, c,),) +11 - starmap(func, zip(a, b, c,),) 11 + map(func, a, b, c,) -12 | | RUF058 [*] `itertools.starmap` called on `zip` iterable @@ -61,17 +55,12 @@ RUF058 [*] `itertools.starmap` called on `zip` iterable | help: Use `map` instead | -13 | - - starmap( -14 + map( +14 ~ map( 15 | func, # Foo - - zip( -16 + [] +16 ~ [] 17 | # Foo 18 | - - ) -19 + -20 | ) +19 ~ | note: This is an unsafe fix and may change runtime behavior @@ -94,18 +83,11 @@ RUF058 [*] `itertools.starmap` called on `zip` iterable | help: Use `map` instead | -21 | - - ( # Foo - - itertools - - ) . starmap ( -22 + map ( +22 ~ map ( 23 | - - func, zip ( -24 + func, +24 ~ func, 25 | a, b, c, - - ), -26 + -27 | ) +26 ~ | note: This is an unsafe fix and may change runtime behavior @@ -139,29 +121,15 @@ RUF058 [*] `itertools.starmap` called on `zip` iterable | help: Use `map` instead | -31 | ( # Foobar - - ( starmap ) -32 + ( map ) +32 ~ ( map ) 33 | # Bazqux 34 | ) \ 35 | (func, - - ( ( - - ( # Zip - - ( - - ( zip - - # Zip - - ) - - ) - - ) - - (a, # A -36 + -37 + a, # A +36 ~ +37 ~ a, # A 38 | b, # B 39 | c, # C - - ) ) - - ), -40 + -41 | ) +40 ~ | note: This is an unsafe fix and may change runtime behavior @@ -183,21 +151,15 @@ RUF058 [*] `itertools.starmap` called on `zip` iterable | |_^ help: Use `map` instead | -50 | - - starmap( -51 + map( +51 ~ map( 52 | func \ 53 | , \ - - zip \ - - ( -54 + \ -55 + +54 ~ \ +55 ~ 56 | a,\ 57 | b,\ 58 | c,\ - - ) -59 + -60 | ) +59 ~ | RUF058 [*] `itertools.starmap` called on `zip` iterable @@ -212,10 +174,8 @@ RUF058 [*] `itertools.starmap` called on `zip` iterable | help: Use `map` instead | -70 | - - starmap(func, zip(a, b, c, strict=True)) +71 - starmap(func, zip(a, b, c, strict=True)) 71 + map(func, a, b, c, strict=True) -72 | starmap(func, zip(a, b, c, strict=False)) | RUF058 [*] `itertools.starmap` called on `zip` iterable @@ -228,10 +188,8 @@ RUF058 [*] `itertools.starmap` called on `zip` iterable | help: Use `map` instead | -71 | starmap(func, zip(a, b, c, strict=True)) - - starmap(func, zip(a, b, c, strict=False)) +72 - starmap(func, zip(a, b, c, strict=False)) 72 + map(func, a, b, c, strict=False) -73 | starmap(func, zip(a, b, c, strict=strict)) | RUF058 [*] `itertools.starmap` called on `zip` iterable @@ -246,8 +204,6 @@ RUF058 [*] `itertools.starmap` called on `zip` iterable | help: Use `map` instead | -72 | starmap(func, zip(a, b, c, strict=False)) - - starmap(func, zip(a, b, c, strict=strict)) +73 - starmap(func, zip(a, b, c, strict=strict)) 73 + map(func, a, b, c, strict=strict) -74 | | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF059_RUF059_0.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF059_RUF059_0.py.snap index 94b7f281dfb55..135284d5d137c 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF059_RUF059_0.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF059_RUF059_0.py.snap @@ -12,11 +12,8 @@ RUF059 [*] Unpacked variable `c` is never used | help: Prefix it with an underscore or any other dummy variable pattern | -23 | bar = (1, 2) - - (c, d) = bar -24 + (_c, d) = bar -25 | - | +24 | (_c, d) = bar + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `d` is never used @@ -30,11 +27,8 @@ RUF059 [*] Unpacked variable `d` is never used | help: Prefix it with an underscore or any other dummy variable pattern | -23 | bar = (1, 2) - - (c, d) = bar -24 + (c, _d) = bar -25 | - | +24 | (c, _d) = bar + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `x` is never used @@ -46,11 +40,8 @@ RUF059 [*] Unpacked variable `x` is never used | ^ help: Prefix it with an underscore or any other dummy variable pattern | -25 | - - (x, y) = baz = bar -26 + (_x, y) = baz = bar -27 | - | +26 | (_x, y) = baz = bar + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `y` is never used @@ -62,11 +53,8 @@ RUF059 [*] Unpacked variable `y` is never used | ^ help: Prefix it with an underscore or any other dummy variable pattern | -25 | - - (x, y) = baz = bar -26 + (x, _y) = baz = bar -27 | - | +26 | (x, _y) = baz = bar + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `connection` is never used @@ -80,11 +68,8 @@ RUF059 [*] Unpacked variable `connection` is never used | help: Prefix it with an underscore or any other dummy variable pattern | -65 | - - with connect() as (connection, cursor): -66 + with connect() as (_connection, cursor): -67 | cursor.execute("SELECT * FROM users") - | +66 | with connect() as (_connection, cursor): + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `connection` is never used @@ -98,11 +83,8 @@ RUF059 [*] Unpacked variable `connection` is never used | help: Prefix it with an underscore or any other dummy variable pattern | -73 | - - with connect() as (connection, cursor): -74 + with connect() as (_connection, cursor): -75 | cursor.execute("SELECT * FROM users") - | +74 | with connect() as (_connection, cursor): + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `this` is never used @@ -115,11 +97,8 @@ RUF059 [*] Unpacked variable `this` is never used | help: Prefix it with an underscore or any other dummy variable pattern | -78 | def f(): - - with open("file") as my_file, open("") as ((this, that)): -79 + with open("file") as my_file, open("") as ((_this, that)): -80 | print("hello") - | +79 | with open("file") as my_file, open("") as ((_this, that)): + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `that` is never used @@ -132,11 +111,8 @@ RUF059 [*] Unpacked variable `that` is never used | help: Prefix it with an underscore or any other dummy variable pattern | -78 | def f(): - - with open("file") as my_file, open("") as ((this, that)): -79 + with open("file") as my_file, open("") as ((this, _that)): -80 | print("hello") - | +79 | with open("file") as my_file, open("") as ((this, _that)): + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `this` is never used @@ -151,11 +127,8 @@ RUF059 [*] Unpacked variable `this` is never used | help: Prefix it with an underscore or any other dummy variable pattern | -85 | open("file") as my_file, - - open("") as ((this, that)), -86 + open("") as ((_this, that)), -87 | ): - | +86 | open("") as ((_this, that)), + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `that` is never used @@ -170,11 +143,8 @@ RUF059 [*] Unpacked variable `that` is never used | help: Prefix it with an underscore or any other dummy variable pattern | -85 | open("file") as my_file, - - open("") as ((this, that)), -86 + open("") as ((this, _that)), -87 | ): - | +86 | open("") as ((this, _that)), + | + note: This is an unsafe fix and may change runtime behavior RUF059 Unpacked variable `x` is never used diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF059_RUF059_1.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF059_RUF059_1.py.snap index 487818493187a..6e5d4f0530010 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF059_RUF059_1.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF059_RUF059_1.py.snap @@ -9,11 +9,8 @@ RUF059 [*] Unpacked variable `x` is never used | ^ help: Prefix it with an underscore or any other dummy variable pattern | -1 | def f(tup): - - x, y = tup -2 + _x, y = tup -3 | - | +2 | _x, y = tup + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `y` is never used @@ -24,11 +21,8 @@ RUF059 [*] Unpacked variable `y` is never used | ^ help: Prefix it with an underscore or any other dummy variable pattern | -1 | def f(tup): - - x, y = tup -2 + x, _y = tup -3 | - | +2 | x, _y = tup + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `y` is never used @@ -42,11 +36,8 @@ RUF059 [*] Unpacked variable `y` is never used | help: Prefix it with an underscore or any other dummy variable pattern | -9 | def f(): - - (x, y) = coords = 1, 2 -10 + (x, _y) = coords = 1, 2 -11 | if x > 1: - | +10 | (x, _y) = coords = 1, 2 + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `x` is never used @@ -57,11 +48,8 @@ RUF059 [*] Unpacked variable `x` is never used | ^ help: Prefix it with an underscore or any other dummy variable pattern | -15 | def f(): - - (x, y) = coords = 1, 2 -16 + (_x, y) = coords = 1, 2 -17 | - | +16 | (_x, y) = coords = 1, 2 + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `y` is never used @@ -72,11 +60,8 @@ RUF059 [*] Unpacked variable `y` is never used | ^ help: Prefix it with an underscore or any other dummy variable pattern | -15 | def f(): - - (x, y) = coords = 1, 2 -16 + (x, _y) = coords = 1, 2 -17 | - | +16 | (x, _y) = coords = 1, 2 + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `x` is never used @@ -87,11 +72,8 @@ RUF059 [*] Unpacked variable `x` is never used | ^ help: Prefix it with an underscore or any other dummy variable pattern | -19 | def f(): - - coords = (x, y) = 1, 2 -20 + coords = (_x, y) = 1, 2 -21 | - | +20 | coords = (_x, y) = 1, 2 + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `y` is never used @@ -102,9 +84,6 @@ RUF059 [*] Unpacked variable `y` is never used | ^ help: Prefix it with an underscore or any other dummy variable pattern | -19 | def f(): - - coords = (x, y) = 1, 2 -20 + coords = (x, _y) = 1, 2 -21 | - | +20 | coords = (x, _y) = 1, 2 + | + note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF059_RUF059_2.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF059_RUF059_2.py.snap index 02a790a6f2945..ea8189129edde 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF059_RUF059_2.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF059_RUF059_2.py.snap @@ -12,11 +12,8 @@ RUF059 [*] Unpacked variable `x2` is never used | help: Prefix it with an underscore or any other dummy variable pattern | -7 | - - with foo() as (x2, y2): -8 + with foo() as (_x2, y2): -9 | pass - | +8 | with foo() as (_x2, y2): + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `y2` is never used @@ -30,11 +27,8 @@ RUF059 [*] Unpacked variable `y2` is never used | help: Prefix it with an underscore or any other dummy variable pattern | -7 | - - with foo() as (x2, y2): -8 + with foo() as (x2, _y2): -9 | pass - | +8 | with foo() as (x2, _y2): + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `x2` is never used @@ -48,11 +42,8 @@ RUF059 [*] Unpacked variable `x2` is never used | help: Prefix it with an underscore or any other dummy variable pattern | -16 | (x1, y1) = (1, 2) - - (x2, y2) = coords2 = (1, 2) -17 + (_x2, y2) = coords2 = (1, 2) -18 | coords3 = (x3, y3) = (1, 2) - | +17 | (_x2, y2) = coords2 = (1, 2) + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `y2` is never used @@ -66,11 +57,8 @@ RUF059 [*] Unpacked variable `y2` is never used | help: Prefix it with an underscore or any other dummy variable pattern | -16 | (x1, y1) = (1, 2) - - (x2, y2) = coords2 = (1, 2) -17 + (x2, _y2) = coords2 = (1, 2) -18 | coords3 = (x3, y3) = (1, 2) - | +17 | (x2, _y2) = coords2 = (1, 2) + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `x3` is never used @@ -82,11 +70,8 @@ RUF059 [*] Unpacked variable `x3` is never used | ^^ help: Prefix it with an underscore or any other dummy variable pattern | -17 | (x2, y2) = coords2 = (1, 2) - - coords3 = (x3, y3) = (1, 2) -18 + coords3 = (_x3, y3) = (1, 2) -19 | - | +18 | coords3 = (_x3, y3) = (1, 2) + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `y3` is never used @@ -98,11 +83,8 @@ RUF059 [*] Unpacked variable `y3` is never used | ^^ help: Prefix it with an underscore or any other dummy variable pattern | -17 | (x2, y2) = coords2 = (1, 2) - - coords3 = (x3, y3) = (1, 2) -18 + coords3 = (x3, _y3) = (1, 2) -19 | - | +18 | coords3 = (x3, _y3) = (1, 2) + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `x` is never used @@ -115,11 +97,8 @@ RUF059 [*] Unpacked variable `x` is never used | help: Prefix it with an underscore or any other dummy variable pattern | -21 | def f(): - - with Nested(m) as (x, y): -22 + with Nested(m) as (_x, y): -23 | pass - | +22 | with Nested(m) as (_x, y): + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `y` is never used @@ -132,11 +111,8 @@ RUF059 [*] Unpacked variable `y` is never used | help: Prefix it with an underscore or any other dummy variable pattern | -21 | def f(): - - with Nested(m) as (x, y): -22 + with Nested(m) as (x, _y): -23 | pass - | +22 | with Nested(m) as (x, _y): + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `a` is never used @@ -147,11 +123,8 @@ RUF059 [*] Unpacked variable `a` is never used | ^ help: Prefix it with an underscore or any other dummy variable pattern | -26 | def f(): - - toplevel = (a, b) = lexer.get_token() -27 + toplevel = (_a, b) = lexer.get_token() -28 | - | +27 | toplevel = (_a, b) = lexer.get_token() + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `b` is never used @@ -162,11 +135,8 @@ RUF059 [*] Unpacked variable `b` is never used | ^ help: Prefix it with an underscore or any other dummy variable pattern | -26 | def f(): - - toplevel = (a, b) = lexer.get_token() -27 + toplevel = (a, _b) = lexer.get_token() -28 | - | +27 | toplevel = (a, _b) = lexer.get_token() + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `a` is never used @@ -177,10 +147,8 @@ RUF059 [*] Unpacked variable `a` is never used | ^ help: Prefix it with an underscore or any other dummy variable pattern | -30 | def f(): - - (a, b) = toplevel = lexer.get_token() -31 + (_a, b) = toplevel = lexer.get_token() - | +31 | (_a, b) = toplevel = lexer.get_token() + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `b` is never used @@ -191,8 +159,6 @@ RUF059 [*] Unpacked variable `b` is never used | ^ help: Prefix it with an underscore or any other dummy variable pattern | -30 | def f(): - - (a, b) = toplevel = lexer.get_token() -31 + (a, _b) = toplevel = lexer.get_token() - | +31 | (a, _b) = toplevel = lexer.get_token() + | + note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF059_RUF059_3.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF059_RUF059_3.py.snap index 9897ceafd1f8d..765bfd6d8d9e0 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF059_RUF059_3.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF059_RUF059_3.py.snap @@ -10,11 +10,8 @@ RUF059 [*] Unpacked variable `b` is never used | ^ help: Prefix it with an underscore or any other dummy variable pattern | -12 | a = foo() - - b, c = foo() -13 + _b, c = foo() -14 | - | +13 | _b, c = foo() + | + note: This is an unsafe fix and may change runtime behavior RUF059 [*] Unpacked variable `c` is never used @@ -26,9 +23,6 @@ RUF059 [*] Unpacked variable `c` is never used | ^ help: Prefix it with an underscore or any other dummy variable pattern | -12 | a = foo() - - b, c = foo() -13 + b, _c = foo() -14 | - | +13 | b, _c = foo() + | + note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF061_RUF061_deprecated_call.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF061_RUF061_deprecated_call.py.snap index e55888ceaf029..bc46f9fade785 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF061_RUF061_deprecated_call.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF061_RUF061_deprecated_call.py.snap @@ -9,11 +9,8 @@ RUF061 [*] Use context-manager form of `pytest.deprecated_call()` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use `pytest.deprecated_call()` as a context-manager | -15 | def test_error_trivial(): - - pytest.deprecated_call(raise_deprecation_warning, "deprecated") -16 + with pytest.deprecated_call(): +16 ~ with pytest.deprecated_call(): 17 + raise_deprecation_warning("deprecated") -18 | | note: This is an unsafe fix and may change runtime behavior @@ -27,11 +24,8 @@ RUF061 [*] Use context-manager form of `pytest.deprecated_call()` | help: Use `pytest.deprecated_call()` as a context-manager | -19 | def test_error_assign(): - - s = pytest.deprecated_call(raise_deprecation_warning, "deprecated") -20 + with pytest.deprecated_call(): +20 ~ with pytest.deprecated_call(): 21 + s = raise_deprecation_warning("deprecated") -22 | print(s) | note: This is an unsafe fix and may change runtime behavior @@ -43,9 +37,7 @@ RUF061 [*] Use context-manager form of `pytest.deprecated_call()` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use `pytest.deprecated_call()` as a context-manager | -24 | def test_error_lambda(): - - pytest.deprecated_call(lambda: warnings.warn("", DeprecationWarning)) -25 + with pytest.deprecated_call(): +25 ~ with pytest.deprecated_call(): 26 + (lambda: warnings.warn("", DeprecationWarning))() | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF061_RUF061_raises.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF061_RUF061_raises.py.snap index 64e072723cf95..2703680fea626 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF061_RUF061_raises.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF061_RUF061_raises.py.snap @@ -9,11 +9,8 @@ RUF061 [*] Use context-manager form of `pytest.raises()` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use `pytest.raises()` as a context-manager | -18 | def test_error_trivial(): - - pytest.raises(ZeroDivisionError, func, 1, b=0) -19 + with pytest.raises(ZeroDivisionError): +19 ~ with pytest.raises(ZeroDivisionError): 20 + func(1, b=0) -21 | | note: This is an unsafe fix and may change runtime behavior @@ -25,11 +22,8 @@ RUF061 [*] Use context-manager form of `pytest.raises()` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use `pytest.raises()` as a context-manager | -22 | def test_error_match(): - - pytest.raises(ZeroDivisionError, func, 1, b=0).match("division by zero") -23 + with pytest.raises(ZeroDivisionError, match="division by zero"): +23 ~ with pytest.raises(ZeroDivisionError, match="division by zero"): 24 + func(1, b=0) -25 | | note: This is an unsafe fix and may change runtime behavior @@ -41,11 +35,8 @@ RUF061 [*] Use context-manager form of `pytest.raises()` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use `pytest.raises()` as a context-manager | -26 | def test_error_assign(): - - excinfo = pytest.raises(ZeroDivisionError, func, 1, b=0) -27 + with pytest.raises(ZeroDivisionError) as excinfo: +27 ~ with pytest.raises(ZeroDivisionError) as excinfo: 28 + func(1, b=0) -29 | | note: This is an unsafe fix and may change runtime behavior @@ -57,11 +48,8 @@ RUF061 [*] Use context-manager form of `pytest.raises()` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use `pytest.raises()` as a context-manager | -30 | def test_error_kwargs(): - - pytest.raises(func=func, expected_exception=ZeroDivisionError) -31 + with pytest.raises(ZeroDivisionError): +31 ~ with pytest.raises(ZeroDivisionError): 32 + func() -33 | | note: This is an unsafe fix and may change runtime behavior @@ -75,11 +63,8 @@ RUF061 [*] Use context-manager form of `pytest.raises()` | help: Use `pytest.raises()` as a context-manager | -34 | def test_error_multi_statement(): - - excinfo = pytest.raises(ValueError, int, "hello") -35 + with pytest.raises(ValueError) as excinfo: +35 ~ with pytest.raises(ValueError) as excinfo: 36 + int("hello") -37 | assert excinfo.match("^invalid literal") | note: This is an unsafe fix and may change runtime behavior @@ -91,9 +76,7 @@ RUF061 [*] Use context-manager form of `pytest.raises()` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use `pytest.raises()` as a context-manager | -39 | def test_error_lambda(): - - pytest.raises(ZeroDivisionError, lambda: 1 / 0) -40 + with pytest.raises(ZeroDivisionError): +40 ~ with pytest.raises(ZeroDivisionError): 41 + (lambda: 1 / 0)() | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF061_RUF061_warns.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF061_RUF061_warns.py.snap index 36dbf41a5fc06..2f1645e1adfa1 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF061_RUF061_warns.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF061_RUF061_warns.py.snap @@ -9,11 +9,8 @@ RUF061 [*] Use context-manager form of `pytest.warns()` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use `pytest.warns()` as a context-manager | -15 | def test_error_trivial(): - - pytest.warns(UserWarning, raise_user_warning, "warning") -16 + with pytest.warns(UserWarning): +16 ~ with pytest.warns(UserWarning): 17 + raise_user_warning("warning") -18 | | note: This is an unsafe fix and may change runtime behavior @@ -27,11 +24,8 @@ RUF061 [*] Use context-manager form of `pytest.warns()` | help: Use `pytest.warns()` as a context-manager | -19 | def test_error_assign(): - - s = pytest.warns(UserWarning, raise_user_warning, "warning") -20 + with pytest.warns(UserWarning): +20 ~ with pytest.warns(UserWarning): 21 + s = raise_user_warning("warning") -22 | print(s) | note: This is an unsafe fix and may change runtime behavior @@ -43,9 +37,7 @@ RUF061 [*] Use context-manager form of `pytest.warns()` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use `pytest.warns()` as a context-manager | -24 | def test_error_lambda(): - - pytest.warns(UserWarning, lambda: warnings.warn("", UserWarning)) -25 + with pytest.warns(UserWarning): +25 ~ with pytest.warns(UserWarning): 26 + (lambda: warnings.warn("", UserWarning))() | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF064_RUF064.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF064_RUF064.py.snap index 07ed2a5d32b9d..2a82c3da9bc65 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF064_RUF064.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF064_RUF064.py.snap @@ -15,11 +15,8 @@ info: Current value of 444 (0o674) sets permissions: u=rw-, g=rwx, o=r-- info: Suggested value of 0o444 sets permissions: u=r--, g=r--, o=r-- help: Replace with octal literal | -5 | - - os.chmod("foo", 444) # Error -6 + os.chmod("foo", 0o444) # Error -7 | os.chmod("foo", 0o444) # OK - | +6 | os.chmod("foo", 0o444) # Error + | ++ note: This is an unsafe fix and may change runtime behavior RUF064 Non-octal mode @@ -72,11 +69,8 @@ info: Current value of 777 (0o1411) sets permissions: u=r--, g=--x, o=--x info: Suggested value of 0o777 sets permissions: u=rwx, g=rwx, o=rwx help: Replace with octal literal | -11 | - - os.umask(777) # Error -12 + os.umask(0o777) # Error -13 | os.umask(0o777) # OK - | +12 | os.umask(0o777) # Error + | ++ note: This is an unsafe fix and may change runtime behavior RUF064 [*] Non-octal mode @@ -92,11 +86,8 @@ info: Current value of 400 (0o620) sets permissions: u=rw-, g=-w-, o=--- info: Suggested value of 0o400 sets permissions: u=r--, g=---, o=--- help: Replace with octal literal | -14 | - - os.fchmod(0, 400) # Error -15 + os.fchmod(0, 0o400) # Error -16 | os.fchmod(0, 0o400) # OK - | +15 | os.fchmod(0, 0o400) # Error + | ++ note: This is an unsafe fix and may change runtime behavior RUF064 [*] Non-octal mode @@ -112,11 +103,8 @@ info: Current value of 755 (0o1363) sets permissions: u=-wx, g=rw-, o=-wx info: Suggested value of 0o755 sets permissions: u=rwx, g=r-x, o=r-x help: Replace with octal literal | -17 | - - os.lchmod("foo", 755) # Error -18 + os.lchmod("foo", 0o755) # Error -19 | os.lchmod("foo", 0o755) # OK - | +18 | os.lchmod("foo", 0o755) # Error + | ++ note: This is an unsafe fix and may change runtime behavior RUF064 [*] Non-octal mode @@ -132,11 +120,8 @@ info: Current value of 600 (0o1130) sets permissions: u=--x, g=-wx, o=--- info: Suggested value of 0o600 sets permissions: u=rw-, g=---, o=--- help: Replace with octal literal | -20 | - - os.mkdir("foo", 600) # Error -21 + os.mkdir("foo", 0o600) # Error -22 | os.mkdir("foo", 0o600) # OK - | +21 | os.mkdir("foo", 0o600) # Error + | ++ note: This is an unsafe fix and may change runtime behavior RUF064 [*] Non-octal mode @@ -152,11 +137,8 @@ info: Current value of 644 (0o1204) sets permissions: u=-w-, g=---, o=r-- info: Suggested value of 0o644 sets permissions: u=rw-, g=r--, o=r-- help: Replace with octal literal | -23 | - - os.makedirs("foo", 644) # Error -24 + os.makedirs("foo", 0o644) # Error -25 | os.makedirs("foo", 0o644) # OK - | +24 | os.makedirs("foo", 0o644) # Error + | ++ note: This is an unsafe fix and may change runtime behavior RUF064 [*] Non-octal mode @@ -172,11 +154,8 @@ info: Current value of 640 (0o1200) sets permissions: u=-w-, g=---, o=--- info: Suggested value of 0o640 sets permissions: u=rw-, g=r--, o=--- help: Replace with octal literal | -26 | - - os.mkfifo("foo", 640) # Error -27 + os.mkfifo("foo", 0o640) # Error -28 | os.mkfifo("foo", 0o640) # OK - | +27 | os.mkfifo("foo", 0o640) # Error + | ++ note: This is an unsafe fix and may change runtime behavior RUF064 [*] Non-octal mode @@ -192,11 +171,8 @@ info: Current value of 660 (0o1224) sets permissions: u=-w-, g=-w-, o=r-- info: Suggested value of 0o660 sets permissions: u=rw-, g=rw-, o=--- help: Replace with octal literal | -29 | - - os.mknod("foo", 660) # Error -30 + os.mknod("foo", 0o660) # Error -31 | os.mknod("foo", 0o660) # OK - | +30 | os.mknod("foo", 0o660) # Error + | ++ note: This is an unsafe fix and may change runtime behavior RUF064 [*] Non-octal mode @@ -212,11 +188,8 @@ info: Current value of 644 (0o1204) sets permissions: u=-w-, g=---, o=r-- info: Suggested value of 0o644 sets permissions: u=rw-, g=r--, o=r-- help: Replace with octal literal | -32 | - - os.open("foo", os.O_CREAT, 644) # Error -33 + os.open("foo", os.O_CREAT, 0o644) # Error -34 | os.open("foo", os.O_CREAT, 0o644) # OK - | +33 | os.open("foo", os.O_CREAT, 0o644) # Error + | ++ note: This is an unsafe fix and may change runtime behavior RUF064 [*] Non-octal mode @@ -232,11 +205,8 @@ info: Current value of 755 (0o1363) sets permissions: u=-wx, g=rw-, o=-wx info: Suggested value of 0o755 sets permissions: u=rwx, g=r-x, o=r-x help: Replace with octal literal | -35 | - - Path("bar").chmod(755) # Error -36 + Path("bar").chmod(0o755) # Error -37 | Path("bar").chmod(0o755) # OK - | +36 | Path("bar").chmod(0o755) # Error + | ++ note: This is an unsafe fix and may change runtime behavior RUF064 [*] Non-octal mode @@ -251,11 +221,8 @@ info: Current value of 755 (0o1363) sets permissions: u=-wx, g=rw-, o=-wx info: Suggested value of 0o755 sets permissions: u=rwx, g=r-x, o=r-x help: Replace with octal literal | -39 | path = Path("bar") - - path.chmod(755) # Error -40 + path.chmod(0o755) # Error -41 | path.chmod(0o755) # OK - | +40 | path.chmod(0o755) # Error + | ++ note: This is an unsafe fix and may change runtime behavior RUF064 [*] Non-octal mode @@ -271,11 +238,8 @@ info: Current value of 600 (0o1130) sets permissions: u=--x, g=-wx, o=--- info: Suggested value of 0o600 sets permissions: u=rw-, g=---, o=--- help: Replace with octal literal | -42 | - - dbm.open("db", "r", 600) # Error -43 + dbm.open("db", "r", 0o600) # Error -44 | dbm.open("db", "r", 0o600) # OK - | +43 | dbm.open("db", "r", 0o600) # Error + | ++ note: This is an unsafe fix and may change runtime behavior RUF064 [*] Non-octal mode @@ -291,11 +255,8 @@ info: Current value of 600 (0o1130) sets permissions: u=--x, g=-wx, o=--- info: Suggested value of 0o600 sets permissions: u=rw-, g=---, o=--- help: Replace with octal literal | -45 | - - dbm.gnu.open("db", "r", 600) # Error -46 + dbm.gnu.open("db", "r", 0o600) # Error -47 | dbm.gnu.open("db", "r", 0o600) # OK - | +46 | dbm.gnu.open("db", "r", 0o600) # Error + | ++ note: This is an unsafe fix and may change runtime behavior RUF064 [*] Non-octal mode @@ -311,11 +272,8 @@ info: Current value of 600 (0o1130) sets permissions: u=--x, g=-wx, o=--- info: Suggested value of 0o600 sets permissions: u=rw-, g=---, o=--- help: Replace with octal literal | -48 | - - dbm.ndbm.open("db", "r", 600) # Error -49 + dbm.ndbm.open("db", "r", 0o600) # Error -50 | dbm.ndbm.open("db", "r", 0o600) # OK - | +49 | dbm.ndbm.open("db", "r", 0o600) # Error + | ++ note: This is an unsafe fix and may change runtime behavior RUF064 [*] Non-octal mode @@ -331,10 +289,8 @@ info: Current value of 256 (0o400) sets permissions: u=r--, g=---, o=--- info: Suggested value of 0o400 sets permissions: u=r--, g=---, o=--- help: Replace with octal literal | -51 | - - os.fchmod(0, 256) # 0o400 +52 - os.fchmod(0, 256) # 0o400 52 + os.fchmod(0, 0o400) # 0o400 -53 | os.fchmod(0, 493) # 0o755 | note: This is an unsafe fix and may change runtime behavior @@ -351,10 +307,8 @@ info: Current value of 493 (0o755) sets permissions: u=rwx, g=r-x, o=r-x info: Suggested value of 0o755 sets permissions: u=rwx, g=r-x, o=r-x help: Replace with octal literal | -52 | os.fchmod(0, 256) # 0o400 - - os.fchmod(0, 493) # 0o755 +53 - os.fchmod(0, 493) # 0o755 53 + os.fchmod(0, 0o755) # 0o755 -54 | | note: This is an unsafe fix and may change runtime behavior @@ -369,11 +323,8 @@ RUF064 [*] Non-octal mode info: Current value of 000 (0o000) sets permissions: u=---, g=---, o=--- help: Replace with octal literal | -55 | # https://github.com/astral-sh/ruff/issues/19010 - - os.chmod("foo", 000) # Error -56 + os.chmod("foo", 0o000) # Error -57 | os.chmod("foo", 0000) # Error - | +56 | os.chmod("foo", 0o000) # Error + | ++ RUF064 [*] Non-octal mode --> RUF064.py:57:17 @@ -388,11 +339,8 @@ RUF064 [*] Non-octal mode info: Current value of 0000 (0o000) sets permissions: u=---, g=---, o=--- help: Replace with octal literal | -56 | os.chmod("foo", 000) # Error - - os.chmod("foo", 0000) # Error -57 + os.chmod("foo", 0o0000) # Error -58 | - | +57 | os.chmod("foo", 0o0000) # Error + | ++ RUF064 Non-octal mode --> RUF064.py:59:17 diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF068_RUF068.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF068_RUF068.py.snap index a93caed1c4ec9..bb611a49e54d9 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF068_RUF068.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF068_RUF068.py.snap @@ -15,10 +15,8 @@ RUF068 [*] `__all__` contains duplicate entries | help: Remove duplicate entries from `__all__` | -14 | __all__ = ["A", "B"] - - __all__ = [A, "B", "B"] +15 - __all__ = [A, "B", "B"] 15 + __all__ = [A, "B"] -16 | __all__ += ["A", "B"] | RUF068 [*] `__all__` contains duplicate entries @@ -34,10 +32,8 @@ RUF068 [*] `__all__` contains duplicate entries | help: Remove duplicate entries from `__all__` | -19 | # Bad - - __all__: list[str] = ["A", "B", "A"] +20 - __all__: list[str] = ["A", "B", "A"] 20 + __all__: list[str] = ["A", "B"] -21 | __all__: typing.Any = ("A", "B", "B") | RUF068 [*] `__all__` contains duplicate entries @@ -54,10 +50,8 @@ RUF068 [*] `__all__` contains duplicate entries | help: Remove duplicate entries from `__all__` | -20 | __all__: list[str] = ["A", "B", "A"] - - __all__: typing.Any = ("A", "B", "B") +21 - __all__: typing.Any = ("A", "B", "B") 21 + __all__: typing.Any = ("A", "B") -22 | __all__ = ["A", "B", "A"] | RUF068 [*] `__all__` contains duplicate entries @@ -74,10 +68,8 @@ RUF068 [*] `__all__` contains duplicate entries | help: Remove duplicate entries from `__all__` | -21 | __all__: typing.Any = ("A", "B", "B") - - __all__ = ["A", "B", "A"] +22 - __all__ = ["A", "B", "A"] 22 + __all__ = ["A", "B"] -23 | __all__ = ["A", "A", "B", "B"] | RUF068 [*] `__all__` contains duplicate entries @@ -94,10 +86,8 @@ RUF068 [*] `__all__` contains duplicate entries | help: Remove duplicate entries from `__all__` | -22 | __all__ = ["A", "B", "A"] - - __all__ = ["A", "A", "B", "B"] +23 - __all__ = ["A", "A", "B", "B"] 23 + __all__ = ["A", "B", "B"] -24 | __all__ = [ | RUF068 [*] `__all__` contains duplicate entries @@ -114,10 +104,8 @@ RUF068 [*] `__all__` contains duplicate entries | help: Remove duplicate entries from `__all__` | -22 | __all__ = ["A", "B", "A"] - - __all__ = ["A", "A", "B", "B"] +23 - __all__ = ["A", "A", "B", "B"] 23 + __all__ = ["A", "A", "B"] -24 | __all__ = [ | RUF068 [*] `__all__` contains duplicate entries @@ -134,9 +122,7 @@ RUF068 [*] `__all__` contains duplicate entries | help: Remove duplicate entries from `__all__` | -25 | "A", - - "A", -26 | "B", +26 - "A", | RUF068 [*] `__all__` contains duplicate entries @@ -153,9 +139,7 @@ RUF068 [*] `__all__` contains duplicate entries | help: Remove duplicate entries from `__all__` | -26 | "A", - - "B", -27 | "B" +27 - "B", | RUF068 [*] `__all__` contains duplicate entries @@ -171,10 +155,8 @@ RUF068 [*] `__all__` contains duplicate entries | help: Remove duplicate entries from `__all__` | -29 | ] - - __all__ += ["B", "B"] +30 - __all__ += ["B", "B"] 30 + __all__ += ["B"] -31 | __all__.extend(["B", "B"]) | RUF068 [*] `__all__` contains duplicate entries @@ -191,10 +173,8 @@ RUF068 [*] `__all__` contains duplicate entries | help: Remove duplicate entries from `__all__` | -30 | __all__ += ["B", "B"] - - __all__.extend(["B", "B"]) +31 - __all__.extend(["B", "B"]) 31 + __all__.extend(["B"]) -32 | | RUF068 [*] `__all__` contains duplicate entries @@ -211,9 +191,7 @@ RUF068 [*] `__all__` contains duplicate entries | help: Remove duplicate entries from `__all__` | -35 | "A", - - "A", -36 | "B", +36 - "A", | RUF068 [*] `__all__` contains duplicate entries @@ -231,9 +209,7 @@ RUF068 [*] `__all__` contains duplicate entries | help: Remove duplicate entries from `__all__` | -36 | "A", - - "B", - - # Comment -37 | "B", # 2 +37 - "B", +38 - # Comment | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF101_RUF101_0.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF101_RUF101_0.py.snap index 2a62da7cde862..0083ea2e0b2e7 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF101_RUF101_0.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF101_RUF101_0.py.snap @@ -11,10 +11,8 @@ RUF101 [*] `RUF940` is a redirect to `RUF950` | help: Replace with `RUF950` | - - x = 2 # noqa: RUF940 -1 | x = 2 # noqa: RUF950 -2 + x = 2 # noqa: RUF950 -3 | x = 2 # noqa: RUF940, RUF950 +1 - x = 2 # noqa: RUF940 +1 + x = 2 # noqa: RUF950 | RUF101 [*] `RUF940` is a redirect to `RUF950` @@ -29,10 +27,8 @@ RUF101 [*] `RUF940` is a redirect to `RUF950` | help: Replace with `RUF950` | -2 | x = 2 # noqa: RUF950 - - x = 2 # noqa: RUF940, RUF950 +3 - x = 2 # noqa: RUF940, RUF950 3 + x = 2 # noqa: RUF950, RUF950 -4 | x = 2 # noqa: RUF950, RUF940, RUF950, RUF950, RUF950 | RUF101 [*] `RUF940` is a redirect to `RUF950` @@ -47,10 +43,8 @@ RUF101 [*] `RUF940` is a redirect to `RUF950` | help: Replace with `RUF950` | -3 | x = 2 # noqa: RUF940, RUF950 - - x = 2 # noqa: RUF950, RUF940, RUF950, RUF950, RUF950 +4 - x = 2 # noqa: RUF950, RUF940, RUF950, RUF950, RUF950 4 + x = 2 # noqa: RUF950, RUF950, RUF950, RUF950, RUF950 -5 | x = 2 # noqa: RUF940, RUF950, RUF940 | RUF101 [*] `RUF940` is a redirect to `RUF950` @@ -64,10 +58,8 @@ RUF101 [*] `RUF940` is a redirect to `RUF950` | help: Replace with `RUF950` | -4 | x = 2 # noqa: RUF950, RUF940, RUF950, RUF950, RUF950 - - x = 2 # noqa: RUF940, RUF950, RUF940 +5 - x = 2 # noqa: RUF940, RUF950, RUF940 5 + x = 2 # noqa: RUF950, RUF950, RUF940 -6 | x = 2 # noqa: RUF940, RUF950, RUF940, RUF950 | RUF101 [*] `RUF940` is a redirect to `RUF950` @@ -81,10 +73,8 @@ RUF101 [*] `RUF940` is a redirect to `RUF950` | help: Replace with `RUF950` | -4 | x = 2 # noqa: RUF950, RUF940, RUF950, RUF950, RUF950 - - x = 2 # noqa: RUF940, RUF950, RUF940 +5 - x = 2 # noqa: RUF940, RUF950, RUF940 5 + x = 2 # noqa: RUF940, RUF950, RUF950 -6 | x = 2 # noqa: RUF940, RUF950, RUF940, RUF950 | RUF101 [*] `RUF940` is a redirect to `RUF950` @@ -96,8 +86,7 @@ RUF101 [*] `RUF940` is a redirect to `RUF950` | ^^^^^^ help: Replace with `RUF950` | -5 | x = 2 # noqa: RUF940, RUF950, RUF940 - - x = 2 # noqa: RUF940, RUF950, RUF940, RUF950 +6 - x = 2 # noqa: RUF940, RUF950, RUF940, RUF950 6 + x = 2 # noqa: RUF950, RUF950, RUF940, RUF950 | @@ -110,7 +99,6 @@ RUF101 [*] `RUF940` is a redirect to `RUF950` | ^^^^^^ help: Replace with `RUF950` | -5 | x = 2 # noqa: RUF940, RUF950, RUF940 - - x = 2 # noqa: RUF940, RUF950, RUF940, RUF950 +6 - x = 2 # noqa: RUF940, RUF950, RUF940, RUF950 6 + x = 2 # noqa: RUF940, RUF950, RUF950, RUF950 | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF101_RUF101_1.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF101_RUF101_1.py.snap index 8ceb73ae953ba..fdd4ea050415a 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF101_RUF101_1.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF101_RUF101_1.py.snap @@ -13,8 +13,6 @@ RUF101 [*] `TCH002` is a redirect to `TC002` | help: Replace with `TC002` | -4 | """ - - # ruff: noqa: TCH002 +5 - # ruff: noqa: TCH002 5 + # ruff: noqa: TC002 -6 | | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF102_RUF102.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF102_RUF102.py.snap index 1f70be69ba4ef..1fc4d9e585c47 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF102_RUF102.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF102_RUF102.py.snap @@ -13,10 +13,8 @@ RUF102 [*] Invalid rule code in `# noqa`: INVALID123 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the `# noqa` comment | -1 | # Invalid code - - import os # noqa: INVALID123 +2 - import os # noqa: INVALID123 2 + import os -3 | # External code | RUF102 [*] Invalid rule code in `# noqa`: V123 @@ -32,10 +30,8 @@ RUF102 [*] Invalid rule code in `# noqa`: V123 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the `# noqa` comment | -3 | # External code - - import re # noqa: V123 +4 - import re # noqa: V123 4 + import re -5 | # Valid noqa | RUF102 [*] Invalid rule code in `# noqa`: INVALID456 @@ -51,10 +47,8 @@ RUF102 [*] Invalid rule code in `# noqa`: INVALID456 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the rule code `INVALID456` | -6 | import sys # noqa: E402 - - from functools import cache # Preceeding comment # noqa: F401, INVALID456 +7 - from functools import cache # Preceeding comment # noqa: F401, INVALID456 7 + from functools import cache # Preceeding comment # noqa: F401 -8 | from itertools import product # Preceeding comment # noqa: INVALID789 | RUF102 [*] Invalid rule code in `# noqa`: INVALID789 @@ -70,10 +64,8 @@ RUF102 [*] Invalid rule code in `# noqa`: INVALID789 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the `# noqa` comment | -7 | from functools import cache # Preceeding comment # noqa: F401, INVALID456 - - from itertools import product # Preceeding comment # noqa: INVALID789 +8 - from itertools import product # Preceeding comment # noqa: INVALID789 8 + from itertools import product # Preceeding comment -9 | # Succeeding comment | RUF102 [*] Invalid rule code in `# noqa`: INVALID000 @@ -89,10 +81,8 @@ RUF102 [*] Invalid rule code in `# noqa`: INVALID000 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the `# noqa` comment | -9 | # Succeeding comment - - import math # noqa: INVALID000 # Succeeding comment +10 - import math # noqa: INVALID000 # Succeeding comment 10 + import math # Succeeding comment -11 | # Mixed valid and invalid | RUF102 [*] Invalid rule code in `# noqa`: INVALID123 @@ -108,10 +98,8 @@ RUF102 [*] Invalid rule code in `# noqa`: INVALID123 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the rule code `INVALID123` | -11 | # Mixed valid and invalid - - from typing import List # noqa: F401, INVALID123 +12 - from typing import List # noqa: F401, INVALID123 12 + from typing import List # noqa: F401 -13 | # Test for multiple invalid | RUF102 [*] Invalid rule code in `# noqa`: INVALID100 @@ -127,10 +115,8 @@ RUF102 [*] Invalid rule code in `# noqa`: INVALID100 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the rule code `INVALID100` | -13 | # Test for multiple invalid - - from collections import defaultdict # noqa: INVALID100, INVALID200, F401 +14 - from collections import defaultdict # noqa: INVALID100, INVALID200, F401 14 + from collections import defaultdict # noqa: INVALID200, F401 -15 | # Test for preserving valid codes when fixing | RUF102 [*] Invalid rule code in `# noqa`: INVALID200 @@ -146,10 +132,8 @@ RUF102 [*] Invalid rule code in `# noqa`: INVALID200 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the rule code `INVALID200` | -13 | # Test for multiple invalid - - from collections import defaultdict # noqa: INVALID100, INVALID200, F401 +14 - from collections import defaultdict # noqa: INVALID100, INVALID200, F401 14 + from collections import defaultdict # noqa: INVALID100, F401 -15 | # Test for preserving valid codes when fixing | RUF102 [*] Invalid rule code in `# noqa`: INVALID300 @@ -165,10 +149,8 @@ RUF102 [*] Invalid rule code in `# noqa`: INVALID300 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the rule code `INVALID300` | -15 | # Test for preserving valid codes when fixing - - from itertools import chain # noqa: E402, INVALID300, F401 +16 - from itertools import chain # noqa: E402, INVALID300, F401 16 + from itertools import chain # noqa: E402, F401 -17 | # Test for mixed code types | RUF102 [*] Invalid rule code in `# noqa`: INVALID400 @@ -184,10 +166,8 @@ RUF102 [*] Invalid rule code in `# noqa`: INVALID400 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the rule code `INVALID400` | -17 | # Test for mixed code types - - import json # noqa: E402, INVALID400, V100 +18 - import json # noqa: E402, INVALID400, V100 18 + import json # noqa: E402, V100 -19 | # Test for rule redirects | RUF102 [*] Invalid rule code in `# noqa`: V100 @@ -203,10 +183,8 @@ RUF102 [*] Invalid rule code in `# noqa`: V100 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the rule code `V100` | -17 | # Test for mixed code types - - import json # noqa: E402, INVALID400, V100 +18 - import json # noqa: E402, INVALID400, V100 18 + import json # noqa: E402, INVALID400 -19 | # Test for rule redirects | RUF102 [*] Invalid rule code in `# noqa`: INVALID123 @@ -219,7 +197,6 @@ RUF102 [*] Invalid rule code in `# noqa`: INVALID123 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the `# noqa` comment | -21 | # Invalid code with trailing reason (single comment) - - import pathlib # noqa: INVALID123 some reason +22 - import pathlib # noqa: INVALID123 some reason 22 + import pathlib | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__add_future_import_RUF013_0.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__add_future_import_RUF013_0.py.snap index cdad7610305e0..f198a2da4e865 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__add_future_import_RUF013_0.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__add_future_import_RUF013_0.py.snap @@ -10,13 +10,12 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -1 + from __future__ import annotations -2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable --------------------------------------------------------------------------------- + 1 + from __future__ import annotations + 2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 3 | + … 20 | - - def f(arg: int = None): # RUF013 -21 + def f(arg: int | None = None): # RUF013 -22 | pass +21 ~ def f(arg: int | None = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -29,13 +28,12 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -1 + from __future__ import annotations -2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable --------------------------------------------------------------------------------- + 1 + from __future__ import annotations + 2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 3 | + … 24 | - - def f(arg: str = None): # RUF013 -25 + def f(arg: str | None = None): # RUF013 -26 | pass +25 ~ def f(arg: str | None = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -48,13 +46,12 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -1 + from __future__ import annotations -2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable --------------------------------------------------------------------------------- + 1 + from __future__ import annotations + 2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 3 | + … 28 | - - def f(arg: Tuple[str] = None): # RUF013 -29 + def f(arg: Tuple[str] | None = None): # RUF013 -30 | pass +29 ~ def f(arg: Tuple[str] | None = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -67,13 +64,12 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -1 + from __future__ import annotations -2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable --------------------------------------------------------------------------------- + 1 + from __future__ import annotations + 2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 3 | + … 58 | - - def f(arg: Union = None): # RUF013 -59 + def f(arg: Union | None = None): # RUF013 -60 | pass +59 ~ def f(arg: Union | None = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -86,13 +82,12 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -1 + from __future__ import annotations -2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable --------------------------------------------------------------------------------- + 1 + from __future__ import annotations + 2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 3 | + … 62 | - - def f(arg: Union[int] = None): # RUF013 -63 + def f(arg: Union[int] | None = None): # RUF013 -64 | pass +63 ~ def f(arg: Union[int] | None = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -105,13 +100,12 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -1 + from __future__ import annotations -2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable --------------------------------------------------------------------------------- + 1 + from __future__ import annotations + 2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 3 | + … 66 | - - def f(arg: Union[int, str] = None): # RUF013 -67 + def f(arg: Union[int, str] | None = None): # RUF013 -68 | pass +67 ~ def f(arg: Union[int, str] | None = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -124,13 +118,12 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -1 + from __future__ import annotations -2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable --------------------------------------------------------------------------------- + 1 + from __future__ import annotations + 2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 3 | + … 85 | - - def f(arg: int | float = None): # RUF013 -86 + def f(arg: int | float | None = None): # RUF013 -87 | pass +86 ~ def f(arg: int | float | None = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -143,13 +136,12 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -1 + from __future__ import annotations -2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable --------------------------------------------------------------------------------- + 1 + from __future__ import annotations + 2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 3 | + … 89 | - - def f(arg: int | float | str | bytes = None): # RUF013 -90 + def f(arg: int | float | str | bytes | None = None): # RUF013 -91 | pass +90 ~ def f(arg: int | float | str | bytes | None = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -162,13 +154,12 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -1 + from __future__ import annotations -2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable --------------------------------------------------------------------------------- + 1 + from __future__ import annotations + 2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 3 | + … 108 | - - def f(arg: Literal[1] = None): # RUF013 -109 + def f(arg: Literal[1] | None = None): # RUF013 -110 | pass +109 ~ def f(arg: Literal[1] | None = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -181,13 +172,12 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -1 + from __future__ import annotations -2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable --------------------------------------------------------------------------------- + 1 + from __future__ import annotations + 2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 3 | + … 112 | - - def f(arg: Literal[1, "foo"] = None): # RUF013 -113 + def f(arg: Literal[1, "foo"] | None = None): # RUF013 -114 | pass +113 ~ def f(arg: Literal[1, "foo"] | None = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -200,13 +190,12 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -1 + from __future__ import annotations -2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable --------------------------------------------------------------------------------- + 1 + from __future__ import annotations + 2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 3 | + … 131 | - - def f(arg: Annotated[int, ...] = None): # RUF013 -132 + def f(arg: Annotated[int | None, ...] = None): # RUF013 -133 | pass +132 ~ def f(arg: Annotated[int | None, ...] = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -219,13 +208,12 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -1 + from __future__ import annotations -2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable --------------------------------------------------------------------------------- + 1 + from __future__ import annotations + 2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 3 | + … 135 | - - def f(arg: Annotated[Annotated[int | str, ...], ...] = None): # RUF013 -136 + def f(arg: Annotated[Annotated[int | str | None, ...], ...] = None): # RUF013 -137 | pass +136 ~ def f(arg: Annotated[Annotated[int | str | None, ...], ...] = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -240,13 +228,12 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -1 + from __future__ import annotations -2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable --------------------------------------------------------------------------------- + 1 + from __future__ import annotations + 2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 3 | + … 151 | def f( - - arg1: int = None, # RUF013 -152 + arg1: int | None = None, # RUF013 -153 | arg2: Union[int, float] = None, # RUF013 +152 ~ arg1: int | None = None, # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -262,13 +249,12 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -1 + from __future__ import annotations -2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable --------------------------------------------------------------------------------- + 1 + from __future__ import annotations + 2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 3 | + … 152 | arg1: int = None, # RUF013 - - arg2: Union[int, float] = None, # RUF013 -153 + arg2: Union[int, float] | None = None, # RUF013 -154 | arg3: Literal[1, 2, 3] = None, # RUF013 +153 ~ arg2: Union[int, float] | None = None, # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -284,13 +270,12 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -1 + from __future__ import annotations -2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable --------------------------------------------------------------------------------- + 1 + from __future__ import annotations + 2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 3 | + … 153 | arg2: Union[int, float] = None, # RUF013 - - arg3: Literal[1, 2, 3] = None, # RUF013 -154 + arg3: Literal[1, 2, 3] | None = None, # RUF013 -155 | ): +154 ~ arg3: Literal[1, 2, 3] | None = None, # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -303,13 +288,12 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -1 + from __future__ import annotations -2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable --------------------------------------------------------------------------------- + 1 + from __future__ import annotations + 2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 3 | + … 181 | - - def f(arg: Union[Annotated[int, ...], Union[str, bytes]] = None): # RUF013 -182 + def f(arg: Union[Annotated[int, ...], Union[str, bytes]] | None = None): # RUF013 -183 | pass +182 ~ def f(arg: Union[Annotated[int, ...], Union[str, bytes]] | None = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -322,10 +306,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | + 1 ~ from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 2 | + … 187 | - - def f(arg: "int" = None): # RUF013 -188 + def f(arg: "Optional[int]" = None): # RUF013 -189 | pass +188 ~ def f(arg: "Optional[int]" = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -338,10 +323,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `Optional[T]` | + 1 ~ from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 2 | + … 191 | - - def f(arg: "str" = None): # RUF013 -192 + def f(arg: "Optional[str]" = None): # RUF013 -193 | pass +192 ~ def f(arg: "Optional[str]" = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -363,12 +349,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -1 + from __future__ import annotations -2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable --------------------------------------------------------------------------------- + 1 + from __future__ import annotations + 2 | from typing import Annotated, Any, Literal, Optional, Tuple, Union, Hashable + 3 | + … 204 | - - def f(arg: Union["int", "str"] = None): # RUF013 -205 + def f(arg: Union["int", "str"] | None = None): # RUF013 -206 | pass +205 ~ def f(arg: Union["int", "str"] | None = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__add_future_import_RUF013_1.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__add_future_import_RUF013_1.py.snap index f7c4035eb4a65..544c3b1894bee 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__add_future_import_RUF013_1.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__add_future_import_RUF013_1.py.snap @@ -10,10 +10,7 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -3 | - - def f(arg: int = None): # RUF013 4 + from __future__ import annotations -5 + def f(arg: int | None = None): # RUF013 -6 | pass +5 ~ def f(arg: int | None = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__add_future_import_RUF013_3.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__add_future_import_RUF013_3.py.snap index 2ca16f01bb720..5f5d259d54fd8 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__add_future_import_RUF013_3.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__add_future_import_RUF013_3.py.snap @@ -14,9 +14,7 @@ help: Convert to `T | None` 2 | import typing 3 | 4 | - - def f(arg: typing.List[str] = None): # RUF013 -5 + def f(arg: typing.List[str] | None = None): # RUF013 -6 | pass +5 ~ def f(arg: typing.List[str] | None = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -29,13 +27,12 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -1 + from __future__ import annotations -2 | import typing --------------------------------------------------------------------------------- + 1 + from __future__ import annotations + 2 | import typing + 3 | + … 22 | - - def f(arg: typing.Union[int, str] = None): # RUF013 -23 + def f(arg: typing.Union[int, str] | None = None): # RUF013 -24 | pass +23 ~ def f(arg: typing.Union[int, str] | None = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior @@ -48,12 +45,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | help: Convert to `T | None` | -1 + from __future__ import annotations -2 | import typing --------------------------------------------------------------------------------- + 1 + from __future__ import annotations + 2 | import typing + 3 | + … 29 | - - def f(arg: typing.Literal[1, "foo", True] = None): # RUF013 -30 + def f(arg: typing.Literal[1, "foo", True] | None = None): # RUF013 -31 | pass +30 ~ def f(arg: typing.Literal[1, "foo", True] | None = None): # RUF013 | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__add_future_import_RUF013_4.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__add_future_import_RUF013_4.py.snap index b84b79359bbb4..b25bdb6ab5487 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__add_future_import_RUF013_4.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__add_future_import_RUF013_4.py.snap @@ -8,13 +8,11 @@ RUF013 [*] PEP 484 prohibits implicit `Optional` | ^^^ help: Convert to `T | None` | -2 | -3 + from __future__ import annotations -4 | from typing import Optional --------------------------------------------------------------------------------- + 3 + from __future__ import annotations + 4 | from typing import Optional + 5 | + … 15 | - - def multiple_2(arg1: Optional, arg2: Optional = None, arg3: int = None): ... -16 + def multiple_2(arg1: Optional, arg2: Optional = None, arg3: int | None = None): ... -17 | +16 ~ def multiple_2(arg1: Optional, arg2: Optional = None, arg3: int | None = None): ... | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__custom_dummy_var_regexp_preset__RUF052_RUF052_0.py_1.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__custom_dummy_var_regexp_preset__RUF052_RUF052_0.py_1.snap index 6a1e7232f79ee..6da1c659a3393 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__custom_dummy_var_regexp_preset__RUF052_RUF052_0.py_1.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__custom_dummy_var_regexp_preset__RUF052_RUF052_0.py_1.snap @@ -12,12 +12,8 @@ RUF052 [*] Local dummy variable `_var` is accessed | help: Remove leading underscores | -91 | def fun(self): - - _var = "method variable" # [RUF052] - - return _var -92 + var = "method variable" # [RUF052] -93 + return var -94 | +92 ~ var = "method variable" # [RUF052] +93 ~ return var | note: This is an unsafe fix and may change runtime behavior @@ -31,12 +27,8 @@ RUF052 [*] Local dummy variable `_list` is accessed | help: Prefer using trailing underscores to avoid shadowing a built-in | -98 | def fun(): - - _list = "built-in" # [RUF052] - - return _list -99 + list_ = "built-in" # [RUF052] -100 + return list_ -101 | + 99 ~ list_ = "built-in" # [RUF052] +100 ~ return list_ | note: This is an unsafe fix and may change runtime behavior @@ -51,12 +43,8 @@ RUF052 [*] Local dummy variable `_x` is accessed | help: Prefer using trailing underscores to avoid shadowing a variable | -105 | global x - - _x = "shadows global" # [RUF052] - - return _x -106 + x_ = "shadows global" # [RUF052] -107 + return x_ -108 | +106 ~ x_ = "shadows global" # [RUF052] +107 ~ return x_ | note: This is an unsafe fix and may change runtime behavior @@ -72,12 +60,8 @@ RUF052 [*] Local dummy variable `_x` is accessed | help: Prefer using trailing underscores to avoid shadowing a variable | -112 | nonlocal x - - _x = "shadows nonlocal" # [RUF052] - - return _x -113 + x_ = "shadows nonlocal" # [RUF052] -114 + return x_ -115 | bar() +113 ~ x_ = "shadows nonlocal" # [RUF052] +114 ~ return x_ | note: This is an unsafe fix and may change runtime behavior @@ -92,12 +76,8 @@ RUF052 [*] Local dummy variable `_x` is accessed | help: Prefer using trailing underscores to avoid shadowing a variable | -119 | x = "local" - - _x = "shadows local" # [RUF052] - - return _x -120 + x_ = "shadows local" # [RUF052] -121 + return x_ -122 | +120 ~ x_ = "shadows local" # [RUF052] +121 ~ return x_ | note: This is an unsafe fix and may change runtime behavior @@ -155,15 +135,11 @@ RUF052 [*] Local dummy variable `_P` is accessed | help: Remove leading underscores | -152 | - - _P = ParamSpec("_P") -153 + P = ParamSpec("P") +153 ~ P = ParamSpec("P") 154 | _T = TypeVar(name="_T", covariant=True, bound=int|str) --------------------------------------------------------------------------------- + … 161 | - - print(_T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -162 + print(_T, P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -163 | +162 ~ print(_T, P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) | note: This is an unsafe fix and may change runtime behavior @@ -178,15 +154,11 @@ RUF052 [*] Local dummy variable `_T` is accessed | help: Remove leading underscores | -153 | _P = ParamSpec("_P") - - _T = TypeVar(name="_T", covariant=True, bound=int|str) -154 + T = TypeVar(name="T", covariant=True, bound=int|str) +154 ~ T = TypeVar(name="T", covariant=True, bound=int|str) 155 | _NT = NamedTuple("_NT", [("foo", int)]) --------------------------------------------------------------------------------- + … 161 | - - print(_T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -162 + print(T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -163 | +162 ~ print(T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) | note: This is an unsafe fix and may change runtime behavior @@ -202,15 +174,11 @@ RUF052 [*] Local dummy variable `_NT` is accessed | help: Remove leading underscores | -154 | _T = TypeVar(name="_T", covariant=True, bound=int|str) - - _NT = NamedTuple("_NT", [("foo", int)]) -155 + NT = NamedTuple("NT", [("foo", int)]) +155 ~ NT = NamedTuple("NT", [("foo", int)]) 156 | _E = Enum("_E", ["a", "b", "c"]) --------------------------------------------------------------------------------- + … 161 | - - print(_T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -162 + print(_T, _P, NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -163 | +162 ~ print(_T, _P, NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) | note: This is an unsafe fix and may change runtime behavior @@ -226,15 +194,11 @@ RUF052 [*] Local dummy variable `_E` is accessed | help: Remove leading underscores | -155 | _NT = NamedTuple("_NT", [("foo", int)]) - - _E = Enum("_E", ["a", "b", "c"]) -156 + E = Enum("E", ["a", "b", "c"]) +156 ~ E = Enum("E", ["a", "b", "c"]) 157 | _NT2 = namedtuple("_NT2", ['x', 'y', 'z']) --------------------------------------------------------------------------------- + … 161 | - - print(_T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -162 + print(_T, _P, _NT, E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -163 | +162 ~ print(_T, _P, _NT, E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) | note: This is an unsafe fix and may change runtime behavior @@ -250,16 +214,11 @@ RUF052 [*] Local dummy variable `_NT2` is accessed | help: Remove leading underscores | -156 | _E = Enum("_E", ["a", "b", "c"]) - - _NT2 = namedtuple("_NT2", ['x', 'y', 'z']) -157 + NT2 = namedtuple("NT2", ['x', 'y', 'z']) +157 ~ NT2 = namedtuple("NT2", ['x', 'y', 'z']) 158 | _NT3 = namedtuple(typename="_NT3", field_names=['x', 'y', 'z']) -159 | _DynamicClass = type("_DynamicClass", (), {}) -160 | _NotADynamicClass = type("_NotADynamicClass") + … 161 | - - print(_T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -162 + print(_T, _P, _NT, _E, NT2, _NT3, _DynamicClass, _NotADynamicClass) -163 | +162 ~ print(_T, _P, _NT, _E, NT2, _NT3, _DynamicClass, _NotADynamicClass) | note: This is an unsafe fix and may change runtime behavior @@ -275,15 +234,11 @@ RUF052 [*] Local dummy variable `_NT3` is accessed | help: Remove leading underscores | -157 | _NT2 = namedtuple("_NT2", ['x', 'y', 'z']) - - _NT3 = namedtuple(typename="_NT3", field_names=['x', 'y', 'z']) -158 + NT3 = namedtuple(typename="NT3", field_names=['x', 'y', 'z']) +158 ~ NT3 = namedtuple(typename="NT3", field_names=['x', 'y', 'z']) 159 | _DynamicClass = type("_DynamicClass", (), {}) 160 | _NotADynamicClass = type("_NotADynamicClass") 161 | - - print(_T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -162 + print(_T, _P, _NT, _E, _NT2, NT3, _DynamicClass, _NotADynamicClass) -163 | +162 ~ print(_T, _P, _NT, _E, _NT2, NT3, _DynamicClass, _NotADynamicClass) | note: This is an unsafe fix and may change runtime behavior @@ -298,14 +253,10 @@ RUF052 [*] Local dummy variable `_DynamicClass` is accessed | help: Remove leading underscores | -158 | _NT3 = namedtuple(typename="_NT3", field_names=['x', 'y', 'z']) - - _DynamicClass = type("_DynamicClass", (), {}) -159 + DynamicClass = type("DynamicClass", (), {}) +159 ~ DynamicClass = type("DynamicClass", (), {}) 160 | _NotADynamicClass = type("_NotADynamicClass") 161 | - - print(_T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -162 + print(_T, _P, _NT, _E, _NT2, _NT3, DynamicClass, _NotADynamicClass) -163 | +162 ~ print(_T, _P, _NT, _E, _NT2, _NT3, DynamicClass, _NotADynamicClass) | note: This is an unsafe fix and may change runtime behavior @@ -321,13 +272,9 @@ RUF052 [*] Local dummy variable `_NotADynamicClass` is accessed | help: Remove leading underscores | -159 | _DynamicClass = type("_DynamicClass", (), {}) - - _NotADynamicClass = type("_NotADynamicClass") -160 + NotADynamicClass = type("_NotADynamicClass") +160 ~ NotADynamicClass = type("_NotADynamicClass") 161 | - - print(_T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, _NotADynamicClass) -162 + print(_T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, NotADynamicClass) -163 | +162 ~ print(_T, _P, _NT, _E, _NT2, _NT3, _DynamicClass, NotADynamicClass) | note: This is an unsafe fix and may change runtime behavior @@ -342,15 +289,11 @@ RUF052 [*] Local dummy variable `_dummy_var` is accessed | help: Prefer using trailing underscores to avoid shadowing a variable | -181 | def foo(): - - _dummy_var = 42 -182 + dummy_var_ = 42 +182 ~ dummy_var_ = 42 183 | 184 | def bar(): 185 | dummy_var = 43 - - print(_dummy_var) -186 + print(dummy_var_) -187 | +186 ~ print(dummy_var_) | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__invalid_rule_code_external_rules_ruff__RUF102.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__invalid_rule_code_external_rules_ruff__RUF102.py.snap index 2320e73ff96d8..ae36cf11e9b23 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__invalid_rule_code_external_rules_ruff__RUF102.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__invalid_rule_code_external_rules_ruff__RUF102.py.snap @@ -13,10 +13,8 @@ RUF102 [*] Invalid rule code in `# noqa`: INVALID123 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the `# noqa` comment | -1 | # Invalid code - - import os # noqa: INVALID123 +2 - import os # noqa: INVALID123 2 + import os -3 | # External code | RUF102 [*] Invalid rule code in `# noqa`: INVALID456 @@ -32,10 +30,8 @@ RUF102 [*] Invalid rule code in `# noqa`: INVALID456 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the rule code `INVALID456` | -6 | import sys # noqa: E402 - - from functools import cache # Preceeding comment # noqa: F401, INVALID456 +7 - from functools import cache # Preceeding comment # noqa: F401, INVALID456 7 + from functools import cache # Preceeding comment # noqa: F401 -8 | from itertools import product # Preceeding comment # noqa: INVALID789 | RUF102 [*] Invalid rule code in `# noqa`: INVALID789 @@ -51,10 +47,8 @@ RUF102 [*] Invalid rule code in `# noqa`: INVALID789 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the `# noqa` comment | -7 | from functools import cache # Preceeding comment # noqa: F401, INVALID456 - - from itertools import product # Preceeding comment # noqa: INVALID789 +8 - from itertools import product # Preceeding comment # noqa: INVALID789 8 + from itertools import product # Preceeding comment -9 | # Succeeding comment | RUF102 [*] Invalid rule code in `# noqa`: INVALID000 @@ -70,10 +64,8 @@ RUF102 [*] Invalid rule code in `# noqa`: INVALID000 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the `# noqa` comment | -9 | # Succeeding comment - - import math # noqa: INVALID000 # Succeeding comment +10 - import math # noqa: INVALID000 # Succeeding comment 10 + import math # Succeeding comment -11 | # Mixed valid and invalid | RUF102 [*] Invalid rule code in `# noqa`: INVALID123 @@ -89,10 +81,8 @@ RUF102 [*] Invalid rule code in `# noqa`: INVALID123 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the rule code `INVALID123` | -11 | # Mixed valid and invalid - - from typing import List # noqa: F401, INVALID123 +12 - from typing import List # noqa: F401, INVALID123 12 + from typing import List # noqa: F401 -13 | # Test for multiple invalid | RUF102 [*] Invalid rule code in `# noqa`: INVALID100 @@ -108,10 +98,8 @@ RUF102 [*] Invalid rule code in `# noqa`: INVALID100 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the rule code `INVALID100` | -13 | # Test for multiple invalid - - from collections import defaultdict # noqa: INVALID100, INVALID200, F401 +14 - from collections import defaultdict # noqa: INVALID100, INVALID200, F401 14 + from collections import defaultdict # noqa: INVALID200, F401 -15 | # Test for preserving valid codes when fixing | RUF102 [*] Invalid rule code in `# noqa`: INVALID200 @@ -127,10 +115,8 @@ RUF102 [*] Invalid rule code in `# noqa`: INVALID200 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the rule code `INVALID200` | -13 | # Test for multiple invalid - - from collections import defaultdict # noqa: INVALID100, INVALID200, F401 +14 - from collections import defaultdict # noqa: INVALID100, INVALID200, F401 14 + from collections import defaultdict # noqa: INVALID100, F401 -15 | # Test for preserving valid codes when fixing | RUF102 [*] Invalid rule code in `# noqa`: INVALID300 @@ -146,10 +132,8 @@ RUF102 [*] Invalid rule code in `# noqa`: INVALID300 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the rule code `INVALID300` | -15 | # Test for preserving valid codes when fixing - - from itertools import chain # noqa: E402, INVALID300, F401 +16 - from itertools import chain # noqa: E402, INVALID300, F401 16 + from itertools import chain # noqa: E402, F401 -17 | # Test for mixed code types | RUF102 [*] Invalid rule code in `# noqa`: INVALID400 @@ -165,10 +149,8 @@ RUF102 [*] Invalid rule code in `# noqa`: INVALID400 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the rule code `INVALID400` | -17 | # Test for mixed code types - - import json # noqa: E402, INVALID400, V100 +18 - import json # noqa: E402, INVALID400, V100 18 + import json # noqa: E402, V100 -19 | # Test for rule redirects | RUF102 [*] Invalid rule code in `# noqa`: INVALID123 @@ -181,7 +163,6 @@ RUF102 [*] Invalid rule code in `# noqa`: INVALID123 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the `# noqa` comment | -21 | # Invalid code with trailing reason (single comment) - - import pathlib # noqa: INVALID123 some reason +22 - import pathlib # noqa: INVALID123 some reason 22 + import pathlib | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__invalid_rule_code_external_rules_ruff__RUF102_1.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__invalid_rule_code_external_rules_ruff__RUF102_1.py.snap index e53e9111a9d56..48d3b84ea5519 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__invalid_rule_code_external_rules_ruff__RUF102_1.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__invalid_rule_code_external_rules_ruff__RUF102_1.py.snap @@ -13,7 +13,5 @@ RUF102 [*] Invalid rule code in `# noqa`: INVALID123 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the `# noqa` comment | -1 | # Invalid file-level code - - # ruff: noqa: INVALID123 -2 | +2 - # ruff: noqa: INVALID123 | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__missing_fstring_syntax_backslash_py311.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__missing_fstring_syntax_backslash_py311.snap index 8b3cb6371bac5..e9019823f5864 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__missing_fstring_syntax_backslash_py311.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__missing_fstring_syntax_backslash_py311.snap @@ -22,11 +22,8 @@ RUF027 [*] Possible f-string without an `f` prefix | |_______^ help: Add `f` prefix | -40 | # RUF027 - - multi_line = a = """b { # comment -41 + multi_line = a = f"""b { # comment -42 | c} d - | +41 | multi_line = a = f"""b { # comment + | + note: This is an unsafe fix and may change runtime behavior @@ -42,11 +39,8 @@ RUF027 [*] Possible f-string without an `f` prefix | |_____^ help: Add `f` prefix | -48 | # RUF027 - - b = " {\ -49 + b = f" {\ -50 | a} \ - | +49 | b = f" {\ + | + note: This is an unsafe fix and may change runtime behavior @@ -62,11 +56,8 @@ RUF027 [*] Possible f-string without an `f` prefix | help: Add `f` prefix | -91 | x = "test" - - print("Hello {'\\n'}{x}") # Should not trigger RUF027 for Python < 3.12 -92 + print(f"Hello {'\\n'}{x}") # Should not trigger RUF027 for Python < 3.12 -93 | - | +92 | print(f"Hello {'\\n'}{x}") # Should not trigger RUF027 for Python < 3.12 + | + note: This is an unsafe fix and may change runtime behavior @@ -84,9 +75,6 @@ RUF027 [*] Possible f-string without an `f` prefix | help: Add `f` prefix | -97 | x = "!" - - print("""{x # } -98 + print(f"""{x # } -99 | }""") - | +98 | print(f"""{x # } + | + note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__no_remove_parentheses_starred_expr_py310.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__no_remove_parentheses_starred_expr_py310.snap index 49ff551ea8808..64e28b90d6432 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__no_remove_parentheses_starred_expr_py310.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__no_remove_parentheses_starred_expr_py310.snap @@ -12,10 +12,8 @@ RUF031 [*] Avoid parentheses for tuples in subscripts | help: Remove parentheses | -1 | d = {(1,2):"a",(3,4):"b",(5,6,7):"c",(8,):"d"} - - d[(1,2)] +2 - d[(1,2)] 2 + d[1,2] -3 | d[( | RUF031 [*] Avoid parentheses for tuples in subscripts @@ -34,14 +32,9 @@ RUF031 [*] Avoid parentheses for tuples in subscripts | help: Remove parentheses | -2 | d[(1,2)] - - d[( -3 + d[ -4 | 1, -5 | 2 - - )] -6 + ] -7 | d[ +3 ~ d[ +4 + 1, +5 + 2 | RUF031 [*] Avoid parentheses for tuples in subscripts @@ -56,10 +49,8 @@ RUF031 [*] Avoid parentheses for tuples in subscripts | help: Remove parentheses | -10 | ] - - d[(2,4)] +11 - d[(2,4)] 11 + d[2,4] -12 | d[(5,6,7)] | RUF031 [*] Avoid parentheses for tuples in subscripts @@ -74,10 +65,8 @@ RUF031 [*] Avoid parentheses for tuples in subscripts | help: Remove parentheses | -11 | d[(2,4)] - - d[(5,6,7)] +12 - d[(5,6,7)] 12 + d[5,6,7] -13 | d[(8,)] | RUF031 [*] Avoid parentheses for tuples in subscripts @@ -92,10 +81,8 @@ RUF031 [*] Avoid parentheses for tuples in subscripts | help: Remove parentheses | -12 | d[(5,6,7)] - - d[(8,)] +13 - d[(8,)] 13 + d[8,] -14 | d[tuple(1,2)] | RUF031 [*] Avoid parentheses for tuples in subscripts @@ -109,11 +96,8 @@ RUF031 [*] Avoid parentheses for tuples in subscripts | help: Remove parentheses | -19 | e = {((1,2),(3,4)):"a"} - - e[((1,2),(3,4))] -20 | e[(1,2),(3,4)] -21 + e[(1,2),(3,4)] -22 | +20 - e[((1,2),(3,4))] +20 + e[(1,2),(3,4)] | RUF031 [*] Avoid parentheses for tuples in subscripts @@ -126,10 +110,8 @@ RUF031 [*] Avoid parentheses for tuples in subscripts | help: Remove parentheses | -23 | token_features[ - - (window_position, feature_name) +24 - (window_position, feature_name) 24 + window_position, feature_name -25 | ] = self._extract_raw_features_from_token | RUF031 [*] Avoid parentheses for tuples in subscripts @@ -143,8 +125,6 @@ RUF031 [*] Avoid parentheses for tuples in subscripts | help: Remove parentheses | -27 | d[1,] - - d[(1,)] +28 - d[(1,)] 28 + d[1,] -29 | d[()] # empty tuples should be ignored | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__noqa.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__noqa.snap index d8164e2f94455..1a0f0e000f58b 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__noqa.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__noqa.snap @@ -18,8 +18,7 @@ F841 [*] Local variable `I` is assigned to but never used | ^ help: Remove assignment to unused variable `I` | -23 | # logged to user - - I = 1 # noqa: E741.F841 +24 - I = 1 # noqa: E741.F841 24 + pass # noqa: E741.F841 | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__prefer_parentheses_getitem_tuple.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__prefer_parentheses_getitem_tuple.snap index 4dc34ed726408..33b360381a03e 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__prefer_parentheses_getitem_tuple.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__prefer_parentheses_getitem_tuple.snap @@ -13,14 +13,10 @@ RUF031 [*] Use parentheses for tuples in subscripts 11 | d[(2,4)] | help: Parenthesize tuple - | -7 | d[ - - 1, - - 2 -8 + (1, -9 + 2) -10 | ] - | + | +8 ~ (1, +9 + 2) + | RUF031 [*] Use parentheses for tuples in subscripts --> RUF031_prefer_parens.py:16:3 @@ -34,10 +30,8 @@ RUF031 [*] Use parentheses for tuples in subscripts | help: Parenthesize tuple | -15 | d[tuple(8)] - - d[1,2] +16 - d[1,2] 16 + d[(1,2)] -17 | d[3,4] | RUF031 [*] Use parentheses for tuples in subscripts @@ -52,10 +46,8 @@ RUF031 [*] Use parentheses for tuples in subscripts | help: Parenthesize tuple | -16 | d[1,2] - - d[3,4] +17 - d[3,4] 17 + d[(3,4)] -18 | d[5,6,7] | RUF031 [*] Use parentheses for tuples in subscripts @@ -70,10 +62,8 @@ RUF031 [*] Use parentheses for tuples in subscripts | help: Parenthesize tuple | -17 | d[3,4] - - d[5,6,7] +18 - d[5,6,7] 18 + d[(5,6,7)] -19 | e = {((1,2),(3,4)):"a"} | RUF031 [*] Use parentheses for tuples in subscripts @@ -88,10 +78,8 @@ RUF031 [*] Use parentheses for tuples in subscripts | help: Parenthesize tuple | -20 | e[((1,2),(3,4))] - - e[(1,2),(3,4)] +21 - e[(1,2),(3,4)] 21 + e[((1,2),(3,4))] -22 | | RUF031 [*] Use parentheses for tuples in subscripts @@ -106,9 +94,6 @@ RUF031 [*] Use parentheses for tuples in subscripts | help: Parenthesize tuple | -25 | ] = self._extract_raw_features_from_token - - d[1,] -26 | d[(1,)] -27 + d[(1,)] -28 | d[()] # empty tuples should be ignored +26 - d[1,] +26 + d[(1,)] | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF039_RUF039.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF039_RUF039.py.snap index 81ec14c221918..95e74c8f33343 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF039_RUF039.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF039_RUF039.py.snap @@ -12,11 +12,8 @@ RUF039 [*] First argument to `re.compile()` is not raw string | help: Replace with raw string | -4 | # Errors - - re.compile('single free-spacing', flags=re.X) -5 + re.compile(r'single free-spacing', flags=re.X) -6 | re.findall('si\ngle') - | +5 | re.compile(r'single free-spacing', flags=re.X) + | + RUF039 [*] First argument to `re.findall()` is not raw string --> RUF039.py:6:12 @@ -30,11 +27,8 @@ RUF039 [*] First argument to `re.findall()` is not raw string | help: Replace with raw string | -5 | re.compile('single free-spacing', flags=re.X) - - re.findall('si\ngle') -6 + re.findall(r'si\ngle') -7 | re.finditer("dou\ble") - | +6 | re.findall(r'si\ngle') + | + note: This is an unsafe fix and may change runtime behavior RUF039 First argument to `re.finditer()` is not raw string @@ -61,11 +55,8 @@ RUF039 [*] First argument to `re.fullmatch()` is not raw string | help: Replace with raw string | -7 | re.finditer("dou\ble") - - re.fullmatch('''t\riple single''') -8 + re.fullmatch(r'''t\riple single''') -9 | re.match("""\triple double""") - | +8 | re.fullmatch(r'''t\riple single''') + | + note: This is an unsafe fix and may change runtime behavior RUF039 [*] First argument to `re.match()` is not raw string @@ -79,12 +70,9 @@ RUF039 [*] First argument to `re.match()` is not raw string 11 | re.split("raw", r'second') | help: Replace with raw string - | -8 | re.fullmatch('''t\riple single''') - - re.match("""\triple double""") -9 + re.match(r"""\triple double""") -10 | re.search('two', 'args') - | + | +9 | re.match(r"""\triple double""") + | + note: This is an unsafe fix and may change runtime behavior RUF039 [*] First argument to `re.search()` is not raw string @@ -99,11 +87,8 @@ RUF039 [*] First argument to `re.search()` is not raw string | help: Replace with raw string | -9 | re.match("""\triple double""") - - re.search('two', 'args') -10 + re.search(r'two', 'args') -11 | re.split("raw", r'second') - | +10 | re.search(r'two', 'args') + | + RUF039 [*] First argument to `re.split()` is not raw string --> RUF039.py:11:10 @@ -117,11 +102,8 @@ RUF039 [*] First argument to `re.split()` is not raw string | help: Replace with raw string | -10 | re.search('two', 'args') - - re.split("raw", r'second') -11 + re.split(r"raw", r'second') -12 | re.sub(u'''nicode''', u"f(?i)rst") - | +11 | re.split(r"raw", r'second') + | + RUF039 First argument to `re.sub()` is not raw string --> RUF039.py:12:8 @@ -146,11 +128,8 @@ RUF039 [*] First argument to `re.subn()` is not raw bytes literal | help: Replace with raw bytes literal | -12 | re.sub(u'''nicode''', u"f(?i)rst") - - re.subn(b"""ytes are""", f"\u006e") -13 + re.subn(rb"""ytes are""", f"\u006e") -14 | - | +13 | re.subn(rb"""ytes are""", f"\u006e") + | + RUF039 [*] First argument to `regex.compile()` is not raw string --> RUF039.py:15:15 @@ -164,11 +143,8 @@ RUF039 [*] First argument to `regex.compile()` is not raw string | help: Replace with raw string | -14 | - - regex.compile('single free-spacing', flags=regex.X) -15 + regex.compile(r'single free-spacing', flags=regex.X) -16 | regex.findall('si\ngle') - | +15 | regex.compile(r'single free-spacing', flags=regex.X) + | + RUF039 [*] First argument to `regex.findall()` is not raw string --> RUF039.py:16:15 @@ -181,11 +157,8 @@ RUF039 [*] First argument to `regex.findall()` is not raw string | help: Replace with raw string | -15 | regex.compile('single free-spacing', flags=regex.X) - - regex.findall('si\ngle') -16 + regex.findall(r'si\ngle') -17 | regex.finditer("dou\ble") - | +16 | regex.findall(r'si\ngle') + | + note: This is an unsafe fix and may change runtime behavior RUF039 First argument to `regex.finditer()` is not raw string @@ -212,11 +185,8 @@ RUF039 [*] First argument to `regex.fullmatch()` is not raw string | help: Replace with raw string | -17 | regex.finditer("dou\ble") - - regex.fullmatch('''t\riple single''') -18 + regex.fullmatch(r'''t\riple single''') -19 | regex.match("""\triple double""") - | +18 | regex.fullmatch(r'''t\riple single''') + | + note: This is an unsafe fix and may change runtime behavior RUF039 [*] First argument to `regex.match()` is not raw string @@ -231,11 +201,8 @@ RUF039 [*] First argument to `regex.match()` is not raw string | help: Replace with raw string | -18 | regex.fullmatch('''t\riple single''') - - regex.match("""\triple double""") -19 + regex.match(r"""\triple double""") -20 | regex.search('two', 'args') - | +19 | regex.match(r"""\triple double""") + | + note: This is an unsafe fix and may change runtime behavior RUF039 [*] First argument to `regex.search()` is not raw string @@ -250,11 +217,8 @@ RUF039 [*] First argument to `regex.search()` is not raw string | help: Replace with raw string | -19 | regex.match("""\triple double""") - - regex.search('two', 'args') -20 + regex.search(r'two', 'args') -21 | regex.split("raw", r'second') - | +20 | regex.search(r'two', 'args') + | + RUF039 [*] First argument to `regex.split()` is not raw string --> RUF039.py:21:13 @@ -268,11 +232,8 @@ RUF039 [*] First argument to `regex.split()` is not raw string | help: Replace with raw string | -20 | regex.search('two', 'args') - - regex.split("raw", r'second') -21 + regex.split(r"raw", r'second') -22 | regex.sub(u'''nicode''', u"f(?i)rst") - | +21 | regex.split(r"raw", r'second') + | + RUF039 First argument to `regex.sub()` is not raw string --> RUF039.py:22:11 @@ -297,11 +258,8 @@ RUF039 [*] First argument to `regex.subn()` is not raw bytes literal | help: Replace with raw bytes literal | -22 | regex.sub(u'''nicode''', u"f(?i)rst") - - regex.subn(b"""ytes are""", f"\u006e") -23 + regex.subn(rb"""ytes are""", f"\u006e") -24 | - | +23 | regex.subn(rb"""ytes are""", f"\u006e") + | + RUF039 [*] First argument to `regex.template()` is not raw string --> RUF039.py:25:16 @@ -317,11 +275,8 @@ RUF039 [*] First argument to `regex.template()` is not raw string | |___^ help: Replace with raw string | -24 | - - regex.template("""(?m) -25 + regex.template(r"""(?m) -26 | (?:ulti)? - | +25 | regex.template(r"""(?m) + | + RUF039 [*] First argument to `re.compile()` is not raw string --> RUF039.py:59:12 @@ -334,11 +289,8 @@ RUF039 [*] First argument to `re.compile()` is not raw string | help: Replace with raw string | -58 | # https://github.com/astral-sh/ruff/issues/16713 - - re.compile("\a\f\n\r\t\u27F2\U0001F0A1\v\x41") # with unsafe fix -59 + re.compile(r"\a\f\n\r\t\u27F2\U0001F0A1\v\x41") # with unsafe fix -60 | re.compile("\b") # without fix - | +59 | re.compile(r"\a\f\n\r\t\u27F2\U0001F0A1\v\x41") # with unsafe fix + | + note: This is an unsafe fix and may change runtime behavior RUF039 First argument to `re.compile()` is not raw string diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF039_RUF039_concat.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF039_RUF039_concat.py.snap index a2cb085e4018c..9d7040b99a5f3 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF039_RUF039_concat.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF039_RUF039_concat.py.snap @@ -12,11 +12,8 @@ RUF039 [*] First argument to `re.compile()` is not raw string | help: Replace with raw string | -4 | re.compile( - - 'implicit' -5 + r'implicit' -6 | 'concatenation' - | +5 | r'implicit' + | + RUF039 [*] First argument to `re.compile()` is not raw string --> RUF039_concat.py:6:5 @@ -30,11 +27,8 @@ RUF039 [*] First argument to `re.compile()` is not raw string | help: Replace with raw string | -5 | 'implicit' - - 'concatenation' -6 + r'concatenation' -7 | ) - | +6 | r'concatenation' + | + RUF039 [*] First argument to `re.findall()` is not raw string --> RUF039_concat.py:12:5 @@ -50,11 +44,8 @@ RUF039 [*] First argument to `re.findall()` is not raw string | help: Replace with raw string | -11 | ''' - - """ -12 + r""" -13 | concatenation - | +12 | r""" + | + RUF039 [*] First argument to `re.match()` is not raw bytes literal --> RUF039_concat.py:26:5 @@ -68,11 +59,8 @@ RUF039 [*] First argument to `re.match()` is not raw bytes literal | help: Replace with raw bytes literal | -25 | re.match( - - b'reak' -26 + rb'reak' -27 | br'eak' - | +26 | rb'reak' + | + RUF039 First argument to `re.search()` is not raw string --> RUF039_concat.py:30:8 @@ -98,11 +86,8 @@ RUF039 [*] First argument to `re.search()` is not raw string | help: Replace with raw string | -30 | r''u'' - - '''okay?''' -31 + r'''okay?''' -32 | ) - | +31 | r'''okay?''' + | + RUF039 [*] First argument to `re.split()` is not raw string --> RUF039_concat.py:33:10 @@ -116,11 +101,8 @@ RUF039 [*] First argument to `re.split()` is not raw string | help: Replace with raw string | -32 | ) - - re.split(''U"""w"""U'') -33 + re.split(r''U"""w"""U'') -34 | re.sub( - | +33 | re.split(r''U"""w"""U'') + | + RUF039 First argument to `re.split()` is not raw string --> RUF039_concat.py:33:12 @@ -158,11 +140,8 @@ RUF039 [*] First argument to `re.sub()` is not raw string | help: Replace with raw string | -34 | re.sub( - - "I''m o" -35 + r"I''m o" -36 | 'utta ideas' - | +35 | r"I''m o" + | + RUF039 [*] First argument to `re.sub()` is not raw string --> RUF039_concat.py:36:5 @@ -176,11 +155,8 @@ RUF039 [*] First argument to `re.sub()` is not raw string | help: Replace with raw string | -35 | "I''m o" - - 'utta ideas' -36 + r'utta ideas' -37 | ) - | +36 | r'utta ideas' + | + RUF039 [*] First argument to `re.subn()` is not raw string --> RUF039_concat.py:38:9 @@ -191,11 +167,8 @@ RUF039 [*] First argument to `re.subn()` is not raw string | ^^^^ help: Replace with raw string | -37 | ) - - re.subn("()"r' am I'"??") -38 + re.subn(r"()"r' am I'"??") -39 | - | +38 | re.subn(r"()"r' am I'"??") + | + RUF039 [*] First argument to `re.subn()` is not raw string --> RUF039_concat.py:38:21 @@ -206,11 +179,8 @@ RUF039 [*] First argument to `re.subn()` is not raw string | ^^^^ help: Replace with raw string | -37 | ) - - re.subn("()"r' am I'"??") -38 + re.subn("()"r' am I'r"??") -39 | - | +38 | re.subn("()"r' am I'r"??") + | + RUF039 [*] First argument to `regex.compile()` is not raw string --> RUF039_concat.py:45:5 @@ -223,11 +193,8 @@ RUF039 [*] First argument to `regex.compile()` is not raw string | help: Replace with raw string | -44 | regex.compile( - - 'implicit' -45 + r'implicit' -46 | 'concatenation' - | +45 | r'implicit' + | + RUF039 [*] First argument to `regex.compile()` is not raw string --> RUF039_concat.py:46:5 @@ -241,11 +208,8 @@ RUF039 [*] First argument to `regex.compile()` is not raw string | help: Replace with raw string | -45 | 'implicit' - - 'concatenation' -46 + r'concatenation' -47 | ) - | +46 | r'concatenation' + | + RUF039 [*] First argument to `regex.findall()` is not raw string --> RUF039_concat.py:52:5 @@ -261,11 +225,8 @@ RUF039 [*] First argument to `regex.findall()` is not raw string | help: Replace with raw string | -51 | ''' - - """ -52 + r""" -53 | concatenation - | +52 | r""" + | + RUF039 [*] First argument to `regex.match()` is not raw bytes literal --> RUF039_concat.py:66:5 @@ -279,11 +240,8 @@ RUF039 [*] First argument to `regex.match()` is not raw bytes literal | help: Replace with raw bytes literal | -65 | regex.match( - - b'reak' -66 + rb'reak' -67 | br'eak' - | +66 | rb'reak' + | + RUF039 First argument to `regex.search()` is not raw string --> RUF039_concat.py:70:8 @@ -309,11 +267,8 @@ RUF039 [*] First argument to `regex.search()` is not raw string | help: Replace with raw string | -70 | r''u'' - - '''okay?''' -71 + r'''okay?''' -72 | ) - | +71 | r'''okay?''' + | + RUF039 [*] First argument to `regex.split()` is not raw string --> RUF039_concat.py:73:13 @@ -327,11 +282,8 @@ RUF039 [*] First argument to `regex.split()` is not raw string | help: Replace with raw string | -72 | ) - - regex.split(''U"""w"""U'') -73 + regex.split(r''U"""w"""U'') -74 | regex.sub( - | +73 | regex.split(r''U"""w"""U'') + | + RUF039 First argument to `regex.split()` is not raw string --> RUF039_concat.py:73:15 @@ -369,11 +321,8 @@ RUF039 [*] First argument to `regex.sub()` is not raw string | help: Replace with raw string | -74 | regex.sub( - - "I''m o" -75 + r"I''m o" -76 | 'utta ideas' - | +75 | r"I''m o" + | + RUF039 [*] First argument to `regex.sub()` is not raw string --> RUF039_concat.py:76:5 @@ -387,11 +336,8 @@ RUF039 [*] First argument to `regex.sub()` is not raw string | help: Replace with raw string | -75 | "I''m o" - - 'utta ideas' -76 + r'utta ideas' -77 | ) - | +76 | r'utta ideas' + | + RUF039 [*] First argument to `regex.subn()` is not raw string --> RUF039_concat.py:78:12 @@ -402,11 +348,8 @@ RUF039 [*] First argument to `regex.subn()` is not raw string | ^^^^ help: Replace with raw string | -77 | ) - - regex.subn("()"r' am I'"??") -78 + regex.subn(r"()"r' am I'"??") -79 | - | +78 | regex.subn(r"()"r' am I'"??") + | + RUF039 [*] First argument to `regex.subn()` is not raw string --> RUF039_concat.py:78:24 @@ -417,11 +360,8 @@ RUF039 [*] First argument to `regex.subn()` is not raw string | ^^^^ help: Replace with raw string | -77 | ) - - regex.subn("()"r' am I'"??") -78 + regex.subn("()"r' am I'r"??") -79 | - | +78 | regex.subn("()"r' am I'r"??") + | + RUF039 [*] First argument to `re.compile()` is not raw string --> RUF039_concat.py:98:5 @@ -435,11 +375,8 @@ RUF039 [*] First argument to `re.compile()` is not raw string | help: Replace with raw string | -97 | re.compile( - - "[" -98 + r"[" -99 | "\U0001F600-\U0001F64F" # emoticons - | +98 | r"[" + | + RUF039 [*] First argument to `re.compile()` is not raw string --> RUF039_concat.py:99:5 @@ -452,12 +389,9 @@ RUF039 [*] First argument to `re.compile()` is not raw string 101 | "\U0001F680-\U0001F6FF" # transport & map symbols | help: Replace with raw string - | -98 | "[" - - "\U0001F600-\U0001F64F" # emoticons -99 + r"\U0001F600-\U0001F64F" # emoticons -100 | "\U0001F300-\U0001F5FF" # symbols & pictographs - | + | +99 | r"\U0001F600-\U0001F64F" # emoticons + | + note: This is an unsafe fix and may change runtime behavior RUF039 [*] First argument to `re.compile()` is not raw string @@ -472,11 +406,8 @@ RUF039 [*] First argument to `re.compile()` is not raw string | help: Replace with raw string | -99 | "\U0001F600-\U0001F64F" # emoticons - - "\U0001F300-\U0001F5FF" # symbols & pictographs -100 + r"\U0001F300-\U0001F5FF" # symbols & pictographs -101 | "\U0001F680-\U0001F6FF" # transport & map symbols - | +100 | r"\U0001F300-\U0001F5FF" # symbols & pictographs + | + note: This is an unsafe fix and may change runtime behavior RUF039 [*] First argument to `re.compile()` is not raw string @@ -491,11 +422,8 @@ RUF039 [*] First argument to `re.compile()` is not raw string | help: Replace with raw string | -100 | "\U0001F300-\U0001F5FF" # symbols & pictographs - - "\U0001F680-\U0001F6FF" # transport & map symbols -101 + r"\U0001F680-\U0001F6FF" # transport & map symbols -102 | "\U0001F1E0-\U0001F1FF" # flags (iOS) - | +101 | r"\U0001F680-\U0001F6FF" # transport & map symbols + | + note: This is an unsafe fix and may change runtime behavior RUF039 [*] First argument to `re.compile()` is not raw string @@ -510,11 +438,8 @@ RUF039 [*] First argument to `re.compile()` is not raw string | help: Replace with raw string | -101 | "\U0001F680-\U0001F6FF" # transport & map symbols - - "\U0001F1E0-\U0001F1FF" # flags (iOS) -102 + r"\U0001F1E0-\U0001F1FF" # flags (iOS) -103 | "\U00002702-\U000027B0" - | +102 | r"\U0001F1E0-\U0001F1FF" # flags (iOS) + | + note: This is an unsafe fix and may change runtime behavior RUF039 [*] First argument to `re.compile()` is not raw string @@ -529,11 +454,8 @@ RUF039 [*] First argument to `re.compile()` is not raw string | help: Replace with raw string | -102 | "\U0001F1E0-\U0001F1FF" # flags (iOS) - - "\U00002702-\U000027B0" -103 + r"\U00002702-\U000027B0" -104 | "\U000024C2-\U0001F251" - | +103 | r"\U00002702-\U000027B0" + | + note: This is an unsafe fix and may change runtime behavior RUF039 [*] First argument to `re.compile()` is not raw string @@ -548,11 +470,8 @@ RUF039 [*] First argument to `re.compile()` is not raw string | help: Replace with raw string | -103 | "\U00002702-\U000027B0" - - "\U000024C2-\U0001F251" -104 + r"\U000024C2-\U0001F251" -105 | "\u200d" # zero width joiner - | +104 | r"\U000024C2-\U0001F251" + | + note: This is an unsafe fix and may change runtime behavior RUF039 [*] First argument to `re.compile()` is not raw string @@ -567,11 +486,8 @@ RUF039 [*] First argument to `re.compile()` is not raw string | help: Replace with raw string | -104 | "\U000024C2-\U0001F251" - - "\u200d" # zero width joiner -105 + r"\u200d" # zero width joiner -106 | "\u200c" # zero width non-joiner - | +105 | r"\u200d" # zero width joiner + | + note: This is an unsafe fix and may change runtime behavior RUF039 [*] First argument to `re.compile()` is not raw string @@ -586,11 +502,8 @@ RUF039 [*] First argument to `re.compile()` is not raw string | help: Replace with raw string | -105 | "\u200d" # zero width joiner - - "\u200c" # zero width non-joiner -106 + r"\u200c" # zero width non-joiner -107 | "\\u200c" # must not be escaped in a raw string - | +106 | r"\u200c" # zero width non-joiner + | + note: This is an unsafe fix and may change runtime behavior RUF039 First argument to `re.compile()` is not raw string @@ -617,8 +530,5 @@ RUF039 [*] First argument to `re.compile()` is not raw string | help: Replace with raw string | -107 | "\\u200c" # must not be escaped in a raw string - - "]+", -108 + r"]+", -109 | flags=re.UNICODE, - | +108 | r"]+", + | + diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF055_RUF055_0.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF055_RUF055_0.py.snap index ac6a7f9132c92..055950c2690dd 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF055_RUF055_0.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF055_RUF055_0.py.snap @@ -9,10 +9,8 @@ RUF055 [*] Plain string pattern passed to `re` function | ^^^^^^^^^^^^^^^^^^^^ help: Replace with `s.replace("abc", "")` | -5 | # this should be replaced with `s.replace("abc", "")` - - re.sub("abc", "", s) +6 - re.sub("abc", "", s) 6 + s.replace("abc", "") -7 | | RUF055 [*] Plain string pattern passed to `re` function @@ -27,10 +25,8 @@ RUF055 [*] Plain string pattern passed to `re` function | help: Replace with `s.startswith("abc")` | -21 | # used in an if context for its truth value - - if re.match("abc", s): +22 - if re.match("abc", s): 22 + if s.startswith("abc"): -23 | pass | RUF055 [*] Plain string pattern passed to `re` function @@ -44,10 +40,8 @@ RUF055 [*] Plain string pattern passed to `re` function | help: Replace with `"abc" in s` | -28 | # this should be replaced with `"abc" in s` - - if re.search("abc", s): +29 - if re.search("abc", s): 29 + if "abc" in s: -30 | pass | RUF055 [*] Plain string pattern passed to `re` function @@ -61,10 +55,8 @@ RUF055 [*] Plain string pattern passed to `re` function | help: Replace with `s == "abc"` | -33 | # this should be replaced with `"abc" == s` - - if re.fullmatch("abc", s): +34 - if re.fullmatch("abc", s): 34 + if s == "abc": -35 | pass | RUF055 [*] Plain string pattern passed to `re` function @@ -78,10 +70,8 @@ RUF055 [*] Plain string pattern passed to `re` function | help: Replace with `s.split("abc")` | -38 | # this should be replaced with `s.split("abc")` - - re.split("abc", s) +39 - re.split("abc", s) 39 + s.split("abc") -40 | | RUF055 [*] Plain string pattern passed to `re` function @@ -101,16 +91,14 @@ RUF055 [*] Plain string pattern passed to `re` function | help: Replace with `s.replace("abc", "")` | -70 | # this should trigger an unsafe fix because of the presence of comments - - re.sub( - - # pattern - - "abc", - - # repl - - "", - - s, # string - - ) +71 - re.sub( +72 - # pattern +73 - "abc", +74 - # repl +75 - "", +76 - s, # string +77 - ) 71 + s.replace("abc", "") -72 | | note: This is an unsafe fix and may change runtime behavior @@ -126,10 +114,8 @@ RUF055 [*] Plain string pattern passed to `re` function | help: Replace with `"a".replace(r"a", "\n")` | -88 | # We currently emit diagnostics for some of these without fixing them. - - re.sub(r"a", "\n", "a") +89 - re.sub(r"a", "\n", "a") 89 + "a".replace(r"a", "\n") -90 | re.sub(r"a", r"\n", "a") | RUF055 Plain string pattern passed to `re` function @@ -154,10 +140,8 @@ RUF055 [*] Plain string pattern passed to `re` function | help: Replace with `"a".replace(r"a", "\x07")` | -90 | re.sub(r"a", r"\n", "a") - - re.sub(r"a", "\a", "a") +91 - re.sub(r"a", "\a", "a") 91 + "a".replace(r"a", "\x07") -92 | re.sub(r"a", r"\a", "a") | RUF055 Plain string pattern passed to `re` function @@ -182,10 +166,8 @@ RUF055 [*] Plain string pattern passed to `re` function | help: Replace with `"a".replace(r"a", "\\?")` | -93 | - - re.sub(r"a", "\?", "a") +94 - re.sub(r"a", "\?", "a") 94 + "a".replace(r"a", "\\?") -95 | re.sub(r"a", r"\?", "a") | RUF055 [*] Plain string pattern passed to `re` function @@ -199,10 +181,8 @@ RUF055 [*] Plain string pattern passed to `re` function | help: Replace with `"a".replace(r"a", r"\?")` | -94 | re.sub(r"a", "\?", "a") - - re.sub(r"a", r"\?", "a") +95 - re.sub(r"a", r"\?", "a") 95 + "a".replace(r"a", r"\?") -96 | | RUF055 [*] Plain string pattern passed to `re` function @@ -216,10 +196,8 @@ RUF055 [*] Plain string pattern passed to `re` function | help: Replace with `s.replace(r'abc', "")` | -97 | # these double as tests for preserving raw string quoting style - - re.sub(r'abc', "", s) +98 - re.sub(r'abc', "", s) 98 + s.replace(r'abc', "") -99 | re.sub(r"""abc""", "", s) | RUF055 [*] Plain string pattern passed to `re` function @@ -232,12 +210,10 @@ RUF055 [*] Plain string pattern passed to `re` function 100 | re.sub(r'''abc''', "", s) | help: Replace with `s.replace(r"""abc""", "")` - | -98 | re.sub(r'abc', "", s) - - re.sub(r"""abc""", "", s) -99 + s.replace(r"""abc""", "") -100 | re.sub(r'''abc''', "", s) - | + | +99 - re.sub(r"""abc""", "", s) +99 + s.replace(r"""abc""", "") + | RUF055 [*] Plain string pattern passed to `re` function --> RUF055_0.py:100:1 @@ -251,8 +227,6 @@ RUF055 [*] Plain string pattern passed to `re` function | help: Replace with `s.replace(r'''abc''', "")` | -99 | re.sub(r"""abc""", "", s) - - re.sub(r'''abc''', "", s) +100 - re.sub(r'''abc''', "", s) 100 + s.replace(r'''abc''', "") -101 | | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF055_RUF055_1.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF055_RUF055_1.py.snap index 2d02880aef2f2..478e4bad939b6 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF055_RUF055_1.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF055_RUF055_1.py.snap @@ -12,12 +12,10 @@ RUF055 [*] Plain string pattern passed to `re` function 11 | # aliases are not followed, so this one should not trigger the rule | help: Replace with `haystack.replace(pat1, "")` - | -8 | - - re.sub(pat1, "", haystack) -9 + haystack.replace(pat1, "") -10 | - | + | +9 - re.sub(pat1, "", haystack) +9 + haystack.replace(pat1, "") + | RUF055 [*] Plain string pattern passed to `re` function --> RUF055_1.py:17:1 @@ -28,7 +26,6 @@ RUF055 [*] Plain string pattern passed to `re` function | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `haystack.replace(r"abc", repl)` | -16 | repl = "new" - - re.sub(r"abc", repl, haystack) +17 - re.sub(r"abc", repl, haystack) 17 + haystack.replace(r"abc", repl) | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF055_RUF055_2.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF055_RUF055_2.py.snap index 65f47a6a8d4eb..7617e31e369f4 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF055_RUF055_2.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF055_RUF055_2.py.snap @@ -9,10 +9,8 @@ RUF055 [*] Plain string pattern passed to `re` function | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `"abc" not in s` | -6 | # this should be replaced with `"abc" not in s` - - re.search("abc", s) is None +7 - re.search("abc", s) is None 7 + "abc" not in s -8 | | RUF055 [*] Plain string pattern passed to `re` function @@ -23,10 +21,8 @@ RUF055 [*] Plain string pattern passed to `re` function | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `"abc" in s` | -10 | # this should be replaced with `"abc" in s` - - re.search("abc", s) is not None +11 - re.search("abc", s) is not None 11 + "abc" in s -12 | | RUF055 [*] Plain string pattern passed to `re` function @@ -37,10 +33,8 @@ RUF055 [*] Plain string pattern passed to `re` function | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `not s.startswith("abc")` | -14 | # this should be replaced with `not s.startswith("abc")` - - re.match("abc", s) is None +15 - re.match("abc", s) is None 15 + not s.startswith("abc") -16 | | RUF055 [*] Plain string pattern passed to `re` function @@ -51,10 +45,8 @@ RUF055 [*] Plain string pattern passed to `re` function | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `s.startswith("abc")` | -18 | # this should be replaced with `s.startswith("abc")` - - re.match("abc", s) is not None +19 - re.match("abc", s) is not None 19 + s.startswith("abc") -20 | | RUF055 [*] Plain string pattern passed to `re` function @@ -65,10 +57,8 @@ RUF055 [*] Plain string pattern passed to `re` function | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `s != "abc"` | -22 | # this should be replaced with `s != "abc"` - - re.fullmatch("abc", s) is None +23 - re.fullmatch("abc", s) is None 23 + s != "abc" -24 | | RUF055 [*] Plain string pattern passed to `re` function @@ -79,10 +69,8 @@ RUF055 [*] Plain string pattern passed to `re` function | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `s == "abc"` | -26 | # this should be replaced with `s == "abc"` - - re.fullmatch("abc", s) is not None +27 - re.fullmatch("abc", s) is not None 27 + s == "abc" -28 | | RUF055 [*] Plain string pattern passed to `re` function @@ -102,15 +90,13 @@ RUF055 [*] Plain string pattern passed to `re` function | help: Replace with `s != "a really really really really long string"` | -32 | if ( - - re.fullmatch( - - "a really really really really long string", - - s, - - ) - - # with a comment here - - is None +33 - re.fullmatch( +34 - "a really really really really long string", +35 - s, +36 - ) +37 - # with a comment here +38 - is None 33 + s != "a really really really really long string" -34 | ): | note: This is an unsafe fix and may change runtime behavior @@ -130,12 +116,10 @@ RUF055 [*] Plain string pattern passed to `re` function | help: Replace with `s != "a really really really really long string"` | -45 | if ( # leading - - re.fullmatch( - - "a really really really really long string", - - s, - - ) - - is None # trailing +46 - re.fullmatch( +47 - "a really really really really long string", +48 - s, +49 - ) +50 - is None # trailing 46 + s != "a really really really really long string" # trailing -47 | ): | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF055_RUF055_3.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF055_RUF055_3.py.snap index ba10db356534e..78f5a0da2d358 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF055_RUF055_3.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF055_RUF055_3.py.snap @@ -12,10 +12,8 @@ RUF055 [*] Plain string pattern passed to `re` function | help: Replace with `b_src.replace(rb"x", b"y")` | -5 | # Should be replaced with `b_src.replace(rb"x", b"y")` - - re.sub(rb"x", b"y", b_src) +6 - re.sub(rb"x", b"y", b_src) 6 + b_src.replace(rb"x", b"y") -7 | | RUF055 [*] Plain string pattern passed to `re` function @@ -27,12 +25,10 @@ RUF055 [*] Plain string pattern passed to `re` function 10 | pass | help: Replace with `b_src.startswith(rb"abc")` - | -8 | # Should be replaced with `b_src.startswith(rb"abc")` - - if re.match(rb"abc", b_src): -9 + if b_src.startswith(rb"abc"): -10 | pass - | + | +9 - if re.match(rb"abc", b_src): +9 + if b_src.startswith(rb"abc"): + | RUF055 [*] Plain string pattern passed to `re` function --> RUF055_3.py:13:4 @@ -44,10 +40,8 @@ RUF055 [*] Plain string pattern passed to `re` function | help: Replace with `rb"x" in b_src` | -12 | # Should be replaced with `rb"x" in b_src` - - if re.search(rb"x", b_src): +13 - if re.search(rb"x", b_src): 13 + if rb"x" in b_src: -14 | pass | RUF055 [*] Plain string pattern passed to `re` function @@ -61,8 +55,6 @@ RUF055 [*] Plain string pattern passed to `re` function | help: Replace with `b_src.split(rb"abc")` | -16 | # Should be replaced with `b_src.split(rb"abc")` - - re.split(rb"abc", b_src) +17 - re.split(rb"abc", b_src) 17 + b_src.split(rb"abc") -18 | | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF070_RUF070.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF070_RUF070.py.snap index a7233c248bda3..1f9e6e91e9585 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF070_RUF070.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF070_RUF070.py.snap @@ -13,11 +13,10 @@ RUF070 [*] Unnecessary assignment to `x` before `yield` statement | help: Remove unnecessary assignment | -5 | def foo(): - - x = 1 - - yield x # RUF070 +6 - x = 1 +7 - yield x # RUF070 +8 - 6 + yield 1 -7 | | note: This is an unsafe fix and may change runtime behavior @@ -33,11 +32,10 @@ RUF070 [*] Unnecessary assignment to `x` before `yield from` statement | help: Remove unnecessary assignment | -9 | def foo(): - - x = [1, 2, 3] - - yield from x # RUF070 +10 - x = [1, 2, 3] +11 - yield from x # RUF070 +12 - 10 + yield from [1, 2, 3] -11 | | note: This is an unsafe fix and may change runtime behavior @@ -53,11 +51,10 @@ RUF070 [*] Unnecessary assignment to `x` before `yield` statement | help: Remove unnecessary assignment | -14 | for i in range(10): - - x = i * 2 - - yield x # RUF070 +15 - x = i * 2 +16 - yield x # RUF070 +17 - 15 + yield i * 2 -16 | | note: This is an unsafe fix and may change runtime behavior @@ -73,11 +70,10 @@ RUF070 [*] Unnecessary assignment to `x` before `yield` statement | help: Remove unnecessary assignment | -19 | if True: - - x = 1 - - yield x # RUF070 +20 - x = 1 +21 - yield x # RUF070 +22 - 20 + yield 1 -21 | | note: This is an unsafe fix and may change runtime behavior @@ -93,11 +89,10 @@ RUF070 [*] Unnecessary assignment to `x` before `yield` statement | help: Remove unnecessary assignment | -24 | with open("foo.txt") as f: - - x = f.read() - - yield x # RUF070 +25 - x = f.read() +26 - yield x # RUF070 +27 - 25 + yield f.read() -26 | | note: This is an unsafe fix and may change runtime behavior @@ -113,11 +108,10 @@ RUF070 [*] Unnecessary assignment to `x` before `yield` statement | help: Remove unnecessary assignment | -29 | try: - - x = something() - - yield x # RUF070 +30 - x = something() +31 - yield x # RUF070 +32 - except Exception: 30 + yield something() -31 | except Exception: | note: This is an unsafe fix and may change runtime behavior @@ -133,11 +127,10 @@ RUF070 [*] Unnecessary assignment to `x` before `yield` statement | help: Remove unnecessary assignment | -35 | def foo(): - - x = some_function() - - yield x # RUF070 +36 - x = some_function() +37 - yield x # RUF070 +38 - 36 + yield some_function() -37 | | note: This is an unsafe fix and may change runtime behavior @@ -153,11 +146,10 @@ RUF070 [*] Unnecessary assignment to `x` before `yield from` statement | help: Remove unnecessary assignment | -39 | def foo(): - - x = some_generator() - - yield from x # RUF070 +40 - x = some_generator() +41 - yield from x # RUF070 +42 - 40 + yield from some_generator() -41 | | note: This is an unsafe fix and may change runtime behavior @@ -173,11 +165,10 @@ RUF070 [*] Unnecessary assignment to `x` before `yield` statement | help: Remove unnecessary assignment | -43 | def foo(): - - x = lambda: 1 - - yield x # RUF070 +44 - x = lambda: 1 +45 - yield x # RUF070 +46 - 44 + yield lambda: 1 -45 | | note: This is an unsafe fix and may change runtime behavior @@ -193,11 +184,10 @@ RUF070 [*] Unnecessary assignment to `x` before `yield` statement | help: Remove unnecessary assignment | -47 | def foo(): - - x = (y := 1) - - yield x # RUF070 +48 - x = (y := 1) +49 - yield x # RUF070 +50 - 48 + yield (y := 1) -49 | | note: This is an unsafe fix and may change runtime behavior @@ -213,11 +203,10 @@ RUF070 [*] Unnecessary assignment to `x` before `yield` statement | help: Remove unnecessary assignment | -51 | def foo(): - - x =1 - - yield x # RUF070 (no space after `=`) +52 - x =1 +53 - yield x # RUF070 (no space after `=`) +54 - 52 + yield 1 -53 | | note: This is an unsafe fix and may change runtime behavior @@ -233,11 +222,10 @@ RUF070 [*] Unnecessary assignment to `x` before `yield` statement | help: Remove unnecessary assignment | -55 | def foo(): - - x = yield 1 - - yield x # RUF070 (yield as assigned value, fix adds parentheses) +56 - x = yield 1 +57 - yield x # RUF070 (yield as assigned value, fix adds parentheses) +58 - 56 + yield (yield 1) -57 | | note: This is an unsafe fix and may change runtime behavior @@ -250,10 +238,9 @@ RUF070 [*] Unnecessary assignment to `x` before `yield` statement | ^ help: Remove unnecessary assignment | -61 | with open("foo.txt") as f: - - x = f.read() - - yield x # RUF070 +62 - x = f.read() +63 - yield x # RUF070 +64 - 62 + yield f.read() -63 | | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF071_RUF071.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF071_RUF071.py.snap index 7ca0c4e421f59..506c81b7b026a 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF071_RUF071.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF071_RUF071.py.snap @@ -12,10 +12,11 @@ RUF071 [*] `os.path.commonprefix()` compares strings character-by-character | help: Use `os.path.commonpath()` to compare path components | +2 ~ import os.path +3 | from os.path import commonprefix +… 6 | # Errors - - os.path.commonprefix(["/usr/lib", "/usr/local/lib"]) -7 + os.path.commonpath(["/usr/lib", "/usr/local/lib"]) -8 | commonprefix(["/usr/lib", "/usr/local/lib"]) +7 ~ os.path.commonpath(["/usr/lib", "/usr/local/lib"]) | note: This is an unsafe fix and may change runtime behavior @@ -30,10 +31,11 @@ RUF071 [*] `os.path.commonprefix()` compares strings character-by-character | help: Use `os.path.commonpath()` to compare path components | +2 ~ import os.path +3 | from os.path import commonprefix +… 7 | os.path.commonprefix(["/usr/lib", "/usr/local/lib"]) - - commonprefix(["/usr/lib", "/usr/local/lib"]) -8 + os.path.commonpath(["/usr/lib", "/usr/local/lib"]) -9 | path.commonprefix(["/usr/lib", "/usr/local/lib"]) +8 ~ os.path.commonpath(["/usr/lib", "/usr/local/lib"]) | note: This is an unsafe fix and may change runtime behavior @@ -48,10 +50,11 @@ RUF071 [*] `os.path.commonprefix()` compares strings character-by-character 11 | # OK | help: Use `os.path.commonpath()` to compare path components - | -8 | commonprefix(["/usr/lib", "/usr/local/lib"]) - - path.commonprefix(["/usr/lib", "/usr/local/lib"]) -9 + os.path.commonpath(["/usr/lib", "/usr/local/lib"]) -10 | - | + | +2 ~ import os.path +3 | from os.path import commonprefix +… +8 | commonprefix(["/usr/lib", "/usr/local/lib"]) +9 ~ os.path.commonpath(["/usr/lib", "/usr/local/lib"]) + | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF072_RUF072.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF072_RUF072.py.snap index fbb131c11363e..e649abe1e98b4 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF072_RUF072.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__RUF072_RUF072.py.snap @@ -13,12 +13,10 @@ RUF072 [*] Empty `finally` clause 11 | # try/except/finally with ellipsis | help: Remove the `finally` clause - | -7 | bar() - - finally: - - pass -8 | - | + | + 8 - finally: + 9 - pass + | RUF072 [*] Empty `finally` clause --> RUF072.py:16:1 @@ -33,10 +31,8 @@ RUF072 [*] Empty `finally` clause | help: Remove the `finally` clause | -15 | bar() - - finally: - - ... -16 | +16 - finally: +17 - ... | RUF072 [*] Empty `finally` clause @@ -52,10 +48,8 @@ RUF072 [*] Empty `finally` clause | help: Remove the `finally` clause | -25 | baz() - - finally: - - pass -26 | +26 - finally: +27 - pass | RUF072 [*] Empty `finally` clause @@ -71,13 +65,12 @@ RUF072 [*] Empty `finally` clause | help: Remove the `finally` clause | -29 | # bare try/finally with pass - - try: - - foo() - - finally: - - pass +30 - try: +31 - foo() +32 - finally: +33 - pass +34 - 30 + foo() -31 | | RUF072 [*] Empty `finally` clause @@ -93,13 +86,12 @@ RUF072 [*] Empty `finally` clause | help: Remove the `finally` clause | -35 | # bare try/finally with ellipsis - - try: - - foo() - - finally: - - ... +36 - try: +37 - foo() +38 - finally: +39 - ... +40 - 36 + foo() -37 | | RUF072 [*] Empty `finally` clause @@ -115,17 +107,9 @@ RUF072 [*] Empty `finally` clause | help: Remove the `finally` clause | -41 | # bare try/finally with multi-line body - - try: - - foo() - - bar() - - baz() - - finally: - - pass 42 + foo() 43 + bar() 44 + baz() -45 | | RUF072 [*] Empty `finally` clause @@ -141,13 +125,12 @@ RUF072 [*] Empty `finally` clause | help: Remove the `finally` clause | -50 | try: - - try: - - foo() - - finally: - - pass +51 - try: +52 - foo() +53 - finally: +54 - pass +55 - except Exception: 51 + foo() -52 | except Exception: | RUF072 [*] Empty `finally` clause @@ -164,11 +147,9 @@ RUF072 [*] Empty `finally` clause | help: Remove the `finally` clause | -62 | bar() - - finally: - - pass - - pass -63 | +63 - finally: +64 - pass +65 - pass | RUF072 [*] Empty `finally` clause @@ -185,14 +166,13 @@ RUF072 [*] Empty `finally` clause | help: Remove the `finally` clause | -67 | # bare try/finally with pass and ellipsis - - try: - - foo() - - finally: - - pass - - ... +68 - try: +69 - foo() +70 - finally: +71 - pass +72 - ... +73 - 68 + foo() -69 | | RUF072 Empty `finally` clause @@ -321,15 +301,8 @@ RUF072 [*] Empty `finally` clause | |________^ help: Remove the `finally` clause | -174 | # Bare try finally with line starting with a formfeed - - try: - - 1 - - 2 - - finally: - - pass -175 + 1 +175 + ␌1 176 + 2 -177 | | RUF072 [*] Empty `finally` clause @@ -342,10 +315,9 @@ RUF072 [*] Empty `finally` clause | |________^ help: Remove the `finally` clause | -183 | # (`try` is preceded by a form feed below) - - try: - - 1 - - finally: - - pass +184 - ␌try: +185 - 1 +186 - finally: +187 - pass 184 + 1 | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__py38__RUF039_RUF039_py_version_sensitive.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__py38__RUF039_RUF039_py_version_sensitive.py.snap index db5e3c79f8326..52ace74cbf6f4 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__py38__RUF039_RUF039_py_version_sensitive.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__preview__py38__RUF039_RUF039_py_version_sensitive.py.snap @@ -10,8 +10,6 @@ RUF039 [*] First argument to `re.compile()` is not raw string | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with raw string | -2 | - - re.compile("\N{Partial Differential}") # with unsafe fix if python target is 3.8 or higher, else without fix -3 + re.compile(r"\N{Partial Differential}") # with unsafe fix if python target is 3.8 or higher, else without fix - | +3 | re.compile(r"\N{Partial Differential}") # with unsafe fix if python target is 3.8 or higher, else without fix + | + note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__py314__RUF058_RUF058_2.py.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__py314__RUF058_RUF058_2.py.snap index 3762a50a11a32..0a8bfe9929914 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__py314__RUF058_RUF058_2.py.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__py314__RUF058_RUF058_2.py.snap @@ -12,10 +12,8 @@ RUF058 [*] `itertools.starmap` called on `zip` iterable | help: Use `map` instead | -4 | # Errors in Python 3.14+ - - starmap(func, zip(a, b, c, strict=True)) +5 - starmap(func, zip(a, b, c, strict=True)) 5 + map(func, a, b, c, strict=True) -6 | starmap(func, zip(a, b, c, strict=False)) | RUF058 [*] `itertools.starmap` called on `zip` iterable @@ -29,10 +27,8 @@ RUF058 [*] `itertools.starmap` called on `zip` iterable | help: Use `map` instead | -5 | starmap(func, zip(a, b, c, strict=True)) - - starmap(func, zip(a, b, c, strict=False)) +6 - starmap(func, zip(a, b, c, strict=False)) 6 + map(func, a, b, c, strict=False) -7 | starmap(func, zip(a, b, c, strict=strict)) | RUF058 [*] `itertools.starmap` called on `zip` iterable @@ -44,8 +40,6 @@ RUF058 [*] `itertools.starmap` called on `zip` iterable | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Use `map` instead | -6 | starmap(func, zip(a, b, c, strict=False)) - - starmap(func, zip(a, b, c, strict=strict)) +7 - starmap(func, zip(a, b, c, strict=strict)) 7 + map(func, a, b, c, strict=strict) -8 | | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__range_suppressions.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__range_suppressions.snap index c65ef006ef1b9..b8ccb359c90d1 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__range_suppressions.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__range_suppressions.snap @@ -32,10 +32,8 @@ F841 [*] Local variable `I` is assigned to but never used | help: Remove assignment to unused variable `I` | -17 | # should be generated. - - I = 1 +18 - I = 1 18 + pass -19 | # ruff: enable[E741, F841] | note: This is an unsafe fix and may change runtime behavior @@ -48,9 +46,7 @@ RUF103 [*] Invalid suppression comment: no matching 'disable' comment | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove suppression comment | -18 | I = 1 - - # ruff: enable[E741, F841] -19 | +19 - # ruff: enable[E741, F841] | note: This is an unsafe fix and may change runtime behavior @@ -65,10 +61,8 @@ F841 [*] Local variable `I` is assigned to but never used | help: Remove assignment to unused variable `I` | -25 | # ruff: disable[E741] - - I = 1 +26 - I = 1 26 + pass -27 | # ruff: enable[E741] | note: This is an unsafe fix and may change runtime behavior @@ -84,9 +78,7 @@ F841 [*] Local variable `l` is assigned to but never used | help: Remove assignment to unused variable `l` | -34 | # ruff: disable[E741] - - l = 0 -35 | # ruff: disable[F841] +35 - l = 0 | note: This is an unsafe fix and may change runtime behavior @@ -112,11 +104,7 @@ RUF100 [*] Unused suppression (non-enabled: `E501`) | -------------------- help: Remove unused suppression | -45 | # An unused suppression diagnostic should also be logged. - - # ruff: disable[E501] -46 | I = 1 - - # ruff: enable[E501] -47 | +46 + | E741 Ambiguous variable name: `I` @@ -140,10 +128,8 @@ F841 [*] Local variable `I` is assigned to but never used | help: Remove assignment to unused variable `I` | -46 | # ruff: disable[E501] - - I = 1 +47 - I = 1 47 + pass -48 | # ruff: enable[E501] | note: This is an unsafe fix and may change runtime behavior @@ -158,10 +144,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E741`, `F841`) | help: Remove unused `noqa` directive | -54 | # ruff:disable[E741,F841] - - I = 1 # noqa: E741,F841 +55 - I = 1 # noqa: E741,F841 55 + I = 1 -56 | # ruff:enable[E741,F841] | RUF104 Suppression comment without matching `#ruff:enable` comment @@ -185,10 +169,8 @@ RUF100 [*] Unused suppression (duplicated: `F841`) | help: Remove unused suppression | -60 | # Duplicate codes that are actually used. - - # ruff: disable[F841, F841] +61 - # ruff: disable[F841, F841] 61 + # ruff: disable[F841] -62 | foo = 0 | RUF104 Suppression comment without matching `#ruff:enable` comment @@ -213,9 +195,7 @@ RUF100 [*] Unused suppression (unused: `F841`) | help: Remove unused suppression | -68 | # ruff: disable[F841] - - # ruff: disable[F841] -69 | foo = 0 +69 - # ruff: disable[F841] | RUF104 Suppression comment without matching `#ruff:enable` comment @@ -239,10 +219,8 @@ RUF100 [*] Unused suppression (unused: `E741`; non-enabled: `F401`) | help: Remove unused suppression | -74 | # Multiple codes but only one is used - - # ruff: disable[E741, F401, F841] +75 - # ruff: disable[E741, F401, F841] 75 + # ruff: disable[F841] -76 | foo = 0 | RUF104 Suppression comment without matching `#ruff:enable` comment @@ -266,10 +244,8 @@ RUF100 [*] Unused suppression (non-enabled: `F401`) | help: Remove unused suppression | -80 | # Multiple codes but only two are used - - # ruff: disable[E741, F401, F841] +81 - # ruff: disable[E741, F401, F841] 81 + # ruff: disable[E741, F841] -82 | I = 0 | RUF100 [*] Unused suppression (unused: `E741`, `F841`; non-enabled: `F401`) @@ -283,9 +259,7 @@ RUF100 [*] Unused suppression (unused: `E741`, `F841`; non-enabled: `F401`) | help: Remove unused suppression | -86 | # Multiple codes but none are used - - # ruff: disable[E741, F401, F841] -87 | print("hello") +87 - # ruff: disable[E741, F401, F841] | RUF102 [*] Invalid rule code in suppression: YF829 @@ -303,13 +277,7 @@ RUF102 [*] Invalid rule code in suppression: YF829 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the suppression comment | -92 | # Unknown rule codes - - # ruff: disable[YF829] -93 | # ruff: disable[F841, RQW320] -94 | value = 0 -95 | # ruff: enable[F841, RQW320] - - # ruff: enable[YF829] -96 | +93 + | RUF102 [*] Invalid rule code in suppression: RQW320 @@ -327,13 +295,9 @@ RUF102 [*] Invalid rule code in suppression: RQW320 help: Add non-Ruff rule codes to the `lint.external` configuration option help: Remove the rule code `RQW320` | -93 | # ruff: disable[YF829] - - # ruff: disable[F841, RQW320] -94 + # ruff: disable[F841] +94 ~ # ruff: disable[F841] 95 | value = 0 - - # ruff: enable[F841, RQW320] -96 + # ruff: enable[F841] -97 | # ruff: enable[YF829] +96 ~ # ruff: enable[F841] | RUF103 [*] Invalid suppression comment: missing suppression codes like `[E501, ...]` @@ -348,9 +312,7 @@ RUF103 [*] Invalid suppression comment: missing suppression codes like `[E501, . | help: Remove suppression comment | -108 | # Empty or missing rule codes - - # ruff: disable -109 | # ruff: disable[] +109 - # ruff: disable | note: This is an unsafe fix and may change runtime behavior @@ -365,9 +327,7 @@ RUF103 [*] Invalid suppression comment: missing suppression codes like `[E501, . | help: Remove suppression comment | -109 | # ruff: disable - - # ruff: disable[] -110 | print("hello") +110 - # ruff: disable[] | note: This is an unsafe fix and may change runtime behavior @@ -380,9 +340,7 @@ F841 [*] Local variable `bar` is assigned to but never used | ^^^ help: Remove assignment to unused variable `bar` | -117 | foo = 0 - - bar = 0 -118 | +118 - bar = 0 | note: This is an unsafe fix and may change runtime behavior @@ -395,9 +353,7 @@ F841 [*] Local variable `bar` is assigned to but never used | ^^^ help: Remove assignment to unused variable `bar` | -123 | foo = 0 # ruff: ignore[F841] - - bar = 0 -124 | +124 - bar = 0 | note: This is an unsafe fix and may change runtime behavior @@ -410,9 +366,7 @@ F841 [*] Local variable `bar` is assigned to but never used | ^^^ help: Remove assignment to unused variable `bar` | -131 | """ # ruff: ignore[F841] - - bar = 0 -132 | +132 - bar = 0 | note: This is an unsafe fix and may change runtime behavior @@ -449,10 +403,8 @@ RUF100 [*] Unused suppression (unused: `ARG001`) | help: Remove unused suppression | -160 | bar, - - ): # ruff: ignore[ARG001] should cover nothing and be marked as unused +161 - ): # ruff: ignore[ARG001] should cover nothing and be marked as unused 161 + ): -162 | pass | RUF100 [*] Unused suppression (unused: `ARG002`) @@ -466,9 +418,7 @@ RUF100 [*] Unused suppression (unused: `ARG002`) | help: Remove unused suppression | -165 | class Foo: - - # ruff: ignore[ARG002] should be unused due to file-ignore below -166 | def bar(self, arg1, arg2): +166 - # ruff: ignore[ARG002] should be unused due to file-ignore below | RUF100 [*] Unused suppression (non-enabled: `F401`) @@ -483,8 +433,5 @@ RUF100 [*] Unused suppression (non-enabled: `F401`) | ------------------- help: Remove unused suppression | -174 | # https://github.com/astral-sh/ruff/issues/23235 - - # ruff:disable[F401] -175 | print("goodbye") - - # ruff:enable[F401] +175 + | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_0.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_0.snap index 9925381435866..1756bbbbbf033 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_0.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_0.snap @@ -10,12 +10,10 @@ RUF100 [*] Unused blanket `noqa` directive 10 | print(c) | help: Remove unused `noqa` directive - | -8 | # Invalid - - c = 1 # noqa -9 + c = 1 -10 | print(c) - | + | +9 - c = 1 # noqa +9 + c = 1 + | RUF100 [*] Unused `noqa` directive (unused: `E501`) --> RUF100_0.py:13:12 @@ -28,10 +26,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`) | help: Remove unused `noqa` directive | -12 | # Invalid - - d = 1 # noqa: E501 +13 - d = 1 # noqa: E501 13 + d = 1 -14 | | RUF100 [*] Unused `noqa` directive (unused: `F841`, `E501`) @@ -45,10 +41,8 @@ RUF100 [*] Unused `noqa` directive (unused: `F841`, `E501`) | help: Remove unused `noqa` directive | -15 | # Invalid - - d = 1 # noqa: F841, E501 +16 - d = 1 # noqa: F841, E501 16 + d = 1 -17 | | RUF100 [*] Unused `noqa` directive (unused: `F841`, `W191`; non-enabled: `F821`) @@ -62,10 +56,8 @@ RUF100 [*] Unused `noqa` directive (unused: `F841`, `W191`; non-enabled: `F821`) | help: Remove unused `noqa` directive | -18 | # Invalid (and unimplemented or not enabled) - - d = 1 # noqa: F841, W191, F821 +19 - d = 1 # noqa: F841, W191, F821 19 + d = 1 -20 | | RUF100 [*] Unused `noqa` directive (unused: `F841`) @@ -79,10 +71,8 @@ RUF100 [*] Unused `noqa` directive (unused: `F841`) | help: Remove unused `noqa` directive | -21 | # Invalid (but external) - - d = 1 # noqa: F841, V101 +22 - d = 1 # noqa: F841, V101 22 + d = 1 # noqa: V101 -23 | | RUF100 [*] Unused `noqa` directive (unused: `E501`) @@ -97,10 +87,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`) | help: Remove unused `noqa` directive | -28 | # Invalid - no space before # - - d = 1 # noqa: E501 +29 - d = 1 # noqa: E501 29 + d = 1 -30 | | F841 [*] Local variable `d` is assigned to but never used @@ -113,9 +101,7 @@ F841 [*] Local variable `d` is assigned to but never used | help: Remove assignment to unused variable `d` | -31 | # Invalid - many spaces before # - - d = 1 # noqa: E501 -32 | # fmt: on +32 - d = 1 # noqa: E501 | note: This is an unsafe fix and may change runtime behavior @@ -129,10 +115,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`) | help: Remove unused `noqa` directive | -31 | # Invalid - many spaces before # - - d = 1 # noqa: E501 +32 - d = 1 # noqa: E501 32 + d = 1 -33 | # fmt: on | RUF100 [*] Unused `noqa` directive (unused: `F841`) @@ -146,10 +130,8 @@ RUF100 [*] Unused `noqa` directive (unused: `F841`) | help: Remove unused `noqa` directive | -57 | Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. - - """ # noqa: E501, F841 +58 - """ # noqa: E501, F841 58 + """ # noqa: E501 -59 | | RUF100 [*] Unused `noqa` directive (unused: `E501`) @@ -163,10 +145,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`) | help: Remove unused `noqa` directive | -65 | Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor. - - """ # noqa: E501 +66 - """ # noqa: E501 66 + """ -67 | | RUF100 [*] Unused blanket `noqa` directive @@ -180,10 +160,8 @@ RUF100 [*] Unused blanket `noqa` directive | help: Remove unused `noqa` directive | -73 | Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor. - - """ # noqa +74 - """ # noqa 74 + """ -75 | | F401 [*] `shelve` imported but unused @@ -197,9 +175,7 @@ F401 [*] `shelve` imported but unused | help: Remove unused import: `shelve` | -87 | import os # noqa: F401, RUF100 - - import shelve # noqa: RUF100 -88 | import sys # noqa: F401, RUF100 +88 - import shelve # noqa: RUF100 | E501 Line too long (89 > 88) @@ -219,10 +195,8 @@ RUF100 [*] Unused `noqa` directive (unused: `F401`) | ^^^^^^^^^^^^ help: Remove unused `noqa` directive | -92 | - - "shape: (6,)\nSeries: '' [duration[μs]]\n[\n\t0µs\n\t1µs\n\t2µs\n\t3µs\n\t4µs\n\t5µs\n]" # noqa: F401 +93 - "shape: (6,)\nSeries: '' [duration[μs]]\n[\n\t0µs\n\t1µs\n\t2µs\n\t3µs\n\t4µs\n\t5µs\n]" # noqa: F401 93 + "shape: (6,)\nSeries: '' [duration[μs]]\n[\n\t0µs\n\t1µs\n\t2µs\n\t3µs\n\t4µs\n\t5µs\n]" -94 | | F841 [*] Local variable `e` is assigned to but never used @@ -234,9 +208,7 @@ F841 [*] Local variable `e` is assigned to but never used | ^ help: Remove assignment to unused variable `e` | -107 | d = 1 # …noqa: F841, E50 - - e = 1 # …noqa: E50 -108 | +108 - e = 1 # …noqa: E50 | note: This is an unsafe fix and may change runtime behavior @@ -252,10 +224,8 @@ RUF100 [*] Unused `noqa` directive (duplicated: `F841`) | help: Remove unused `noqa` directive | -117 | def f(): - - x = 2 # noqa: F841, F841, X200 +118 - x = 2 # noqa: F841, F841, X200 118 + x = 2 # noqa: F841 -119 | | RUF100 [*] Unused `noqa` directive (duplicated: `SIM300`, `SIM300`) @@ -270,10 +240,8 @@ RUF100 [*] Unused `noqa` directive (duplicated: `SIM300`, `SIM300`) | help: Remove unused `noqa` directive | -119 | - - y = 2 == bar # noqa: SIM300, F841, SIM300, SIM300 +120 - y = 2 == bar # noqa: SIM300, F841, SIM300, SIM300 120 + y = 2 == bar # noqa: SIM300, F841 -121 | | RUF100 [*] Unused `noqa` directive (duplicated: `F841`, `F841`, `F841`, `F841`) @@ -288,10 +256,8 @@ RUF100 [*] Unused `noqa` directive (duplicated: `F841`, `F841`, `F841`, `F841`) | help: Remove unused `noqa` directive | -121 | - - z = 2 # noqa: F841 F841 F841, F841, F841 +122 - z = 2 # noqa: F841 F841 F841, F841, F841 122 + z = 2 # noqa: F841 -123 | | RUF100 [*] Unused `noqa` directive (duplicated: `S307`, `S307`, `S307`) @@ -306,10 +272,8 @@ RUF100 [*] Unused `noqa` directive (duplicated: `S307`, `S307`, `S307`) | help: Remove unused `noqa` directive | -128 | x = eval(command) # noqa: PGH001, S307 - - x = eval(command) # noqa: S307, PGH001, S307, S307, S307 +129 - x = eval(command) # noqa: S307, PGH001, S307, S307, S307 129 + x = eval(command) # noqa: S307, PGH001 -130 | x = eval(command) # noqa: PGH001, S307, PGH001 | RUF100 [*] Unused `noqa` directive (duplicated: `PGH001`) @@ -323,10 +287,8 @@ RUF100 [*] Unused `noqa` directive (duplicated: `PGH001`) | help: Remove unused `noqa` directive | -129 | x = eval(command) # noqa: S307, PGH001, S307, S307, S307 - - x = eval(command) # noqa: PGH001, S307, PGH001 +130 - x = eval(command) # noqa: PGH001, S307, PGH001 130 + x = eval(command) # noqa: PGH001, S307 -131 | x = eval(command) # noqa: PGH001, S307, PGH001, S307 | RUF100 [*] Unused `noqa` directive (duplicated: `PGH001`, `S307`) @@ -338,7 +300,6 @@ RUF100 [*] Unused `noqa` directive (duplicated: `PGH001`, `S307`) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove unused `noqa` directive | -130 | x = eval(command) # noqa: PGH001, S307, PGH001 - - x = eval(command) # noqa: PGH001, S307, PGH001, S307 +131 - x = eval(command) # noqa: PGH001, S307, PGH001, S307 131 + x = eval(command) # noqa: PGH001, S307 | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_0_prefix.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_0_prefix.snap index 9925381435866..1756bbbbbf033 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_0_prefix.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_0_prefix.snap @@ -10,12 +10,10 @@ RUF100 [*] Unused blanket `noqa` directive 10 | print(c) | help: Remove unused `noqa` directive - | -8 | # Invalid - - c = 1 # noqa -9 + c = 1 -10 | print(c) - | + | +9 - c = 1 # noqa +9 + c = 1 + | RUF100 [*] Unused `noqa` directive (unused: `E501`) --> RUF100_0.py:13:12 @@ -28,10 +26,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`) | help: Remove unused `noqa` directive | -12 | # Invalid - - d = 1 # noqa: E501 +13 - d = 1 # noqa: E501 13 + d = 1 -14 | | RUF100 [*] Unused `noqa` directive (unused: `F841`, `E501`) @@ -45,10 +41,8 @@ RUF100 [*] Unused `noqa` directive (unused: `F841`, `E501`) | help: Remove unused `noqa` directive | -15 | # Invalid - - d = 1 # noqa: F841, E501 +16 - d = 1 # noqa: F841, E501 16 + d = 1 -17 | | RUF100 [*] Unused `noqa` directive (unused: `F841`, `W191`; non-enabled: `F821`) @@ -62,10 +56,8 @@ RUF100 [*] Unused `noqa` directive (unused: `F841`, `W191`; non-enabled: `F821`) | help: Remove unused `noqa` directive | -18 | # Invalid (and unimplemented or not enabled) - - d = 1 # noqa: F841, W191, F821 +19 - d = 1 # noqa: F841, W191, F821 19 + d = 1 -20 | | RUF100 [*] Unused `noqa` directive (unused: `F841`) @@ -79,10 +71,8 @@ RUF100 [*] Unused `noqa` directive (unused: `F841`) | help: Remove unused `noqa` directive | -21 | # Invalid (but external) - - d = 1 # noqa: F841, V101 +22 - d = 1 # noqa: F841, V101 22 + d = 1 # noqa: V101 -23 | | RUF100 [*] Unused `noqa` directive (unused: `E501`) @@ -97,10 +87,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`) | help: Remove unused `noqa` directive | -28 | # Invalid - no space before # - - d = 1 # noqa: E501 +29 - d = 1 # noqa: E501 29 + d = 1 -30 | | F841 [*] Local variable `d` is assigned to but never used @@ -113,9 +101,7 @@ F841 [*] Local variable `d` is assigned to but never used | help: Remove assignment to unused variable `d` | -31 | # Invalid - many spaces before # - - d = 1 # noqa: E501 -32 | # fmt: on +32 - d = 1 # noqa: E501 | note: This is an unsafe fix and may change runtime behavior @@ -129,10 +115,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`) | help: Remove unused `noqa` directive | -31 | # Invalid - many spaces before # - - d = 1 # noqa: E501 +32 - d = 1 # noqa: E501 32 + d = 1 -33 | # fmt: on | RUF100 [*] Unused `noqa` directive (unused: `F841`) @@ -146,10 +130,8 @@ RUF100 [*] Unused `noqa` directive (unused: `F841`) | help: Remove unused `noqa` directive | -57 | Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. - - """ # noqa: E501, F841 +58 - """ # noqa: E501, F841 58 + """ # noqa: E501 -59 | | RUF100 [*] Unused `noqa` directive (unused: `E501`) @@ -163,10 +145,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`) | help: Remove unused `noqa` directive | -65 | Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor. - - """ # noqa: E501 +66 - """ # noqa: E501 66 + """ -67 | | RUF100 [*] Unused blanket `noqa` directive @@ -180,10 +160,8 @@ RUF100 [*] Unused blanket `noqa` directive | help: Remove unused `noqa` directive | -73 | Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor. - - """ # noqa +74 - """ # noqa 74 + """ -75 | | F401 [*] `shelve` imported but unused @@ -197,9 +175,7 @@ F401 [*] `shelve` imported but unused | help: Remove unused import: `shelve` | -87 | import os # noqa: F401, RUF100 - - import shelve # noqa: RUF100 -88 | import sys # noqa: F401, RUF100 +88 - import shelve # noqa: RUF100 | E501 Line too long (89 > 88) @@ -219,10 +195,8 @@ RUF100 [*] Unused `noqa` directive (unused: `F401`) | ^^^^^^^^^^^^ help: Remove unused `noqa` directive | -92 | - - "shape: (6,)\nSeries: '' [duration[μs]]\n[\n\t0µs\n\t1µs\n\t2µs\n\t3µs\n\t4µs\n\t5µs\n]" # noqa: F401 +93 - "shape: (6,)\nSeries: '' [duration[μs]]\n[\n\t0µs\n\t1µs\n\t2µs\n\t3µs\n\t4µs\n\t5µs\n]" # noqa: F401 93 + "shape: (6,)\nSeries: '' [duration[μs]]\n[\n\t0µs\n\t1µs\n\t2µs\n\t3µs\n\t4µs\n\t5µs\n]" -94 | | F841 [*] Local variable `e` is assigned to but never used @@ -234,9 +208,7 @@ F841 [*] Local variable `e` is assigned to but never used | ^ help: Remove assignment to unused variable `e` | -107 | d = 1 # …noqa: F841, E50 - - e = 1 # …noqa: E50 -108 | +108 - e = 1 # …noqa: E50 | note: This is an unsafe fix and may change runtime behavior @@ -252,10 +224,8 @@ RUF100 [*] Unused `noqa` directive (duplicated: `F841`) | help: Remove unused `noqa` directive | -117 | def f(): - - x = 2 # noqa: F841, F841, X200 +118 - x = 2 # noqa: F841, F841, X200 118 + x = 2 # noqa: F841 -119 | | RUF100 [*] Unused `noqa` directive (duplicated: `SIM300`, `SIM300`) @@ -270,10 +240,8 @@ RUF100 [*] Unused `noqa` directive (duplicated: `SIM300`, `SIM300`) | help: Remove unused `noqa` directive | -119 | - - y = 2 == bar # noqa: SIM300, F841, SIM300, SIM300 +120 - y = 2 == bar # noqa: SIM300, F841, SIM300, SIM300 120 + y = 2 == bar # noqa: SIM300, F841 -121 | | RUF100 [*] Unused `noqa` directive (duplicated: `F841`, `F841`, `F841`, `F841`) @@ -288,10 +256,8 @@ RUF100 [*] Unused `noqa` directive (duplicated: `F841`, `F841`, `F841`, `F841`) | help: Remove unused `noqa` directive | -121 | - - z = 2 # noqa: F841 F841 F841, F841, F841 +122 - z = 2 # noqa: F841 F841 F841, F841, F841 122 + z = 2 # noqa: F841 -123 | | RUF100 [*] Unused `noqa` directive (duplicated: `S307`, `S307`, `S307`) @@ -306,10 +272,8 @@ RUF100 [*] Unused `noqa` directive (duplicated: `S307`, `S307`, `S307`) | help: Remove unused `noqa` directive | -128 | x = eval(command) # noqa: PGH001, S307 - - x = eval(command) # noqa: S307, PGH001, S307, S307, S307 +129 - x = eval(command) # noqa: S307, PGH001, S307, S307, S307 129 + x = eval(command) # noqa: S307, PGH001 -130 | x = eval(command) # noqa: PGH001, S307, PGH001 | RUF100 [*] Unused `noqa` directive (duplicated: `PGH001`) @@ -323,10 +287,8 @@ RUF100 [*] Unused `noqa` directive (duplicated: `PGH001`) | help: Remove unused `noqa` directive | -129 | x = eval(command) # noqa: S307, PGH001, S307, S307, S307 - - x = eval(command) # noqa: PGH001, S307, PGH001 +130 - x = eval(command) # noqa: PGH001, S307, PGH001 130 + x = eval(command) # noqa: PGH001, S307 -131 | x = eval(command) # noqa: PGH001, S307, PGH001, S307 | RUF100 [*] Unused `noqa` directive (duplicated: `PGH001`, `S307`) @@ -338,7 +300,6 @@ RUF100 [*] Unused `noqa` directive (duplicated: `PGH001`, `S307`) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove unused `noqa` directive | -130 | x = eval(command) # noqa: PGH001, S307, PGH001 - - x = eval(command) # noqa: PGH001, S307, PGH001, S307 +131 - x = eval(command) # noqa: PGH001, S307, PGH001, S307 131 + x = eval(command) # noqa: PGH001, S307 | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_1.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_1.snap index 653a8ea302191..91bcb98de0cfa 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_1.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_1.snap @@ -12,11 +12,9 @@ F401 [*] `typing.Union` imported but unused | help: Remove unused import: `typing.Union` | -36 | Mapping, # noqa: F401 - - Union, - - ) +35 ~ from typing import ( +36 + Mapping, # noqa: F401 37 + ) -38 | | RUF100 [*] Unused `noqa` directive (unused: `F401`) @@ -30,10 +28,8 @@ RUF100 [*] Unused `noqa` directive (unused: `F401`) | help: Remove unused `noqa` directive | -51 | from typing import ( # noqa: F401 - - Optional, # noqa: F401 +52 - Optional, # noqa: F401 52 + Optional, -53 | ) | RUF100 [*] Unused `noqa` directive (unused: `F401`) @@ -47,10 +43,8 @@ RUF100 [*] Unused `noqa` directive (unused: `F401`) | help: Remove unused `noqa` directive | -58 | from typing import ( # noqa - - Optional, # noqa: F401 +59 - Optional, # noqa: F401 59 + Optional, -60 | ) | RUF100 [*] Unused `noqa` directive (non-enabled: `F501`) @@ -64,10 +58,8 @@ RUF100 [*] Unused `noqa` directive (non-enabled: `F501`) | help: Remove unused `noqa` directive | -65 | from typing import ( # noqa: F401 - - Dict, # noqa: F501 +66 - Dict, # noqa: F501 66 + Dict, -67 | ) | RUF100 [*] Unused `noqa` directive (non-enabled: `F501`) @@ -82,10 +74,8 @@ RUF100 [*] Unused `noqa` directive (non-enabled: `F501`) | help: Remove unused `noqa` directive | -71 | # This should ignore the error, but mark F501 as unused. - - from typing import ( # noqa: F501 +72 - from typing import ( # noqa: F501 72 + from typing import ( -73 | Tuple, # noqa: F401 | F401 [*] `typing.Awaitable` imported but unused @@ -97,8 +87,7 @@ F401 [*] `typing.Awaitable` imported but unused | ^^^^^^^^^ help: Remove unused import | -88 | # This should mark F501 as unused. - - from typing import Awaitable, AwaitableGenerator # noqa: F501 +89 - from typing import Awaitable, AwaitableGenerator # noqa: F501 89 + pass # noqa: F501 | @@ -111,8 +100,7 @@ F401 [*] `typing.AwaitableGenerator` imported but unused | ^^^^^^^^^^^^^^^^^^ help: Remove unused import | -88 | # This should mark F501 as unused. - - from typing import Awaitable, AwaitableGenerator # noqa: F501 +89 - from typing import Awaitable, AwaitableGenerator # noqa: F501 89 + pass # noqa: F501 | @@ -125,7 +113,6 @@ RUF100 [*] Unused `noqa` directive (non-enabled: `F501`) | ^^^^^^^^^^^^ help: Remove unused `noqa` directive | -88 | # This should mark F501 as unused. - - from typing import Awaitable, AwaitableGenerator # noqa: F501 +89 - from typing import Awaitable, AwaitableGenerator # noqa: F501 89 + from typing import Awaitable, AwaitableGenerator | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_2.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_2.snap index 3b2f4a86dc2b2..372437a16e72c 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_2.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_2.snap @@ -8,6 +8,6 @@ RUF100 [*] Unused `noqa` directive (non-enabled: `F401`) | ^^^^^^^^^^^^ help: Remove unused `noqa` directive | - - import itertools # noqa: F401 +1 - import itertools # noqa: F401 1 + import itertools | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_3.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_3.snap index aa8e5eb9583d0..662450fd37b30 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_3.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_3.snap @@ -11,8 +11,7 @@ RUF100 [*] Unused blanket `noqa` directive | help: Remove unused `noqa` directive | - - # noqa -1 | # noqa # comment +1 - # noqa | RUF100 [*] Unused blanket `noqa` directive @@ -26,10 +25,8 @@ RUF100 [*] Unused blanket `noqa` directive | help: Remove unused `noqa` directive | -1 | # noqa - - # noqa # comment +2 - # noqa # comment 2 + # comment -3 | print() # noqa | RUF100 [*] Unused blanket `noqa` directive @@ -44,10 +41,8 @@ RUF100 [*] Unused blanket `noqa` directive | help: Remove unused `noqa` directive | -2 | # noqa # comment - - print() # noqa +3 - print() # noqa 3 + print() -4 | print() # noqa # comment | RUF100 [*] Unused blanket `noqa` directive @@ -62,10 +57,8 @@ RUF100 [*] Unused blanket `noqa` directive | help: Remove unused `noqa` directive | -3 | print() # noqa - - print() # noqa # comment +4 - print() # noqa # comment 4 + print() # comment -5 | print() # noqa # comment | RUF100 [*] Unused blanket `noqa` directive @@ -80,10 +73,8 @@ RUF100 [*] Unused blanket `noqa` directive | help: Remove unused `noqa` directive | -4 | print() # noqa # comment - - print() # noqa # comment +5 - print() # noqa # comment 5 + print() # comment -6 | print() # noqa comment | RUF100 [*] Unused blanket `noqa` directive @@ -98,10 +89,8 @@ RUF100 [*] Unused blanket `noqa` directive | help: Remove unused `noqa` directive | -5 | print() # noqa # comment - - print() # noqa comment +6 - print() # noqa comment 6 + print() -7 | print() # noqa comment | RUF100 [*] Unused blanket `noqa` directive @@ -116,10 +105,8 @@ RUF100 [*] Unused blanket `noqa` directive | help: Remove unused `noqa` directive | -6 | print() # noqa comment - - print() # noqa comment +7 - print() # noqa comment 7 + print() -8 | print(a) # noqa | RUF100 [*] Unused `noqa` directive (unused: `E501`, `F821`) @@ -134,9 +121,7 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`, `F821`) | help: Remove unused `noqa` directive | -13 | - - # noqa: E501, F821 -14 | # noqa: E501, F821 # comment +14 - # noqa: E501, F821 | RUF100 [*] Unused `noqa` directive (unused: `E501`, `F821`) @@ -150,10 +135,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`, `F821`) | help: Remove unused `noqa` directive | -14 | # noqa: E501, F821 - - # noqa: E501, F821 # comment +15 - # noqa: E501, F821 # comment 15 + # comment -16 | print() # noqa: E501, F821 | RUF100 [*] Unused `noqa` directive (unused: `E501`, `F821`) @@ -168,10 +151,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`, `F821`) | help: Remove unused `noqa` directive | -15 | # noqa: E501, F821 # comment - - print() # noqa: E501, F821 +16 - print() # noqa: E501, F821 16 + print() -17 | print() # noqa: E501, F821 # comment | RUF100 [*] Unused `noqa` directive (unused: `E501`, `F821`) @@ -186,10 +167,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`, `F821`) | help: Remove unused `noqa` directive | -16 | print() # noqa: E501, F821 - - print() # noqa: E501, F821 # comment +17 - print() # noqa: E501, F821 # comment 17 + print() # comment -18 | print() # noqa: E501, F821 # comment | RUF100 [*] Unused `noqa` directive (unused: `E501`, `F821`) @@ -204,10 +183,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`, `F821`) | help: Remove unused `noqa` directive | -17 | print() # noqa: E501, F821 # comment - - print() # noqa: E501, F821 # comment +18 - print() # noqa: E501, F821 # comment 18 + print() # comment -19 | print() # noqa: E501, F821 comment | RUF100 [*] Unused `noqa` directive (unused: `E501`, `F821`) @@ -222,10 +199,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`, `F821`) | help: Remove unused `noqa` directive | -18 | print() # noqa: E501, F821 # comment - - print() # noqa: E501, F821 comment +19 - print() # noqa: E501, F821 comment 19 + print() -20 | print() # noqa: E501, F821 comment | RUF100 [*] Unused `noqa` directive (unused: `E501`, `F821`) @@ -240,10 +215,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`, `F821`) | help: Remove unused `noqa` directive | -19 | print() # noqa: E501, F821 comment - - print() # noqa: E501, F821 comment +20 - print() # noqa: E501, F821 comment 20 + print() -21 | print(a) # noqa: E501, F821 | RUF100 [*] Unused `noqa` directive (unused: `E501`) @@ -258,10 +231,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`) | help: Remove unused `noqa` directive | -20 | print() # noqa: E501, F821 comment - - print(a) # noqa: E501, F821 +21 - print(a) # noqa: E501, F821 21 + print(a) # noqa: F821 -22 | print(a) # noqa: E501, F821 # comment | RUF100 [*] Unused `noqa` directive (unused: `E501`) @@ -276,10 +247,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`) | help: Remove unused `noqa` directive | -21 | print(a) # noqa: E501, F821 - - print(a) # noqa: E501, F821 # comment +22 - print(a) # noqa: E501, F821 # comment 22 + print(a) # noqa: F821 # comment -23 | print(a) # noqa: E501, F821 # comment | RUF100 [*] Unused `noqa` directive (unused: `E501`) @@ -294,10 +263,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`) | help: Remove unused `noqa` directive | -22 | print(a) # noqa: E501, F821 # comment - - print(a) # noqa: E501, F821 # comment +23 - print(a) # noqa: E501, F821 # comment 23 + print(a) # noqa: F821 # comment -24 | print(a) # noqa: E501, F821 comment | RUF100 [*] Unused `noqa` directive (unused: `E501`) @@ -312,10 +279,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`) | help: Remove unused `noqa` directive | -23 | print(a) # noqa: E501, F821 # comment - - print(a) # noqa: E501, F821 comment +24 - print(a) # noqa: E501, F821 comment 24 + print(a) # noqa: F821 comment -25 | print(a) # noqa: E501, F821 comment | RUF100 [*] Unused `noqa` directive (unused: `E501`) @@ -330,10 +295,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`) | help: Remove unused `noqa` directive | -24 | print(a) # noqa: E501, F821 comment - - print(a) # noqa: E501, F821 comment +25 - print(a) # noqa: E501, F821 comment 25 + print(a) # noqa: F821 comment -26 | print(a) # noqa: E501,,F821 comment | RUF100 [*] Unused `noqa` directive (unused: `E501`) @@ -348,10 +311,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`) | help: Remove unused `noqa` directive | -25 | print(a) # noqa: E501, F821 comment - - print(a) # noqa: E501,,F821 comment +26 - print(a) # noqa: E501,,F821 comment 26 + print(a) # noqa: F821 comment -27 | print(a) # noqa: E501, ,F821 comment | RUF100 [*] Unused `noqa` directive (unused: `E501`) @@ -365,10 +326,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`) | help: Remove unused `noqa` directive | -26 | print(a) # noqa: E501,,F821 comment - - print(a) # noqa: E501, ,F821 comment +27 - print(a) # noqa: E501, ,F821 comment 27 + print(a) # noqa: F821 comment -28 | print(a) # noqa: E501 F821 comment | RUF100 [*] Unused `noqa` directive (unused: `E501`) @@ -383,10 +342,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`) | help: Remove unused `noqa` directive | -27 | print(a) # noqa: E501, ,F821 comment - - print(a) # noqa: E501 F821 comment +28 - print(a) # noqa: E501 F821 comment 28 + print(a) # noqa: F821 comment -29 | | F821 Undefined name `a` @@ -410,10 +367,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`) | help: Remove unused `noqa` directive | -29 | - - print(a) # comment with unicode µ # noqa: E501 +30 - print(a) # comment with unicode µ # noqa: E501 30 + print(a) # comment with unicode µ -31 | print(a) # comment with unicode µ # noqa: E501, F821 | RUF100 [*] Unused `noqa` directive (unused: `E501`) @@ -424,7 +379,6 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`) | ^^^^^^^^^^^^^^^^^^ help: Remove unused `noqa` directive | -30 | print(a) # comment with unicode µ # noqa: E501 - - print(a) # comment with unicode µ # noqa: E501, F821 +31 - print(a) # comment with unicode µ # noqa: E501, F821 31 + print(a) # comment with unicode µ # noqa: F821 | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_5.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_5.snap index 2edd5120911d8..f83829f940405 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_5.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_5.snap @@ -12,9 +12,7 @@ ERA001 [*] Found commented-out code | help: Remove commented-out code | -6 | # "key2": 456, # noqa - - # "key3": 789, -7 | } +7 - # "key3": 789, | note: This is a display-only fix and is likely to be incorrect @@ -28,9 +26,7 @@ ERA001 [*] Found commented-out code | help: Remove commented-out code | -10 | - - #import os # noqa: E501 -11 | +11 - #import os # noqa: E501 | note: This is a display-only fix and is likely to be incorrect @@ -44,10 +40,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`) | help: Remove unused `noqa` directive | -10 | - - #import os # noqa: E501 +11 - #import os # noqa: E501 11 + #import os -12 | | RUF100 [*] Unused `noqa` directive (non-enabled: `RET504`) @@ -62,10 +56,8 @@ RUF100 [*] Unused `noqa` directive (non-enabled: `RET504`) | help: Remove unused `noqa` directive | -15 | # line below should autofix to `return data # fmt: skip` - - return data # noqa: RET504 # fmt: skip +16 - return data # noqa: RET504 # fmt: skip 16 + return data # fmt: skip -17 | | RUF100 [*] Unused `noqa` directive (non-enabled: `RET504`) @@ -77,10 +69,8 @@ RUF100 [*] Unused `noqa` directive (non-enabled: `RET504`) | ^^^^^^^^^^^^^^ help: Remove unused `noqa` directive | -20 | # line below should autofix to `return data` - - return data # noqa: RET504 - intentional incorrect noqa, will be removed +21 - return data # noqa: RET504 - intentional incorrect noqa, will be removed 21 + return data -22 | | ERA001 [*] Found commented-out code @@ -93,9 +83,7 @@ ERA001 [*] Found commented-out code | help: Remove commented-out code | -24 | # Regression test for https://github.com/astral-sh/ruff/issues/25386 - - # ) -25 | # ) # noqa: ERA001 +25 - # ) | note: This is a display-only fix and is likely to be incorrect @@ -110,8 +98,6 @@ ERA001 [*] Found commented-out code | help: Remove commented-out code | -27 | - - # ( -28 | # ( # noqa: ERA001 +28 - # ( | note: This is a display-only fix and is likely to be incorrect diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruff_noqa_codes.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruff_noqa_codes.snap index 6faada6c7ba0a..c416552c938a1 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruff_noqa_codes.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruff_noqa_codes.snap @@ -9,8 +9,7 @@ F841 [*] Local variable `x` is assigned to but never used | ^ help: Remove assignment to unused variable `x` | -7 | def f(): - - x = 1 +8 - x = 1 8 + pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruff_noqa_filedirective_unused.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruff_noqa_filedirective_unused.snap index f1c33a1592c6e..aeeba09b46652 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruff_noqa_filedirective_unused.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruff_noqa_filedirective_unused.snap @@ -8,6 +8,5 @@ RUF100 [*] Unused `noqa` directive (non-enabled: `F841`) | ^^^^^^^^^^^^^^^^^^ help: Remove unused `noqa` directive | - - # ruff: noqa: F841 -- intentional unused file directive; will be removed -1 + +1 - # ruff: noqa: F841 -- intentional unused file directive; will be removed | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruff_noqa_filedirective_unused_last_of_many.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruff_noqa_filedirective_unused_last_of_many.snap index 3c138f9c1d1b6..fcbd852b4de23 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruff_noqa_filedirective_unused_last_of_many.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruff_noqa_filedirective_unused_last_of_many.snap @@ -10,9 +10,8 @@ RUF100 [*] Unused `noqa` directive (unused: `E501`) | help: Remove unused `noqa` directive | - - # flake8: noqa: F841, E501 -- used followed by unused code +1 - # flake8: noqa: F841, E501 -- used followed by unused code 1 + # flake8: noqa: F841 -- used followed by unused code -2 | # ruff: noqa: E701, F541 -- unused followed by used code | RUF100 [*] Unused `noqa` directive (non-enabled: `E701`) @@ -23,8 +22,6 @@ RUF100 [*] Unused `noqa` directive (non-enabled: `E701`) | ^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove unused `noqa` directive | -1 | # flake8: noqa: F841, E501 -- used followed by unused code - - # ruff: noqa: E701, F541 -- unused followed by used code +2 - # ruff: noqa: E701, F541 -- unused followed by used code 2 + # ruff: noqa: F541 -- unused followed by used code -3 | | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruff_noqa_invalid.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruff_noqa_invalid.snap index 04b50369b3686..3a81227f6e126 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruff_noqa_invalid.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruff_noqa_invalid.snap @@ -8,8 +8,7 @@ F401 [*] `os` imported but unused | ^^ help: Remove unused import: `os` | - - import os # ruff: noqa: F401 -1 | +1 - import os # ruff: noqa: F401 | F841 [*] Local variable `x` is assigned to but never used @@ -20,8 +19,7 @@ F841 [*] Local variable `x` is assigned to but never used | ^ help: Remove assignment to unused variable `x` | -4 | def f(): - - x = 1 +5 - x = 1 5 + pass | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__unnecessary_if_and_needless_else.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__unnecessary_if_and_needless_else.snap index e8ed80b8735c8..eb2b60515e2b4 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__unnecessary_if_and_needless_else.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__unnecessary_if_and_needless_else.snap @@ -14,10 +14,8 @@ RUF047 [*] Empty `else` clause | help: Remove the `else` clause | -5 | pass - - else: - - pass -6 | +6 - else: +7 - pass | RUF047 [*] Empty `else` clause @@ -33,10 +31,8 @@ RUF047 [*] Empty `else` clause | help: Remove the `else` clause | -13 | pass - - else: - - pass -14 | +14 - else: +15 - pass | RUF047 [*] Empty `else` clause @@ -49,8 +45,6 @@ RUF047 [*] Empty `else` clause | |________^ help: Remove the `else` clause | -20 | pass - - else: - - pass -21 | +21 - else: +22 - pass | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__unnecessary_if_and_unused_import.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__unnecessary_if_and_unused_import.snap index fef58b93d9321..7f57ec47e4785 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__unnecessary_if_and_unused_import.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__unnecessary_if_and_unused_import.snap @@ -13,10 +13,8 @@ F401 [*] `exceptiongroup.ExceptionGroup` imported but unused | help: Remove unused import: `exceptiongroup.ExceptionGroup` | -11 | if sys.version_info < (3, 11): - - from exceptiongroup import ExceptionGroup +12 - from exceptiongroup import ExceptionGroup 12 + pass -13 | | RUF050 [*] Empty `if` statement @@ -31,8 +29,6 @@ RUF050 [*] Empty `if` statement | help: Remove the `if` statement | -14 | # Already-empty block handled in a single pass by RUF050 - - if sys.version_info < (3, 11): - - pass -15 | +15 - if sys.version_info < (3, 11): +16 - pass | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__useless_finally_and_needless_else.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__useless_finally_and_needless_else.snap index b8824b9cea378..ef9eaaa57d669 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__useless_finally_and_needless_else.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__useless_finally_and_needless_else.snap @@ -14,10 +14,8 @@ RUF047 [*] Empty `else` clause | help: Remove the `else` clause | -6 | bar() - - else: - - pass -7 | finally: +7 - else: +8 - pass | RUF072 [*] Empty `finally` clause @@ -32,12 +30,10 @@ RUF072 [*] Empty `finally` clause 12 | # All non-body clauses are no-ops | help: Remove the `finally` clause - | -8 | pass - - finally: - - pass -9 | - | + | + 9 - finally: +10 - pass + | RUF047 [*] Empty `else` clause --> RUF072_RUF047.py:17:1 @@ -52,10 +48,8 @@ RUF047 [*] Empty `else` clause | help: Remove the `else` clause | -16 | pass - - else: - - pass -17 | finally: +17 - else: +18 - pass | RUF072 [*] Empty `finally` clause @@ -71,10 +65,8 @@ RUF072 [*] Empty `finally` clause | help: Remove the `finally` clause | -18 | pass - - finally: - - pass -19 | +19 - finally: +20 - pass | RUF072 [*] Empty `finally` clause @@ -87,7 +79,6 @@ RUF072 [*] Empty `finally` clause | |________^ help: Remove the `finally` clause | -28 | baz() - - finally: - - pass +29 - finally: +30 - pass | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__useless_finally_and_needless_else_and_suppressible_exception.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__useless_finally_and_needless_else_and_suppressible_exception.snap index d6b94487535a1..91c3643dde69b 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__useless_finally_and_needless_else_and_suppressible_exception.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__useless_finally_and_needless_else_and_suppressible_exception.snap @@ -14,10 +14,8 @@ RUF047 [*] Empty `else` clause | help: Remove the `else` clause | -6 | pass - - else: - - pass -7 | finally: +7 - else: +8 - pass | RUF072 [*] Empty `finally` clause @@ -29,8 +27,7 @@ RUF072 [*] Empty `finally` clause 10 | | pass | |________^ help: Remove the `finally` clause - | -8 | pass - - finally: - - pass - | + | + 9 - finally: +10 - pass + | diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__useless_finally_and_suppressible_exception.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__useless_finally_and_suppressible_exception.snap index 845be65e12b1f..ec19082749995 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__useless_finally_and_suppressible_exception.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__useless_finally_and_suppressible_exception.snap @@ -10,9 +10,7 @@ RUF072 [*] Empty `finally` clause 9 | | pass | |________^ help: Remove the `finally` clause - | -7 | pass - - finally: - - pass -8 | - | + | + 8 - finally: + 9 - pass + | diff --git a/crates/ruff_linter/src/rules/tryceratops/snapshots/ruff_linter__rules__tryceratops__tests__error-instead-of-exception_TRY400.py.snap b/crates/ruff_linter/src/rules/tryceratops/snapshots/ruff_linter__rules__tryceratops__tests__error-instead-of-exception_TRY400.py.snap index 51a8680efaca1..f58c792af2862 100644 --- a/crates/ruff_linter/src/rules/tryceratops/snapshots/ruff_linter__rules__tryceratops__tests__error-instead-of-exception_TRY400.py.snap +++ b/crates/ruff_linter/src/rules/tryceratops/snapshots/ruff_linter__rules__tryceratops__tests__error-instead-of-exception_TRY400.py.snap @@ -13,10 +13,8 @@ TRY400 [*] Use `logging.exception` instead of `logging.error` | help: Replace with `exception` | -12 | except Exception: - - logging.error("Context message here") +13 - logging.error("Context message here") 13 + logging.exception("Context message here") -14 | | TRY400 [*] Use `logging.exception` instead of `logging.error` @@ -27,10 +25,8 @@ TRY400 [*] Use `logging.exception` instead of `logging.error` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `exception` | -15 | if True: - - logging.error("Context message here") +16 - logging.error("Context message here") 16 + logging.exception("Context message here") -17 | | TRY400 [*] Use `logging.exception` instead of `logging.error` @@ -45,10 +41,8 @@ TRY400 [*] Use `logging.exception` instead of `logging.error` | help: Replace with `exception` | -26 | except Exception: - - logger.error("Context message here") +27 - logger.error("Context message here") 27 + logger.exception("Context message here") -28 | | note: This is an unsafe fix and may change runtime behavior @@ -60,10 +54,8 @@ TRY400 [*] Use `logging.exception` instead of `logging.error` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `exception` | -29 | if True: - - logger.error("Context message here") +30 - logger.error("Context message here") 30 + logger.exception("Context message here") -31 | | note: This is an unsafe fix and may change runtime behavior @@ -79,10 +71,8 @@ TRY400 [*] Use `logging.exception` instead of `logging.error` | help: Replace with `exception` | -36 | except Exception: - - log.error("Context message here") +37 - log.error("Context message here") 37 + log.exception("Context message here") -38 | | note: This is an unsafe fix and may change runtime behavior @@ -94,10 +84,8 @@ TRY400 [*] Use `logging.exception` instead of `logging.error` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `exception` | -39 | if True: - - log.error("Context message here") +40 - log.error("Context message here") 40 + log.exception("Context message here") -41 | | note: This is an unsafe fix and may change runtime behavior @@ -113,10 +101,8 @@ TRY400 [*] Use `logging.exception` instead of `logging.error` | help: Replace with `exception` | -46 | except Exception: - - self.logger.error("Context message here") +47 - self.logger.error("Context message here") 47 + self.logger.exception("Context message here") -48 | | note: This is an unsafe fix and may change runtime behavior @@ -128,10 +114,8 @@ TRY400 [*] Use `logging.exception` instead of `logging.error` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `exception` | -49 | if True: - - self.logger.error("Context message here") +50 - self.logger.error("Context message here") 50 + self.logger.exception("Context message here") -51 | | note: This is an unsafe fix and may change runtime behavior @@ -147,10 +131,11 @@ TRY400 [*] Use `logging.exception` instead of `logging.error` | help: Replace with `exception` | -99 | except Exception: - - error("Context message here") -100 + exception("Context message here") -101 | + 95 ~ from logging import error, exception + 96 | + … + 99 | except Exception: +100 ~ exception("Context message here") | TRY400 [*] Use `logging.exception` instead of `logging.error` @@ -161,10 +146,11 @@ TRY400 [*] Use `logging.exception` instead of `logging.error` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `exception` | + 95 ~ from logging import error, exception + 96 | + … 102 | if True: - - error("Context message here") -103 + exception("Context message here") -104 | +103 ~ exception("Context message here") | TRY400 [*] Use `logging.exception` instead of `logging.error` @@ -176,7 +162,9 @@ TRY400 [*] Use `logging.exception` instead of `logging.error` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Replace with `exception` | +135 ~ from logging import error, exception +136 | + … 142 | except Exception: - - error("Context message here") -143 + exception("Context message here") +143 ~ exception("Context message here") | diff --git a/crates/ruff_linter/src/rules/tryceratops/snapshots/ruff_linter__rules__tryceratops__tests__verbose-raise_TRY201.py.snap b/crates/ruff_linter/src/rules/tryceratops/snapshots/ruff_linter__rules__tryceratops__tests__verbose-raise_TRY201.py.snap index 0560eb3a08473..0f62466acb885 100644 --- a/crates/ruff_linter/src/rules/tryceratops/snapshots/ruff_linter__rules__tryceratops__tests__verbose-raise_TRY201.py.snap +++ b/crates/ruff_linter/src/rules/tryceratops/snapshots/ruff_linter__rules__tryceratops__tests__verbose-raise_TRY201.py.snap @@ -10,10 +10,8 @@ TRY201 [*] Use `raise` without specifying exception name | ^ help: Remove exception name | -19 | logger.exception("process failed") - - raise e +20 - raise e 20 + raise -21 | | note: This is an unsafe fix and may change runtime behavior @@ -26,10 +24,8 @@ TRY201 [*] Use `raise` without specifying exception name | ^ help: Remove exception name | -62 | if True: - - raise e +63 - raise e 63 + raise -64 | | note: This is an unsafe fix and may change runtime behavior @@ -41,8 +37,7 @@ TRY201 [*] Use `raise` without specifying exception name | ^ help: Remove exception name | -73 | def foo(): - - raise e +74 - raise e 74 + raise | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__disabled_typing_extensions_pyi019_adds_typing_extensions.snap b/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__disabled_typing_extensions_pyi019_adds_typing_extensions.snap index a059dbab11998..ffdd8f6f3e586 100644 --- a/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__disabled_typing_extensions_pyi019_adds_typing_extensions.snap +++ b/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__disabled_typing_extensions_pyi019_adds_typing_extensions.snap @@ -11,13 +11,10 @@ PYI019 [*] Use `Self` instead of custom TypeVar `T` | help: Replace TypeVar `T` with `Self` | -2 | from typing import TypeVar 3 + from typing_extensions import Self -4 | +4 + 5 | T = TypeVar("T", bound="_NiceReprEnum") 6 | 7 | class C: - - def __new__(cls: type[T]) -> T: -8 + def __new__(cls) -> Self: -9 | return cls +8 ~ def __new__(cls) -> Self: | diff --git a/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__disabled_typing_extensions_pyi019_adds_typing_with_extensions_disabled.snap b/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__disabled_typing_extensions_pyi019_adds_typing_with_extensions_disabled.snap index 04b9b2efb2418..34f5413091d17 100644 --- a/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__disabled_typing_extensions_pyi019_adds_typing_with_extensions_disabled.snap +++ b/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__disabled_typing_extensions_pyi019_adds_typing_with_extensions_disabled.snap @@ -11,14 +11,9 @@ PYI019 [*] Use `Self` instead of custom TypeVar `T` | help: Replace TypeVar `T` with `Self` | -1 | - - from typing import TypeVar -2 + from typing import TypeVar, Self +2 ~ from typing import TypeVar, Self 3 | -4 | T = TypeVar("T", bound="_NiceReprEnum") -5 | +… 6 | class C: - - def __new__(cls: type[T]) -> T: -7 + def __new__(cls) -> Self: -8 | return cls +7 ~ def __new__(cls) -> Self: | diff --git a/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__disabled_typing_extensions_pyi019_adds_typing_without_extensions_disabled.snap b/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__disabled_typing_extensions_pyi019_adds_typing_without_extensions_disabled.snap index 04b9b2efb2418..34f5413091d17 100644 --- a/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__disabled_typing_extensions_pyi019_adds_typing_without_extensions_disabled.snap +++ b/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__disabled_typing_extensions_pyi019_adds_typing_without_extensions_disabled.snap @@ -11,14 +11,9 @@ PYI019 [*] Use `Self` instead of custom TypeVar `T` | help: Replace TypeVar `T` with `Self` | -1 | - - from typing import TypeVar -2 + from typing import TypeVar, Self +2 ~ from typing import TypeVar, Self 3 | -4 | T = TypeVar("T", bound="_NiceReprEnum") -5 | +… 6 | class C: - - def __new__(cls: type[T]) -> T: -7 + def __new__(cls) -> Self: -8 | return cls +7 ~ def __new__(cls) -> Self: | diff --git a/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__import_sorting.snap b/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__import_sorting.snap index 9d888d969781b..0fef2885c6a35 100644 --- a/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__import_sorting.snap +++ b/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__import_sorting.snap @@ -9,13 +9,11 @@ I001 [*] Import block is un-sorted or un-formatted 3 | | import math | |___________^ help: Organize imports - ::: cell 1 + ::: cell 1:0:1 | -1 + import math -2 + import random -3 | from pathlib import Path - - import random - - import math +0 + import math +1 + import random +2 + from pathlib import Path | I001 [*] Import block is un-sorted or un-formatted @@ -28,14 +26,10 @@ I001 [*] Import block is un-sorted or un-formatted 4 | def foo(): | help: Organize imports - ::: cell 2 + ::: cell 2:0:1 | -1 + import collections -2 | from typing import Any - - import collections -3 + -4 + -5 | # Newline should be added here +0 + import collections +1 + from typing import Any | I001 [*] Import block is un-sorted or un-formatted @@ -48,12 +42,10 @@ I001 [*] Import block is un-sorted or un-formatted 4 | %matplotlib \ | help: Organize imports - ::: cell 3 + ::: cell 3:0:1 | -1 + import sys -2 | from pathlib import Path - - import sys -3 | +0 + import sys +1 + from pathlib import Path | I001 [*] Import block is un-sorted or un-formatted @@ -65,10 +57,8 @@ I001 [*] Import block is un-sorted or un-formatted 8 | | import abc | |__________^ help: Organize imports - ::: cell 3 + ::: cell 3:6:1 | -6 | -7 + import abc -8 | import math - - import abc +6 + import abc +7 + import math | diff --git a/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__ipy_escape_command.snap b/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__ipy_escape_command.snap index 646b1f26c4f73..226c0dae1a884 100644 --- a/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__ipy_escape_command.snap +++ b/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__ipy_escape_command.snap @@ -12,11 +12,9 @@ F401 [*] `os` imported but unused 7 | _ = math.pi | help: Remove unused import: `os` - ::: cell 1 + ::: cell 1:4:1 | -4 | - - import os -5 | +4 - import os | F401 [*] `sys` imported but unused @@ -26,8 +24,7 @@ F401 [*] `sys` imported but unused 2 | import sys | ^^^ help: Remove unused import: `sys` - ::: cell 2 + ::: cell 2:1:1 | -1 | %%timeit - - import sys +1 - import sys | diff --git a/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__unused_variable.snap b/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__unused_variable.snap index de53bff60850a..6bb4acc20ca7a 100644 --- a/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__unused_variable.snap +++ b/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__unused_variable.snap @@ -10,12 +10,10 @@ F841 [*] Local variable `foo1` is assigned to but never used 3 | foo2: list[str] = %matplotlib --list | help: Remove assignment to unused variable `foo1` - ::: cell 1 + ::: cell 1:1:5 | -1 | def f(): - - foo1 = %matplotlib --list -2 + %matplotlib --list -3 | foo2: list[str] = %matplotlib --list +1 - foo1 = %matplotlib --list +1 + %matplotlib --list | note: This is an unsafe fix and may change runtime behavior @@ -27,11 +25,10 @@ F841 [*] Local variable `foo2` is assigned to but never used 3 | foo2: list[str] = %matplotlib --list | ^^^^ help: Remove assignment to unused variable `foo2` - ::: cell 1 + ::: cell 1:2:5 | -2 | foo1 = %matplotlib --list - - foo2: list[str] = %matplotlib --list -3 + %matplotlib --list +2 - foo2: list[str] = %matplotlib --list +2 + %matplotlib --list | note: This is an unsafe fix and may change runtime behavior @@ -44,12 +41,10 @@ F841 [*] Local variable `bar1` is assigned to but never used 3 | bar2: str = !pwd | help: Remove assignment to unused variable `bar1` - ::: cell 2 + ::: cell 2:1:5 | -1 | def f(): - - bar1 = !pwd -2 + !pwd -3 | bar2: str = !pwd +1 - bar1 = !pwd +1 + !pwd | note: This is an unsafe fix and may change runtime behavior @@ -61,10 +56,9 @@ F841 [*] Local variable `bar2` is assigned to but never used 3 | bar2: str = !pwd | ^^^^ help: Remove assignment to unused variable `bar2` - ::: cell 2 + ::: cell 2:2:5 | -2 | bar1 = !pwd - - bar2: str = !pwd -3 + !pwd +2 - bar2: str = !pwd +2 + !pwd | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__vscode_language_id.snap b/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__vscode_language_id.snap index 877703bbf4dff..c33b6dd540dee 100644 --- a/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__vscode_language_id.snap +++ b/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__vscode_language_id.snap @@ -10,8 +10,7 @@ F401 [*] `os` imported but unused 3 | print("hello world") | help: Remove unused import: `os` - ::: cell 3 + ::: cell 3:0:1 | - - import os -1 | +0 - import os | diff --git a/crates/ty_ide/src/code_action.rs b/crates/ty_ide/src/code_action.rs index e6ed2b5ed0e04..95958a649034a 100644 --- a/crates/ty_ide/src/code_action.rs +++ b/crates/ty_ide/src/code_action.rs @@ -106,9 +106,8 @@ mod tests { 1 | b = a / 10 | ^ | - - b = a / 10 - 1 + b = a / 10 # ty: ignore[unresolved-reference] - | + 1 | b = a / 10 # ty: ignore[unresolved-reference] + | ++++++++++++++++++++++++++++++++++ "); } @@ -123,9 +122,8 @@ mod tests { 1 | b = a / 10 # fmt: off | ^ | - - b = a / 10 # fmt: off - 1 + b = a / 10 # fmt: off # ty: ignore[unresolved-reference] - | + 1 | b = a / 10 # fmt: off # ty: ignore[unresolved-reference] + | ++++++++++++++++++++++++++++++++++ "); } @@ -152,10 +150,8 @@ mod tests { 2 | b = a / 0 # ty:ignore[division-by-zero] | ^ | - 1 | - - b = a / 0 # ty:ignore[division-by-zero] - 2 + b = a / 0 # ty:ignore[division-by-zero, unresolved-reference] - | + 2 | b = a / 0 # ty:ignore[division-by-zero, unresolved-reference] + | ++++++++++++++++++++++ "); } @@ -174,10 +170,8 @@ mod tests { 2 | b = a / 10 # ty:ignore[] | ^ | - 1 | - - b = a / 10 # ty:ignore[] - 2 + b = a / 10 # ty:ignore[unresolved-reference] - | + 2 | b = a / 10 # ty:ignore[unresolved-reference] + | ++++++++++++++++++++ "); } @@ -198,11 +192,8 @@ mod tests { 4 | b = a / 10 | ^ | - 2 | seen_code = True - - # ty:ignore[] - 3 + # ty:ignore[unresolved-reference] - 4 | b = a / 10 - | + 3 | # ty:ignore[unresolved-reference] + | ++++++++++++++++++++ "); } @@ -228,11 +219,8 @@ mod tests { 3 | # ty:ignore[] # ty:ignore[not-a-rule] # ty:ignore[division-by-zero] | ^^^^^^^^^^ | - 2 | seen_code = True - - # ty:ignore[] # ty:ignore[not-a-rule] # ty:ignore[division-by-zero] - 3 + # ty:ignore[ignore-comment-unknown-rule] # ty:ignore[not-a-rule] # ty:ignore[division-by-zero] - 4 | value = 1 / 0 - | + 3 | # ty:ignore[ignore-comment-unknown-rule] # ty:ignore[not-a-rule] # ty:ignore[division-by-zero] + | +++++++++++++++++++++++++++ "); } @@ -257,11 +245,8 @@ mod tests { 7 | absent, | ^^^^^^ | - 2 | seen_code = True - - # ty:ignore[] - 3 + # ty:ignore[unresolved-reference] - 4 | values = [ - | + 3 | # ty:ignore[unresolved-reference] + | ++++++++++++++++++++ "); } @@ -288,11 +273,8 @@ mod tests { 9 | absent, | ^^^^^^ | - 4 | seen_code = True - - # ty:ignore[invalid-assignment] - 5 + # ty:ignore[invalid-assignment, unresolved-reference] - 6 | values: tuple[int] = [ - | + 5 | # ty:ignore[invalid-assignment, unresolved-reference] + | ++++++++++++++++++++++ "); } @@ -311,10 +293,8 @@ mod tests { 2 | b = a / 0 # type:ignore[ty:division-by-zero] | ^ | - 1 | - - b = a / 0 # type:ignore[ty:division-by-zero] - 2 + b = a / 0 # type:ignore[ty:division-by-zero, ty:unresolved-reference] - | + 2 | b = a / 0 # type:ignore[ty:division-by-zero, ty:unresolved-reference] + | +++++++++++++++++++++++++ "); } @@ -333,10 +313,8 @@ mod tests { 2 | b = a / 0 # type:ignore[mypy-code] | ^ | - 1 | - - b = a / 0 # type:ignore[mypy-code] - 2 + b = a / 0 # type:ignore[mypy-code] # ty: ignore[unresolved-reference] - | + 2 | b = a / 0 # type:ignore[mypy-code] # ty: ignore[unresolved-reference] + | ++++++++++++++++++++++++++++++++++ "); } @@ -357,10 +335,8 @@ mod tests { 4 | b = a / 0 | ^ | - 3 | - - b = a / 0 - 4 + b = a / 0 # ty: ignore[unresolved-reference] - | + 4 | b = a / 0 # ty: ignore[unresolved-reference] + | ++++++++++++++++++++++++++++++++++ "); } @@ -379,10 +355,8 @@ mod tests { 2 | b = a / 0 # ty:ignore[division-by-zero,] | ^ | - 1 | - - b = a / 0 # ty:ignore[division-by-zero,] - 2 + b = a / 0 # ty:ignore[division-by-zero, unresolved-reference] - | + 2 | b = a / 0 # ty:ignore[division-by-zero, unresolved-reference] + | ++++++++++++++++++++ "); } @@ -401,10 +375,8 @@ mod tests { 2 | b = a / 0 # ty:ignore[division-by-zero ] | ^ | - 1 | - - b = a / 0 # ty:ignore[division-by-zero ] - 2 + b = a / 0 # ty:ignore[division-by-zero, unresolved-reference ] - | + 2 | b = a / 0 # ty:ignore[division-by-zero, unresolved-reference ] + | ++++++++++++++++++++++ "); } @@ -423,10 +395,8 @@ mod tests { 2 | b = a / 0 # ty:ignore[division-by-zero] some explanation | ^ | - 1 | - - b = a / 0 # ty:ignore[division-by-zero] some explanation - 2 + b = a / 0 # ty:ignore[division-by-zero] some explanation # ty: ignore[unresolved-reference] - | + 2 | b = a / 0 # ty:ignore[division-by-zero] some explanation # ty: ignore[unresolved-reference] + | ++++++++++++++++++++++++++++++++++ "); } @@ -451,11 +421,8 @@ mod tests { 5 | | 0 | |_________^ | - 2 | b = ( - - a # ty:ignore[division-by-zero] - 3 + a # ty:ignore[division-by-zero, unresolved-reference] - 4 | / - | + 3 | a # ty:ignore[division-by-zero, unresolved-reference] + | ++++++++++++++++++++++ "); } @@ -480,11 +447,8 @@ mod tests { 5 | | 0 # ty:ignore[division-by-zero] | |_________^ | - 4 | / - - 0 # ty:ignore[division-by-zero] - 5 + 0 # ty:ignore[division-by-zero, unresolved-reference] - 6 | ) - | + 5 | 0 # ty:ignore[division-by-zero, unresolved-reference] + | ++++++++++++++++++++++ "); } @@ -509,11 +473,8 @@ mod tests { 5 | | 0 # ty:ignore[division-by-zero] | |_________^ | - 2 | b = ( - - a # ty:ignore[division-by-zero] - 3 + a # ty:ignore[division-by-zero, unresolved-reference] - 4 | / - | + 3 | a # ty:ignore[division-by-zero, unresolved-reference] + | ++++++++++++++++++++++ "); } @@ -535,10 +496,8 @@ mod tests { 3 | {a} | ^ | - 4 | more text - - """ - 5 + """ # ty: ignore[unresolved-reference] - | + 5 | """ # ty: ignore[unresolved-reference] + | ++++++++++++++++++++++++++++++++++ "#); } @@ -562,11 +521,8 @@ mod tests { 4 | a | ^ | - 3 | { - - a - 4 + a # ty: ignore[unresolved-reference] - 5 | } - | + 4 | a # ty: ignore[unresolved-reference] + | ++++++++++++++++++++++++++++++++++ "); } @@ -587,10 +543,8 @@ mod tests { 2 | b = a + """ | ^ | - 3 | more text - - """ - 4 + """ # ty: ignore[unresolved-reference] - | + 4 | """ # ty: ignore[unresolved-reference] + | ++++++++++++++++++++++++++++++++++ "#); } @@ -610,10 +564,8 @@ mod tests { 2 | b = a \ | ^ | - 2 | b = a \ - - + "test" - 3 + + "test" # ty: ignore[unresolved-reference] - | + 3 | + "test" # ty: ignore[unresolved-reference] + | ++++++++++++++++++++++++++++++++++ "#); } @@ -636,10 +588,7 @@ mod tests { 4 | + ddd \ | ^^^ | - 4 | + ddd \ - - - 5 + # ty: ignore[unresolved-reference] - 6 | ] # test + 5 | # ty: ignore[unresolved-reference] | "); } @@ -661,7 +610,6 @@ mod tests { help: This is a preferred code action | 1 + from typing import reveal_type - 2 | | info[code-action]: import typing_extensions.reveal_type @@ -672,7 +620,6 @@ mod tests { help: This is a preferred code action | 1 + from typing_extensions import reveal_type - 2 | | info[code-action]: Ignore 'undefined-reveal' for this line @@ -681,10 +628,8 @@ mod tests { 2 | reveal_type(1) | ^^^^^^^^^^^ | - 1 | - - reveal_type(1) - 2 + reveal_type(1) # ty: ignore[undefined-reveal] - | + 2 | reveal_type(1) # ty: ignore[undefined-reveal] + | ++++++++++++++++++++++++++++++ "); } @@ -706,7 +651,6 @@ mod tests { help: This is a preferred code action | 1 + from warnings import deprecated - 2 | | info[code-action]: import typing_extensions.deprecated @@ -717,7 +661,6 @@ mod tests { help: This is a preferred code action | 1 + from typing_extensions import deprecated - 2 | | info[code-action]: Ignore 'unresolved-reference' for this line @@ -726,11 +669,8 @@ mod tests { 2 | @deprecated("do not use") | ^^^^^^^^^^ | - 1 | - - @deprecated("do not use") - 2 + @deprecated("do not use") # ty: ignore[unresolved-reference] - 3 | def my_func(): ... - | + 2 | @deprecated("do not use") # ty: ignore[unresolved-reference] + | ++++++++++++++++++++++++++++++++++ "#); } @@ -754,7 +694,6 @@ mod tests { help: This is a preferred code action | 1 + from warnings import deprecated - 2 | | info[code-action]: import typing_extensions.deprecated @@ -765,7 +704,6 @@ mod tests { help: This is a preferred code action | 1 + from typing_extensions import deprecated - 2 | | info[code-action]: qualify warnings.deprecated @@ -775,11 +713,8 @@ mod tests { | ^^^^^^^^^^ help: This is a preferred code action | - 3 | - - @deprecated("do not use") - 4 + @warnings.deprecated("do not use") - 5 | def my_func(): ... - | + 4 | @warnings.deprecated("do not use") + | +++++++++ info[code-action]: Ignore 'unresolved-reference' for this line --> main.py:4:2 @@ -787,11 +722,8 @@ mod tests { 4 | @deprecated("do not use") | ^^^^^^^^^^ | - 3 | - - @deprecated("do not use") - 4 + @deprecated("do not use") # ty: ignore[unresolved-reference] - 5 | def my_func(): ... - | + 4 | @deprecated("do not use") # ty: ignore[unresolved-reference] + | ++++++++++++++++++++++++++++++++++ "#); } @@ -813,7 +745,6 @@ mod tests { help: This is a preferred code action | 1 + from importlib.abc import ExecutionLoader - 2 | | info[code-action]: Ignore 'unresolved-reference' for this line @@ -822,10 +753,8 @@ mod tests { 2 | ExecutionLoader | ^^^^^^^^^^^^^^^ | - 1 | - - ExecutionLoader - 2 + ExecutionLoader # ty: ignore[unresolved-reference] - | + 2 | ExecutionLoader # ty: ignore[unresolved-reference] + | ++++++++++++++++++++++++++++++++++ "); } @@ -851,7 +780,6 @@ mod tests { help: This is a preferred code action | 1 + from importlib.abc import ExecutionLoader - 2 | | info[code-action]: Ignore 'unresolved-reference' for this line @@ -860,10 +788,8 @@ mod tests { 3 | ExecutionLoader | ^^^^^^^^^^^^^^^ | - 2 | import importlib - - ExecutionLoader - 3 + ExecutionLoader # ty: ignore[unresolved-reference] - | + 3 | ExecutionLoader # ty: ignore[unresolved-reference] + | ++++++++++++++++++++++++++++++++++ "); } @@ -886,7 +812,6 @@ mod tests { help: This is a preferred code action | 1 + from importlib.abc import ExecutionLoader - 2 | | info[code-action]: qualify importlib.abc.ExecutionLoader @@ -896,10 +821,8 @@ mod tests { | ^^^^^^^^^^^^^^^ help: This is a preferred code action | - 2 | import importlib.abc - - ExecutionLoader - 3 + importlib.abc.ExecutionLoader - | + 3 | importlib.abc.ExecutionLoader + | ++++++++++++++ info[code-action]: Ignore 'unresolved-reference' for this line --> main.py:3:1 @@ -907,10 +830,8 @@ mod tests { 3 | ExecutionLoader | ^^^^^^^^^^^^^^^ | - 2 | import importlib.abc - - ExecutionLoader - 3 + ExecutionLoader # ty: ignore[unresolved-reference] - | + 3 | ExecutionLoader # ty: ignore[unresolved-reference] + | ++++++++++++++++++++++++++++++++++ "); } diff --git a/crates/ty_ide/src/inlay_hints.rs b/crates/ty_ide/src/inlay_hints.rs index 8a69580832972..19a821af7cf25 100644 --- a/crates/ty_ide/src/inlay_hints.rs +++ b/crates/ty_ide/src/inlay_hints.rs @@ -1099,21 +1099,19 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 - | - 1 + from typing import Literal - 2 | - -------------------------------------------------------------------------------- - 6 | x = 1 - - y = x - - z = i(1) - - w = z - 7 + y: Literal[1] = x - 8 + z: int = i(1) - 9 + w: int = z + --> main.py:1:1 + | + 1 + from typing import Literal + 2 + + 3 | def i(x: int, /) -> int: + 4 | return x + 5 | + 6 | x = 1 + 7 ~ y: Literal[1] = x + 8 ~ z: int = i(1) + 9 ~ w: int = z 10 | aa = b'foo' - - bb = aa - 11 + bb: Literal[b"foo"] = aa + 11 ~ bb: Literal[b"foo"] = aa | "#); } @@ -1392,11 +1390,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 2 | def i(x: int, /) -> int: + 3 | return x 4 | - - __special__ = i(1) - 5 + __special__: int = i(1) + 5 ~ __special__: int = i(1) | "); } @@ -1672,18 +1671,19 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 - | - 1 + from typing import Literal - 2 | - -------------------------------------------------------------------------------- - 8 | x = (1, 'abc') - - y = x - - z = (i(1), s('abc')) - - w = z - 9 + y: tuple[Literal[1], Literal["abc"]] = x - 10 + z: tuple[int, str] = (i(1), s('abc')) - 11 + w: tuple[int, str] = z + --> main.py:1:1 + | + 1 + from typing import Literal + 2 + + 3 | def i(x: int, /) -> int: + 4 | return x + 5 | def s(x: str, /) -> str: + 6 | return x + 7 | + 8 | x = (1, 'abc') + 9 ~ y: tuple[Literal[1], Literal["abc"]] = x + 10 ~ z: tuple[int, str] = (i(1), s('abc')) + 11 ~ w: tuple[int, str] = z | "#); } @@ -1907,17 +1907,17 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | 1 + from typing import Literal - 2 | - -------------------------------------------------------------------------------- + 2 + + 3 | def i(x: int, /) -> int: + 4 | return x + 5 | 6 | x: int = 1 - - y = x - 7 + y: Literal[1] = x + 7 ~ y: Literal[1] = x 8 | z: int = i(1) - - w = z - 9 + w: int = z + 9 ~ w: int = z | "); } @@ -1952,11 +1952,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | + 2 | def i(x: int, /) -> int: 3 | return x - - x = i(1) - 4 + x: int = i(1) + 4 ~ x: int = i(1) 5 | z = x | "); @@ -2011,18 +2012,16 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | 1 + from ty_extensions._internal import Unknown - 2 | + 2 + 3 | class A: 4 | def __init__(self, y): 5 | self.x = int(1) - - self.y = y - 6 + self.y: Unknown = y + 6 ~ self.y: Unknown = y 7 | - - a = A(2) - 8 + a = A(y=2) + 8 ~ a = A(y=2) 9 | a.y = int(3) | "); @@ -2060,11 +2059,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 2 | def my_func(command: str): + 3 | match command.split(): 4 | case ["get", ab]: - - x = ab - 5 + x: str = ab + 5 ~ x: str = ab | "#); } @@ -2112,11 +2112,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 2 | def my_func(command: str): + 3 | match command.split(): 4 | case ["get", *ab]: - - x = ab - 5 + x: list[str] = ab + 5 ~ x: list[str] = ab | "#); } @@ -2175,15 +2176,14 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | 1 + from typing import Literal - 2 | + 2 + 3 | def my_func(command: str): 4 | match command.split(): 5 | case ["get", ("a" | "b") as ab]: - - x = ab - 6 + x: Literal["a", "b"] = ab + 6 ~ x: Literal["a", "b"] = ab | "#); } @@ -2232,11 +2232,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 8 | def my_func(event: Click): + 9 | match event: 10 | case Click(x, button=ab): - - x = ab - 11 + x: str = ab + 11 ~ x: str = ab | "#); } @@ -2709,33 +2710,22 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 - | - 1 + from ty_extensions._internal import Unknown - 2 + from string.templatelib import Template - 3 | - - a = [1, 2] - - b = [1.0, 2.0] - - c = [True, False] - - d = [None, None] - - e = ["hel", "lo"] - - f = ['the', 're'] - - g = [f"{ft}", f"{ft}"] - - h = [t"wow %d", t"wow %d"] - - i = [b'/x01', b'/x02'] - - j = [+1, +2.0] - - k = [-1, -2.0] - 4 + a: list[int] = [1, 2] - 5 + b: list[float] = [1.0, 2.0] - 6 + c: list[bool] = [True, False] - 7 + d: list[None | Unknown] = [None, None] - 8 + e: list[str] = ["hel", "lo"] - 9 + f: list[str] = ['the', 're'] - 10 + g: list[str] = [f"{ft}", f"{ft}"] - 11 + h: list[Template] = [t"wow %d", t"wow %d"] - 12 + i: list[bytes] = [b'/x01', b'/x02'] - 13 + j: list[float] = [+1, +2.0] - 14 + k: list[float] = [-1, -2.0] + --> main.py:1:1 + | + 1 + from ty_extensions._internal import Unknown + 2 ~ from string.templatelib import Template + 3 + + 4 ~ a: list[int] = [1, 2] + 5 ~ b: list[float] = [1.0, 2.0] + 6 ~ c: list[bool] = [True, False] + 7 ~ d: list[None | Unknown] = [None, None] + 8 ~ e: list[str] = ["hel", "lo"] + 9 ~ f: list[str] = ['the', 're'] + 10 ~ g: list[str] = [f"{ft}", f"{ft}"] + 11 ~ h: list[Template] = [t"wow %d", t"wow %d"] + 12 ~ i: list[bytes] = [b'/x01', b'/x02'] + 13 ~ j: list[float] = [+1, +2.0] + 14 ~ k: list[float] = [-1, -2.0] | "#); } @@ -2906,12 +2896,14 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 4 | self.x: int = 1 + 5 | 6 | x = MyClass() - - y = (MyClass(), MyClass()) - 7 + y: tuple[MyClass, MyClass] = (MyClass(), MyClass()) + 7 ~ y: tuple[MyClass, MyClass] = (MyClass(), MyClass()) 8 | a, b = MyClass(), MyClass() + 9 | c, d = (MyClass(), MyClass()) | "); } @@ -3365,17 +3357,15 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 - | - 6 | - - x = MyClass([42], ("a", "b")) - - y = (MyClass([42], ("a", "b")), MyClass([42], ("a", "b"))) - - a, b = MyClass([42], ("a", "b")), MyClass([42], ("a", "b")) - - c, d = (MyClass([42], ("a", "b")), MyClass([42], ("a", "b"))) - 7 + x: MyClass[int, str] = MyClass([42], y=("a", "b")) - 8 + y: tuple[MyClass[int, str], MyClass[int, str]] = (MyClass([42], y=("a", "b")), MyClass([42], y=("a", "b"))) - 9 + a, b = MyClass([42], y=("a", "b")), MyClass([42], y=("a", "b")) - 10 + c, d = (MyClass([42], y=("a", "b")), MyClass([42], y=("a", "b"))) + --> main.py:1:1 + | + 4 | self.x = x + 5 | self.y = y + 6 | + 7 ~ x: MyClass[int, str] = MyClass([42], y=("a", "b")) + 8 ~ y: tuple[MyClass[int, str], MyClass[int, str]] = (MyClass([42], y=("a", "b")), MyClass([42], y=("a", "b"))) + 9 ~ a, b = MyClass([42], y=("a", "b")), MyClass([42], y=("a", "b")) + 10 ~ c, d = (MyClass([42], y=("a", "b")), MyClass([42], y=("a", "b"))) | "#); } @@ -3432,11 +3422,11 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | 2 | def foo(x: int): pass - - foo(1) - 3 + foo(x=1) + 3 ~ foo(x=1) | "); } @@ -3473,11 +3463,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 3 | x = 1 + 4 | y = 2 5 | foo(x) - - foo(y) - 6 + foo(x=y) + 6 ~ foo(x=y) | "); } @@ -3522,11 +3513,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | - 9 | foo(val.x) - - foo(val.y) - 10 + foo(x=val.y) + 7 | val = MyClass() + 8 | + 9 | foo(val.x) + 10 ~ foo(x=val.y) | "); } @@ -3572,11 +3564,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | - 9 | foo(x.x) - - foo(x.y) - 10 + foo(x=x.y) + 7 | x = MyClass() + 8 | + 9 | foo(x.x) + 10 ~ foo(x=x.y) | "); } @@ -3625,11 +3618,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 9 | val = MyClass() + 10 | 11 | foo(val.x()) - - foo(val.y()) - 12 + foo(x=val.y()) + 12 ~ foo(x=val.y()) | "); } @@ -3682,11 +3676,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 11 | val = MyClass() + 12 | 13 | foo(val.x()[0]) - - foo(val.y()[1]) - 14 + foo(x=val.y()[1]) + 14 ~ foo(x=val.y()[1]) | "); } @@ -3769,17 +3764,15 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | 2 | def foo(x: int): pass - - x = [1] - - y = [2] - 3 + x: list[int] = [1] - 4 + y: list[int] = [2] + 3 ~ x: list[int] = [1] + 4 ~ y: list[int] = [2] 5 | 6 | foo(x[0]) - - foo(y[0]) - 7 + foo(x=y[0]) + 7 ~ foo(x=y[0]) | "); } @@ -3875,11 +3868,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | + 2 | def foo(a: str, b: int, c: int, d: str): ... 3 | t: tuple[int, int] = (23, 42) - - foo('foo', *t, d='bar') - 4 + foo(a='foo', *t, d='bar') + 4 ~ foo(a='foo', *t, d='bar') | "); } @@ -3935,11 +3929,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | + 2 | def foo(a: str, b: int, c: str): ... 3 | t: tuple[int] = (42,) - - foo('foo', *t, 'bar') - 4 + foo('foo', *t, c='bar') + 4 ~ foo('foo', *t, c='bar') | "); } @@ -3983,11 +3978,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | + 2 | def foo(a: int, b: int): ... 3 | t: tuple[int] = (2,) - - foo(1, *t) - 4 + foo(a=1, *t) + 4 ~ foo(a=1, *t) | "); } @@ -4046,11 +4042,11 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | 2 | def foo(x: int, /, y: int): pass - - foo(1, 2) - 3 + foo(1, y=2) + 3 ~ foo(1, y=2) | "); } @@ -4126,13 +4122,13 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | + 2 | class Foo: 3 | def __init__(self, x: int): pass - - Foo(1) - - f = Foo(1) - 4 + Foo(x=1) - 5 + f = Foo(x=1) + 4 ~ Foo(x=1) + 5 ~ f = Foo(x=1) | "); } @@ -4184,11 +4180,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 5 | x: int + 6 | y: str 7 | - - Foo(1, 'a') - 8 + Foo(1, y='a') + 8 ~ Foo(1, y='a') | "); } @@ -4234,13 +4231,13 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | + 2 | class Foo: 3 | def __new__(cls, x: int): pass - - Foo(1) - - f = Foo(1) - 4 + Foo(x=1) - 5 + f = Foo(x=1) + 4 ~ Foo(x=1) + 5 ~ f = Foo(x=1) | "); } @@ -4277,11 +4274,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 3 | def __call__(self, x: int): pass + 4 | class Foo(metaclass=MetaFoo): 5 | pass - - Foo(1) - 6 + Foo(x=1) + 6 ~ Foo(x=1) | "); } @@ -4331,11 +4329,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | + 2 | class Foo: 3 | def bar(self, y: int): pass - - Foo().bar(2) - 4 + Foo().bar(y=2) + 4 ~ Foo().bar(y=2) | "); } @@ -4401,13 +4400,13 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 11 | class Child(Parent): pass + 12 | 13 | def f(parent: Parent, child: Child): - - parent.choose(1) - - child.choose(2) - 14 + parent.choose(parent_value=1) - 15 + child.choose(child_value=2) + 14 ~ parent.choose(parent_value=1) + 15 ~ child.choose(child_value=2) | "#); } @@ -4442,11 +4441,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 2 | class Foo: + 3 | @classmethod 4 | def bar(cls, y: int): pass - - Foo.bar(2) - 5 + Foo.bar(y=2) + 5 ~ Foo.bar(y=2) | "); } @@ -4481,11 +4481,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 2 | class Foo: + 3 | @staticmethod 4 | def bar(y: int): pass - - Foo.bar(2) - 5 + Foo.bar(y=2) + 5 ~ Foo.bar(y=2) | "); } @@ -4529,13 +4530,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | 2 | def foo(x: int | str): pass - - foo(1) - - foo('abc') - 3 + foo(x=1) - 4 + foo(x='abc') + 3 ~ foo(x=1) + 4 ~ foo(x='abc') | "); } @@ -4588,11 +4588,11 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | 2 | def foo(x: int, y: str, z: bool): pass - - foo(1, 'hello', True) - 3 + foo(1, 'hello', z=True) + 3 ~ foo(1, 'hello', z=True) | "); } @@ -4649,11 +4649,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 2 | def add(x: int, b, y: int) -> int: + 3 | return x + y 4 | - - total = add(3, 2, y=4) - 5 + total: int = add(3, b=2, y=4) + 5 ~ total: int = add(3, b=2, y=4) | "); } @@ -4684,11 +4685,11 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | 2 | def foo(x: int, y: str, z: bool): pass - - foo(1, z=True, y='hello') - 3 + foo(x=1, z=True, y='hello') + 3 ~ foo(x=1, z=True, y='hello') | "); } @@ -4721,11 +4722,11 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | 2 | def foo(x: int, y: str): pass - - foo(y='hello', 1) - 3 + foo(y='hello', y=1) + 3 ~ foo(y='hello', y=1) | "); } @@ -4815,15 +4816,13 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | 2 | def foo(x: int, y: str = 'default', z: bool = False): pass - - foo(1) - - foo(1, 'custom') - - foo(1, 'custom', True) - 3 + foo(x=1) - 4 + foo(1, y='custom') - 5 + foo(1, 'custom', z=True) + 3 ~ foo(x=1) + 4 ~ foo(1, y='custom') + 5 ~ foo(1, 'custom', z=True) | "); } @@ -4923,11 +4922,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | - 9 | - - baz(foo(5), bar(bar('test')), True) - 10 + baz(foo(x=5), bar(y=bar(y='test')), c=True) + 7 | + 8 | def baz(a: int, b: str, c: bool): pass + 9 | + 10 ~ baz(foo(x=5), bar(y=bar(y='test')), c=True) | "); } @@ -4979,11 +4979,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 5 | def bar(self, name: str) -> 'A': + 6 | return self 7 | def baz(self): pass - - A().foo(42).bar('test').baz() - 8 + A().foo(value=42).bar(name='test').baz() + 8 ~ A().foo(value=42).bar(name='test').baz() | "); } @@ -5020,11 +5021,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 2 | def foo(x: str) -> str: + 3 | return x 4 | def bar(y: int): pass - - bar(y=foo('test')) - 5 + bar(y=foo(x='test')) + 5 ~ bar(y=foo(x='test')) | "); } @@ -5070,13 +5072,13 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | + 2 | foo = lambda x: x * 2 3 | bar = lambda a, b: a + b - - foo(5) - - bar(1, 2) - 4 + foo(x=5) - 5 + bar(1, b=2) + 4 ~ foo(x=5) + 5 ~ bar(1, b=2) | "); } @@ -5111,11 +5113,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | + 2 | from typing import LiteralString 3 | def my_func(x: LiteralString): - - y = x - 4 + y: LiteralString = x + 4 ~ y: LiteralString = x 5 | my_func(x="hello") | "#); @@ -5222,14 +5225,22 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 - | - 1 + from typing import Literal - 2 | - -------------------------------------------------------------------------------- + --> main.py:1:1 + | + 1 + from typing import Literal + 2 + + 3 | def branch(cond: int): + 4 | if cond < 10: + 5 | x = 1 + 6 | elif cond < 20: + 7 | x = 2 + 8 | elif cond < 30: + 9 | x = 3 + 10 | elif cond < 40: + 11 | x = "hello" + 12 | else: 13 | x = None - - y = x - 14 + y: Literal[1, 2, 3, "hello"] | None = x + 14 ~ y: Literal[1, 2, 3, "hello"] | None = x | "#); } @@ -5321,11 +5332,11 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | 2 | def f(x: list[str]): - - y = type(x) - 3 + y: type[list[str]] = type(x) + 3 ~ y: type[list[str]] = type(x) | "); } @@ -5412,13 +5423,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | 2 | def foo(a: int, b: str, /, c: float, d: bool = True, *, e: int, f: str = 'default'): pass - - foo(1, 'pos', 3.14, False, e=42) - - foo(1, 'pos', 3.14, e=42, f='custom') - 3 + foo(1, 'pos', 3.14, d=False, e=42) - 4 + foo(1, 'pos', c=3.14, e=42, f='custom') + 3 ~ foo(1, 'pos', 3.14, d=False, e=42) + 4 ~ foo(1, 'pos', c=3.14, e=42, f='custom') | "); } @@ -5458,11 +5468,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | + 2 | from foo import bar 3 | - - bar(1) - 4 + bar(x=1) + 4 ~ bar(x=1) | "); } @@ -5522,13 +5533,13 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 8 | def foo(x): + 9 | return x 10 | - - foo(42) - - foo('hello') - 11 + foo(x=42) - 12 + foo(x='hello') + 11 ~ foo(x=42) + 12 ~ foo(x='hello') | "); } @@ -5590,11 +5601,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 8 | def S(): + 9 | pass 10 | - - b = S('x', 'y') - 11 + b: Sequence[str] = S('x', 'y') + 11 ~ b: Sequence[str] = S('x', 'y') | "); } @@ -5646,11 +5658,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 8 | def f(x): + 9 | return x 10 | - - f([]) - 11 + f(x=[]) + 11 ~ f(x=[]) | "); } @@ -5804,15 +5817,14 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 4 | my_param2 = 1 + 5 | parameter = 1 6 | - - foo(param2) - - foo(my_param2) - - foo(parameter) - 7 + foo(param=param2) - 8 + foo(param=my_param2) - 9 + foo(param=parameter) + 7 ~ foo(param=param2) + 8 ~ foo(param=my_param2) + 9 ~ foo(param=parameter) | "); } @@ -5863,11 +5875,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 10 | foo(FOCUS_RANGE) + 11 | foo(focus_range_end) 12 | foo(start_focus_range) - - foo(focus_end_range) - 13 + foo(focus_range=focus_end_range) + 13 ~ foo(focus_range=focus_end_range) | "); } @@ -5902,11 +5915,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | + 2 | def foo(x: int): pass 3 | def bar(y: int): pass - - foo(1) - 4 + foo(x=1) + 4 ~ foo(x=1) 5 | bar(2) | "); @@ -5938,11 +5952,11 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | 2 | def foo(_x: int, y: int): pass - - foo(1, 2) - 3 + foo(1, y=2) + 3 ~ foo(1, y=2) | "); } @@ -5992,11 +6006,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 4 | y: int + 5 | ): ... 6 | - - foo(1, 2) - 7 + foo(1, y=2) + 7 ~ foo(1, y=2) | "); } @@ -6384,12 +6399,14 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | + 2 | from typing import NewType 3 | - - N = NewType('N', str) - 4 + N = NewType('N', tp=str) + 4 ~ N = NewType('N', tp=str) 5 | + 6 | Y = N | "); } @@ -6481,11 +6498,11 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | 2 | from typing import Protocol, TypeVar - - T = TypeVar('T') - 3 + T = TypeVar(name='T') + 3 ~ T = TypeVar(name='T') 4 | Strange = Protocol[T] | "); @@ -6517,11 +6534,11 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | 2 | from typing import ParamSpec - - P = ParamSpec('P') - 3 + P = ParamSpec(name='P') + 3 ~ P = ParamSpec(name='P') | "); } @@ -6563,11 +6580,11 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | 2 | from typing_extensions import TypeAliasType - - A = TypeAliasType('A', str) - 3 + A = TypeAliasType('A', value=str) + 3 ~ A = TypeAliasType('A', value=str) | "); } @@ -6598,11 +6615,11 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 1 | 2 | from typing_extensions import TypeVarTuple - - Ts = TypeVarTuple('Ts') - 3 + Ts = TypeVarTuple(name='Ts') + 3 ~ Ts = TypeVarTuple(name='Ts') | "); } @@ -6663,11 +6680,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 3 | from ty_extensions import Top + 4 | 5 | def f(xyxy: Top[list[Any]]): - - x = xyxy - 6 + x: Top[list[Any]] = xyxy + 6 ~ x: Top[list[Any]] = xyxy | "); } @@ -6812,14 +6830,13 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | 1 + from bar import D - 2 | + 2 + 3 | import foo 4 | - - a = foo.C().foo() - 5 + a: foo.B[foo.A[D[int, list[str | foo.A[foo.B[int]]]]]] = foo.C().foo() + 5 ~ a: foo.B[foo.A[D[int, list[str | foo.A[foo.B[int]]]]]] = foo.C().foo() | "); } @@ -6964,15 +6981,13 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | 1 + from bar import D - 2 | - - from foo import C - 3 + from foo import C, B, A + 2 + + 3 ~ from foo import C, B, A 4 | - - a = C().foo() - 5 + a: B[A[D[int, list[str | A[B[int]]]]]] = C().foo() + 5 ~ a: B[A[D[int, list[str | A[B[int]]]]]] = C().foo() | "); } @@ -7049,11 +7064,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 3 | + 4 | class Baz: ... 5 | - - a = D(Baz) - 6 + a: D[Baz] = D(x=Baz) + 6 ~ a: D[Baz] = D(x=Baz) | "); } @@ -7112,15 +7128,13 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | 1 | - - from typing import Any - 2 + from typing import Any, Literal + 2 ~ from typing import Any, Literal 3 | 4 | def foo(x: Any): - - a = getattr(x, 'foo', "some") - 5 + a: Any | Literal["some"] = getattr(x, 'foo', "some") + 5 ~ a: Any | Literal["some"] = getattr(x, 'foo', "some") | "#); } @@ -7197,15 +7211,14 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | 1 + from typing import TypeVar - 2 + from typing import Any - 3 | + 2 ~ from typing import Any + 3 + 4 | from foo import foo 5 | - - a = foo() - 6 + a: dict[TypeVar, Any] | None = foo() + 6 ~ a: dict[TypeVar, Any] | None = foo() | "); } @@ -7279,15 +7292,14 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | 1 + import bar - 2 + import baz - 3 | + 2 ~ import baz + 3 + 4 | from foo import foo 5 | - - a = foo() - 6 + a: bar.A | baz.A = foo() + 6 ~ a: bar.A | baz.A = foo() | "); } @@ -7399,16 +7411,15 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | 1 + import bar - 2 + import baz - 3 | + 2 ~ import baz + 3 + 4 | from foo import foo 5 | from bar import B 6 | - - a = foo() - 7 + a: bar.A | baz.A | list[bar.A | baz.A] = foo() + 7 ~ a: bar.A | baz.A | list[bar.A | baz.A] = foo() | "); } @@ -7489,11 +7500,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 8 | class B[T]: + 9 | x: T 10 | - - b = B(foo.A()) - 11 + b: B[foo.A] = B(x=foo.A()) + 11 ~ b: B[foo.A] = B(x=foo.A()) | "); } @@ -7632,11 +7644,12 @@ Source with applied edits: --------------------------------------------- info[inlay-hint-edit]: Inlay hint edits - --> main.py:1:1 + --> main.py:1:1 | + 5 | def wrap[T](x: T) -> list[T]: + 6 | return [x] 7 | - - y = wrap(Outer.Inner()) - 8 + y = wrap(x=Outer.Inner()) + 8 ~ y = wrap(x=Outer.Inner()) | "); } diff --git a/crates/ty_ide/src/snapshots/ty_ide__code_action__tests__add_ignore_trailing_whitespace.snap b/crates/ty_ide/src/snapshots/ty_ide__code_action__tests__add_ignore_trailing_whitespace.snap index 40cf35facd50b..f4ed047b1df92 100644 --- a/crates/ty_ide/src/snapshots/ty_ide__code_action__tests__add_ignore_trailing_whitespace.snap +++ b/crates/ty_ide/src/snapshots/ty_ide__code_action__tests__add_ignore_trailing_whitespace.snap @@ -8,6 +8,5 @@ info[code-action]: Ignore 'unresolved-reference' for this line 1 | b = a / 10 | ^ | - - b = a / 10 -1 + b = a / 10 # ty: ignore[unresolved-reference] - | +1 | b = a / 10 # ty: ignore[unresolved-reference] + | ++++++++++++++++++++++++++++++++++ diff --git a/crates/ty_python_semantic/resources/mdtest/call/type.md b/crates/ty_python_semantic/resources/mdtest/call/type.md index 1d97de797cce9..4d0a340dbe98f 100644 --- a/crates/ty_python_semantic/resources/mdtest/call/type.md +++ b/crates/ty_python_semantic/resources/mdtest/call/type.md @@ -693,10 +693,8 @@ error[inconsistent-mro]: Cannot create a consistent method resolution order (MRO | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: Move `Generic[K, V]` to the end of the bases list | -6 | # error: [missing-type-argument] - - class Foo1(Generic[K, V], dict): ... # snapshot: inconsistent-mro +7 - class Foo1(Generic[K, V], dict): ... # snapshot: inconsistent-mro 7 + class Foo1(dict, Generic[K, V]): ... # snapshot: inconsistent-mro -8 | # fmt: off | note: This is an unsafe fix and may change runtime behavior ``` @@ -730,13 +728,11 @@ error[inconsistent-mro]: Cannot create a consistent method resolution order (MRO | |_^ help: Move `Generic[K, V]` to the end of the bases list | -11 | # comment1 - - Generic[K, V], # comment2 - - # comment3 - - # error: [missing-type-argument] - - dict # comment4 +12 - Generic[K, V], # comment2 +13 - # comment3 +14 - # error: [missing-type-argument] +15 - dict # comment4 12 + dict, Generic[K, V] # comment4 -13 | # comment5 | note: This is an unsafe fix and may change runtime behavior ``` @@ -754,10 +750,8 @@ error[inconsistent-mro]: Cannot create a consistent method resolution order (MRO | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Move `Generic[K, V]` to the end of the bases list | -18 | # error: [missing-type-argument] - - class Foo3(Generic[K, V], dict, metaclass=type): ... # snapshot: inconsistent-mro +19 - class Foo3(Generic[K, V], dict, metaclass=type): ... # snapshot: inconsistent-mro 19 + class Foo3(dict, Generic[K, V], metaclass=type): ... # snapshot: inconsistent-mro -20 | class Foo4( # snapshot: inconsistent-mro | note: This is an unsafe fix and may change runtime behavior ``` @@ -795,13 +789,11 @@ error[inconsistent-mro]: Cannot create a consistent method resolution order (MRO | |_^ help: Move `Generic[K, V]` to the end of the bases list | -21 | # comment1 - - Generic[K, V], # comment2 - - # comment3 - - # error: [missing-type-argument] - - dict, # comment4 +22 - Generic[K, V], # comment2 +23 - # comment3 +24 - # error: [missing-type-argument] +25 - dict, # comment4 22 + dict, Generic[K, V], # comment4 -23 | # comment5 | note: This is an unsafe fix and may change runtime behavior ``` diff --git a/crates/ty_python_semantic/resources/mdtest/directives/cast.md b/crates/ty_python_semantic/resources/mdtest/directives/cast.md index 0311c79766067..37faec64df969 100644 --- a/crates/ty_python_semantic/resources/mdtest/directives/cast.md +++ b/crates/ty_python_semantic/resources/mdtest/directives/cast.md @@ -115,10 +115,8 @@ warning[redundant-cast]: Value is already of type `int` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove the redundant `cast` | -4 | # snapshot: redundant-cast - - cast(int, secrets.randbelow(10)) +5 - cast(int, secrets.randbelow(10)) 5 + secrets.randbelow(10) -6 | # snapshot: redundant-cast | ``` @@ -135,10 +133,8 @@ warning[redundant-cast]: Value is already of type `int` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove the redundant `cast` | -6 | # snapshot: redundant-cast - - cast(val=secrets.randbelow(10), typ=int) +7 - cast(val=secrets.randbelow(10), typ=int) 7 + secrets.randbelow(10) -8 | def f(x: int, y: int, z: int) -> int: | ``` @@ -156,10 +152,8 @@ warning[redundant-cast]: Value is already of type `int` | ^^^^^^^^^^^^^^^^ help: Remove the redundant `cast` | -9 | # snapshot: redundant-cast - - return cast(int, x + y) * z +10 - return cast(int, x + y) * z 10 + return (x + y) * z -11 | def g(x: int, y: int) -> int: | ``` @@ -177,10 +171,8 @@ warning[redundant-cast]: Value is already of type `int` | ^^^^^^^^^^^^^^^^ help: Remove the redundant `cast` | -12 | # snapshot: redundant-cast - - return -cast(int, x + y) +13 - return -cast(int, x + y) 13 + return -(x + y) -14 | def h(x: int, y: int) -> None: | ``` @@ -198,8 +190,7 @@ warning[redundant-cast]: Value is already of type `int` | ^^^^^^^^^^^^^^^^ help: Remove the redundant `cast` | -15 | # snapshot: redundant-cast - - print(cast(int, x + y)) +16 - print(cast(int, x + y)) 16 + print(x + y) | ``` diff --git a/crates/ty_python_semantic/resources/mdtest/regression/3525_character_split_notebook.md b/crates/ty_python_semantic/resources/mdtest/regression/3525_character_split_notebook.md index e3909af220a72..7959262ea52f5 100644 --- a/crates/ty_python_semantic/resources/mdtest/regression/3525_character_split_notebook.md +++ b/crates/ty_python_semantic/resources/mdtest/regression/3525_character_split_notebook.md @@ -37,10 +37,9 @@ warning[unused-ignore-comment]: Unused `ty: ignore` directive 2 | x = 1 # ty: ignore[unresolved-reference] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove the unused suppression comment - ::: cell 2 + ::: cell 2:1:6 | -1 | # snapshot - - x = 1 # ty: ignore[unresolved-reference] -2 + x = 1 +1 - x = 1 # ty: ignore[unresolved-reference] +1 + x = 1 | ``` diff --git "a/crates/ty_python_semantic/resources/mdtest/snapshots/assignment_diagnosti\342\200\246_-_Subscript_assignment\342\200\246_-_Misspelled_key_for_`\342\200\246_(7cf0fa634e2a2d59).snap" "b/crates/ty_python_semantic/resources/mdtest/snapshots/assignment_diagnosti\342\200\246_-_Subscript_assignment\342\200\246_-_Misspelled_key_for_`\342\200\246_(7cf0fa634e2a2d59).snap" index b902d9d89b0d1..fcf11066c0058 100644 --- "a/crates/ty_python_semantic/resources/mdtest/snapshots/assignment_diagnosti\342\200\246_-_Subscript_assignment\342\200\246_-_Misspelled_key_for_`\342\200\246_(7cf0fa634e2a2d59).snap" +++ "b/crates/ty_python_semantic/resources/mdtest/snapshots/assignment_diagnosti\342\200\246_-_Subscript_assignment\342\200\246_-_Misspelled_key_for_`\342\200\246_(7cf0fa634e2a2d59).snap" @@ -33,8 +33,7 @@ error[invalid-key]: Unknown key "Retries" for TypedDict `Config` | | | TypedDict `Config` | -6 | def _(config: Config) -> None: - - config["Retries"] = 30.0 # error: [invalid-key] +7 - config["Retries"] = 30.0 # error: [invalid-key] 7 + config["retries"] = 30.0 # error: [invalid-key] | note: This is an unsafe fix and may change runtime behavior diff --git "a/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_A_possibly-undefined\342\200\246_(fc7b496fd1986deb).snap" "b/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_A_possibly-undefined\342\200\246_(fc7b496fd1986deb).snap" index bde456cf8292c..47fca6c1b33df 100644 --- "a/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_A_possibly-undefined\342\200\246_(fc7b496fd1986deb).snap" +++ "b/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_A_possibly-undefined\342\200\246_(fc7b496fd1986deb).snap" @@ -105,10 +105,8 @@ info: `A.method1` is decorated with `@final`, forbidding overrides | ------- `A.method1` defined here help: Remove the override of `method1` | -39 | class B(A): - - def method1(self) -> None: ... # error: [override-of-final-method] +40 - def method1(self) -> None: ... # error: [override-of-final-method] 40 + # error: [override-of-final-method] -41 | def method2(self) -> None: ... # error: [override-of-final-method] | note: This is an unsafe fix and may change runtime behavior @@ -129,10 +127,8 @@ info: `A.method2` is decorated with `@final`, forbidding overrides | ------- `A.method2` defined here help: Remove the override of `method2` | -40 | def method1(self) -> None: ... # error: [override-of-final-method] - - def method2(self) -> None: ... # error: [override-of-final-method] +41 - def method2(self) -> None: ... # error: [override-of-final-method] 41 + # error: [override-of-final-method] -42 | def method3(self) -> None: ... # error: [override-of-final-method] | note: This is an unsafe fix and may change runtime behavior @@ -153,10 +149,8 @@ info: `A.method3` is decorated with `@final`, forbidding overrides | ------- `A.method3` defined here help: Remove the override of `method3` | -41 | def method2(self) -> None: ... # error: [override-of-final-method] - - def method3(self) -> None: ... # error: [override-of-final-method] +42 - def method3(self) -> None: ... # error: [override-of-final-method] 42 + # error: [override-of-final-method] -43 | | note: This is an unsafe fix and may change runtime behavior diff --git "a/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_Cannot_override_a_me\342\200\246_(338615109711a91b).snap" "b/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_Cannot_override_a_me\342\200\246_(338615109711a91b).snap" index 4e28e306ede31..bbb3ccd73601a 100644 --- "a/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_Cannot_override_a_me\342\200\246_(338615109711a91b).snap" +++ "b/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_Cannot_override_a_me\342\200\246_(338615109711a91b).snap" @@ -145,10 +145,7 @@ info: `Parent.foo` is decorated with `@final`, forbidding overrides | --- `Parent.foo` defined here help: Remove the override of `foo` | -41 | # error: [override-of-final-method] "Cannot override final member `foo` from superclass `Parent`" - - def foo(self): ... -42 + -43 | @property +42 - def foo(self): ... | note: This is an unsafe fix and may change runtime behavior @@ -222,11 +219,9 @@ info: `Parent.class_method1` is decorated with `@final`, forbidding overrides | ------------- `Parent.class_method1` defined here help: Remove the override of `class_method1` | -52 | def my_property3(self) -> None: ... - - @classmethod - - def class_method1(cls) -> int: ... # error: [override-of-final-method] +53 - @classmethod +54 - def class_method1(cls) -> int: ... # error: [override-of-final-method] 53 + # error: [override-of-final-method] -54 | @staticmethod | note: This is an unsafe fix and may change runtime behavior @@ -248,11 +243,9 @@ info: `Parent.static_method1` is decorated with `@final`, forbidding overrides | -------------- `Parent.static_method1` defined here help: Remove the override of `static_method1` | -54 | def class_method1(cls) -> int: ... # error: [override-of-final-method] - - @staticmethod - - def static_method1() -> int: ... # error: [override-of-final-method] +55 - @staticmethod +56 - def static_method1() -> int: ... # error: [override-of-final-method] 55 + # error: [override-of-final-method] -56 | @classmethod | note: This is an unsafe fix and may change runtime behavior @@ -273,11 +266,9 @@ info: `Parent.class_method2` is decorated with `@final`, forbidding overrides | ------------- `Parent.class_method2` defined here help: Remove the override of `class_method2` | -56 | def static_method1() -> int: ... # error: [override-of-final-method] - - @classmethod - - def class_method2(cls) -> int: ... # error: [override-of-final-method] +57 - @classmethod +58 - def class_method2(cls) -> int: ... # error: [override-of-final-method] 57 + # error: [override-of-final-method] -58 | @staticmethod | note: This is an unsafe fix and may change runtime behavior @@ -298,11 +289,9 @@ info: `Parent.static_method2` is decorated with `@final`, forbidding overrides | -------------- `Parent.static_method2` defined here help: Remove the override of `static_method2` | -58 | def class_method2(cls) -> int: ... # error: [override-of-final-method] - - @staticmethod - - def static_method2() -> int: ... # error: [override-of-final-method] +59 - @staticmethod +60 - def static_method2() -> int: ... # error: [override-of-final-method] 59 + # error: [override-of-final-method] -60 | def decorated_1(self): ... # TODO: should emit [override-of-final-method] | note: This is an unsafe fix and may change runtime behavior @@ -339,13 +328,10 @@ info: `Parent.foo` is decorated with `@final`, forbidding overrides | --- `Parent.foo` defined here help: Remove the override of `foo` | -71 | # concern of Liskov. - - @staticmethod - - # error: [override-of-final-method] - - # error: [invalid-method-override] - - def foo(): ... -72 + -73 | @property +72 - @staticmethod +73 - # error: [override-of-final-method] +74 - # error: [invalid-method-override] +75 - def foo(): ... | note: This is an unsafe fix and may change runtime behavior @@ -405,8 +391,7 @@ info: `Foo.bar` is decorated with `@final`, forbidding overrides | --- `Foo.bar` defined here help: Remove the override of `bar` | -112 | class Baz(Foo): - - def bar(self): ... # error: [override-of-final-method] +113 - def bar(self): ... # error: [override-of-final-method] 113 + pass # error: [override-of-final-method] | note: This is an unsafe fix and may change runtime behavior diff --git "a/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_Diagnostic_edge_case\342\200\246_(2389d52c5ecfa2bd).snap" "b/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_Diagnostic_edge_case\342\200\246_(2389d52c5ecfa2bd).snap" index 3e3f8481ac8c1..3e9b3631a3096 100644 --- "a/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_Diagnostic_edge_case\342\200\246_(2389d52c5ecfa2bd).snap" +++ "b/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_Diagnostic_edge_case\342\200\246_(2389d52c5ecfa2bd).snap" @@ -46,8 +46,7 @@ info: `module1.Foo.f` is decorated with `@final`, forbidding overrides | - `module1.Foo.f` defined here help: Remove the override of `f` | -3 | class Foo(module1.Foo): - - def f(self): ... # error: [override-of-final-method] +4 - def f(self): ... # error: [override-of-final-method] 4 + pass # error: [override-of-final-method] | note: This is an unsafe fix and may change runtime behavior diff --git "a/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_Only_the_first_`@fin\342\200\246_(9863b583f4c651c5).snap" "b/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_Only_the_first_`@fin\342\200\246_(9863b583f4c651c5).snap" index 47bd4c9ad4fbc..625d59fb1eb33 100644 --- "a/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_Only_the_first_`@fin\342\200\246_(9863b583f4c651c5).snap" +++ "b/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_Only_the_first_`@fin\342\200\246_(9863b583f4c651c5).snap" @@ -46,11 +46,9 @@ info: `A.f` is decorated with `@final`, forbidding overrides | - `A.f` defined here help: Remove the override of `f` | -7 | class B(A): - - @final - - def f(self): ... # error: [override-of-final-method] +8 - @final +9 - def f(self): ... # error: [override-of-final-method] 8 + pass # error: [override-of-final-method] -9 | | note: This is an unsafe fix and may change runtime behavior @@ -71,10 +69,9 @@ info: `B.f` is decorated with `@final`, forbidding overrides | - `B.f` defined here help: Remove the override of `f` | -11 | class C(B): - - @final - - # we only emit one error here, not two - - def f(self): ... # error: [override-of-final-method] +12 - @final +13 - # we only emit one error here, not two +14 - def f(self): ... # error: [override-of-final-method] 12 + pass # error: [override-of-final-method] | note: This is an unsafe fix and may change runtime behavior diff --git "a/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_Overloaded_methods_d\342\200\246_(861757f48340ed92).snap" "b/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_Overloaded_methods_d\342\200\246_(861757f48340ed92).snap" index 9fa15ee4303f4..53bb5e139d854 100644 --- "a/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_Overloaded_methods_d\342\200\246_(861757f48340ed92).snap" +++ "b/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_Overloaded_methods_d\342\200\246_(861757f48340ed92).snap" @@ -144,14 +144,8 @@ info: `Good.bar` is decorated with `@final`, forbidding overrides | --- `Good.bar` defined here help: Remove all overloads for `bar` | -15 | class ChildOfGood(Good): - - @overload - - def bar(self, x: str) -> str: ... - - @overload - - def bar(self, x: int) -> int: ... # error: [override-of-final-method] -16 + -17 + # error: [override-of-final-method] -18 | @overload +16 ~ +17 ~ # error: [override-of-final-method] | note: This is an unsafe fix and may change runtime behavior @@ -173,14 +167,8 @@ info: `Good.baz` is decorated with `@final`, forbidding overrides | --- `Good.baz` defined here help: Remove all overloads for `baz` | -19 | def bar(self, x: int) -> int: ... # error: [override-of-final-method] - - @overload - - def baz(self, x: str) -> str: ... - - @overload - - def baz(self, x: int) -> int: ... # error: [override-of-final-method] -20 + -21 + # error: [override-of-final-method] -22 | +20 ~ +21 ~ # error: [override-of-final-method] | note: This is an unsafe fix and may change runtime behavior @@ -231,14 +219,8 @@ info: `Bad.bar` is decorated with `@final`, forbidding overrides | --- `Bad.bar` defined here help: Remove all overloads for `bar` | -39 | class ChildOfBad(Bad): - - @overload - - def bar(self, x: str) -> str: ... - - @overload - - def bar(self, x: int) -> int: ... # error: [override-of-final-method] -40 + -41 + # error: [override-of-final-method] -42 | @overload +40 ~ +41 ~ # error: [override-of-final-method] | note: This is an unsafe fix and may change runtime behavior @@ -257,13 +239,8 @@ info: `Bad.baz` is decorated with `@final`, forbidding overrides | --- `Bad.baz` defined here help: Remove all overloads for `baz` | -43 | def bar(self, x: int) -> int: ... # error: [override-of-final-method] - - @overload - - def baz(self, x: str) -> str: ... - - @overload - - def baz(self, x: int) -> int: ... # error: [override-of-final-method] -44 + -45 + # error: [override-of-final-method] +44 ~ +45 ~ # error: [override-of-final-method] | note: This is an unsafe fix and may change runtime behavior @@ -284,19 +261,11 @@ info: `Good.f` is decorated with `@final`, forbidding overrides | - `Good.f` defined here help: Remove all overloads and the implementation for `f` | -12 | class ChildOfGood(Good): - - @overload - - def f(self, x: str) -> str: ... - - @overload - - def f(self, x: int) -> int: ... -13 + pass -14 + pass +13 ~ pass +14 ~ pass 15 | 16 | # error: [override-of-final-method] - - def f(self, x: int | str) -> int | str: - - return x -17 + pass -18 | +17 ~ pass | note: This is an unsafe fix and may change runtime behavior diff --git "a/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_Overloads_in_statica\342\200\246_(29a698d9deaf7318).snap" "b/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_Overloads_in_statica\342\200\246_(29a698d9deaf7318).snap" index 4df9b8fbff9b4..72534e9b1d6a1 100644 --- "a/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_Overloads_in_statica\342\200\246_(29a698d9deaf7318).snap" +++ "b/crates/ty_python_semantic/resources/mdtest/snapshots/final.md_-_Tests_for_the_`@typi\342\200\246_-_Overloads_in_statica\342\200\246_(29a698d9deaf7318).snap" @@ -70,14 +70,8 @@ info: `Foo.method` is decorated with `@final`, forbidding overrides | ------ `Foo.method` defined here help: Remove all overloads for `method` | -27 | class Bar(Foo): - - @overload - - def method(self, x: int) -> int: ... - - @overload - - def method(self, x: str) -> str: ... # error: [override-of-final-method] -28 + -29 + # error: [override-of-final-method] -30 | +28 ~ +29 ~ # error: [override-of-final-method] | note: This is an unsafe fix and may change runtime behavior diff --git "a/crates/ty_python_semantic/resources/mdtest/snapshots/invalid.md_-_Tests_for_invalid_ty\342\200\246_-_Diagnostics_for_comm\342\200\246_-_Module-literal_used_\342\200\246_(652fec4fd4a6c63a).snap" "b/crates/ty_python_semantic/resources/mdtest/snapshots/invalid.md_-_Tests_for_invalid_ty\342\200\246_-_Diagnostics_for_comm\342\200\246_-_Module-literal_used_\342\200\246_(652fec4fd4a6c63a).snap" index da667d81c73fc..95682d13b5ed0 100644 --- "a/crates/ty_python_semantic/resources/mdtest/snapshots/invalid.md_-_Tests_for_invalid_ty\342\200\246_-_Diagnostics_for_comm\342\200\246_-_Module-literal_used_\342\200\246_(652fec4fd4a6c63a).snap" +++ "b/crates/ty_python_semantic/resources/mdtest/snapshots/invalid.md_-_Tests_for_invalid_ty\342\200\246_-_Diagnostics_for_comm\342\200\246_-_Module-literal_used_\342\200\246_(652fec4fd4a6c63a).snap" @@ -41,10 +41,8 @@ error[invalid-type-form]: Module `datetime` is not valid in a parameter annotati 3 | def f(x: datetime): ... # error: [invalid-type-form] | ^^^^^^^^ Did you mean to use the module's member `datetime.datetime`? | -2 | - - def f(x: datetime): ... # error: [invalid-type-form] -3 + def f(x: datetime.datetime): ... # error: [invalid-type-form] - | +3 | def f(x: datetime.datetime): ... # error: [invalid-type-form] + | +++++++++ note: This is an unsafe fix and may change runtime behavior ``` @@ -56,10 +54,8 @@ error[invalid-type-form]: Module `PIL.Image` is not valid in a parameter annotat 3 | def g(x: Image): ... # error: [invalid-type-form] | ^^^^^ Did you mean to use the module's member `Image.Image`? | -2 | - - def g(x: Image): ... # error: [invalid-type-form] -3 + def g(x: Image.Image): ... # error: [invalid-type-form] - | +3 | def g(x: Image.Image): ... # error: [invalid-type-form] + | ++++++ note: This is an unsafe fix and may change runtime behavior ``` diff --git "a/crates/ty_python_semantic/resources/mdtest/snapshots/invalid_type_paramet\342\200\246_-_Invalid_Order_of_Leg\342\200\246_(eaa359e8d6b3031d).snap" "b/crates/ty_python_semantic/resources/mdtest/snapshots/invalid_type_paramet\342\200\246_-_Invalid_Order_of_Leg\342\200\246_(eaa359e8d6b3031d).snap" index 99ad2532ab15d..43e0d49148f01 100644 --- "a/crates/ty_python_semantic/resources/mdtest/snapshots/invalid_type_paramet\342\200\246_-_Invalid_Order_of_Leg\342\200\246_(eaa359e8d6b3031d).snap" +++ "b/crates/ty_python_semantic/resources/mdtest/snapshots/invalid_type_paramet\342\200\246_-_Invalid_Order_of_Leg\342\200\246_(eaa359e8d6b3031d).snap" @@ -140,10 +140,8 @@ error[invalid-generic-class]: Cannot both inherit from subscripted `Protocol` an | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove the type parameters from the `Protocol` base | -31 | # error: [invalid-generic-class] - - Protocol[T1, T2, DefaultStrT, T3], +32 - Protocol[T1, T2, DefaultStrT, T3], 32 + Protocol, -33 | Generic[T1, T2, DefaultStrT, T3], | note: This is an unsafe fix and may change runtime behavior diff --git "a/crates/ty_python_semantic/resources/mdtest/snapshots/mro.md_-_Method_Resolution_Or\342\200\246_-_`__bases__`_lists_wi\342\200\246_(ea7ebc83ec359b54).snap" "b/crates/ty_python_semantic/resources/mdtest/snapshots/mro.md_-_Method_Resolution_Or\342\200\246_-_`__bases__`_lists_wi\342\200\246_(ea7ebc83ec359b54).snap" index 4cdfd9adc0a5c..4ae722068fac5 100644 --- "a/crates/ty_python_semantic/resources/mdtest/snapshots/mro.md_-_Method_Resolution_Or\342\200\246_-_`__bases__`_lists_wi\342\200\246_(ea7ebc83ec359b54).snap" +++ "b/crates/ty_python_semantic/resources/mdtest/snapshots/mro.md_-_Method_Resolution_Or\342\200\246_-_`__bases__`_lists_wi\342\200\246_(ea7ebc83ec359b54).snap" @@ -187,10 +187,8 @@ warning[unused-type-ignore-comment]: Unused `type: ignore` directive | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove the unused suppression comment | -62 | # error: [unused-type-ignore-comment] - - ): # type: ignore[ty:duplicate-base] +63 - ): # type: ignore[ty:duplicate-base] 63 + ): -64 | x: int | ``` diff --git "a/crates/ty_python_semantic/resources/mdtest/snapshots/protocols.md_-_Protocols_-_Diagnostics_and_auto\342\200\246_(310665856cfe2424).snap" "b/crates/ty_python_semantic/resources/mdtest/snapshots/protocols.md_-_Protocols_-_Diagnostics_and_auto\342\200\246_(310665856cfe2424).snap" index b04e1b5ef8dc0..007bf33ce138a 100644 --- "a/crates/ty_python_semantic/resources/mdtest/snapshots/protocols.md_-_Protocols_-_Diagnostics_and_auto\342\200\246_(310665856cfe2424).snap" +++ "b/crates/ty_python_semantic/resources/mdtest/snapshots/protocols.md_-_Protocols_-_Diagnostics_and_auto\342\200\246_(310665856cfe2424).snap" @@ -57,10 +57,8 @@ error[invalid-generic-class]: Cannot both inherit from subscripted `Protocol` an | ^^^^^^^^^^^ help: Remove the type parameters from the `Protocol` base | -4 | - - class Foo(Protocol[T], Generic[T]): ... # error: [invalid-generic-class] +5 - class Foo(Protocol[T], Generic[T]): ... # error: [invalid-generic-class] 5 + class Foo(Protocol, Generic[T]): ... # error: [invalid-generic-class] -6 | | note: This is an unsafe fix and may change runtime behavior @@ -77,12 +75,10 @@ error[invalid-generic-class]: Cannot both inherit from subscripted `Protocol` an | |_^ help: Remove the type parameters from the `Protocol` base | -9 | # error: [invalid-generic-class] - - class Bar(Protocol[ - - T, - - ], Generic[T]): ... +10 - class Bar(Protocol[ +11 - T, +12 - ], Generic[T]): ... 10 + class Bar(Protocol, Generic[T]): ... -11 | | note: This is an unsafe fix and may change runtime behavior @@ -100,14 +96,12 @@ error[invalid-generic-class]: Cannot both inherit from subscripted `Protocol` an | |_^ help: Remove the type parameters from the `Protocol` base | -15 | # error: [invalid-generic-class] - - Protocol[ # some comment - - # another comment - - T, # just love my comments - - # very well documented code - - ], # important comma! +16 - Protocol[ # some comment +17 - # another comment +18 - T, # just love my comments +19 - # very well documented code +20 - ], # important comma! 16 + Protocol, # important comma! -17 | # and a newline... | note: This is an unsafe fix and may change runtime behavior @@ -121,8 +115,7 @@ error[invalid-generic-class]: Cannot both inherit from subscripted `Protocol` an | ^^^^^^^^^^^ help: Remove the type parameters from the `Protocol` base | -31 | - - class Foo[T](Protocol[T]): ... # error: [invalid-generic-class] +32 - class Foo[T](Protocol[T]): ... # error: [invalid-generic-class] 32 + class Foo[T](Protocol): ... # error: [invalid-generic-class] | note: This is an unsafe fix and may change runtime behavior diff --git a/crates/ty_python_semantic/resources/mdtest/snapshots/typed_dict.md_-_`TypedDict`_-_Diagnostics_(e5289abf5c570c29).snap b/crates/ty_python_semantic/resources/mdtest/snapshots/typed_dict.md_-_`TypedDict`_-_Diagnostics_(e5289abf5c570c29).snap index aedd64b9907ba..ae3280764959b 100644 --- a/crates/ty_python_semantic/resources/mdtest/snapshots/typed_dict.md_-_`TypedDict`_-_Diagnostics_(e5289abf5c570c29).snap +++ b/crates/ty_python_semantic/resources/mdtest/snapshots/typed_dict.md_-_`TypedDict`_-_Diagnostics_(e5289abf5c570c29).snap @@ -83,10 +83,8 @@ error[invalid-key]: Unknown key "nane" for TypedDict `Person` | | | TypedDict `Person` | -7 | def access_invalid_literal_string_key(person: Person): - - person["nane"] # error: [invalid-key] +8 - person["nane"] # error: [invalid-key] 8 + person["name"] # error: [invalid-key] -9 | | note: This is an unsafe fix and may change runtime behavior @@ -138,10 +136,8 @@ error[invalid-key]: Unknown key "nane" for TypedDict `Person` | | | TypedDict `Person` | -21 | def write_to_non_existing_key(person: Person): - - person["nane"] = "Alice" # error: [invalid-key] +22 - person["nane"] = "Alice" # error: [invalid-key] 22 + person["name"] = "Alice" # error: [invalid-key] -23 | | note: This is an unsafe fix and may change runtime behavior @@ -202,10 +198,8 @@ error[invalid-key]: Unknown key "nane" for TypedDict `Person` | | | TypedDict `Person` | -42 | # error: [invalid-key] - - person['nane'] = "Alice" # fmt: skip +43 - person['nane'] = "Alice" # fmt: skip 43 + person['name'] = "Alice" # fmt: skip -44 | class MovieBase(TypedDict): | note: This is an unsafe fix and may change runtime behavior diff --git "a/crates/ty_python_semantic/resources/mdtest/snapshots/typed_dict.md_-_`TypedDict`_-_Redundant_cast_warni\342\200\246_(75ac240a2d1f7108).snap" "b/crates/ty_python_semantic/resources/mdtest/snapshots/typed_dict.md_-_`TypedDict`_-_Redundant_cast_warni\342\200\246_(75ac240a2d1f7108).snap" index 11b404c26efad..e55f94de0197c 100644 --- "a/crates/ty_python_semantic/resources/mdtest/snapshots/typed_dict.md_-_`TypedDict`_-_Redundant_cast_warni\342\200\246_(75ac240a2d1f7108).snap" +++ "b/crates/ty_python_semantic/resources/mdtest/snapshots/typed_dict.md_-_`TypedDict`_-_Redundant_cast_warni\342\200\246_(75ac240a2d1f7108).snap" @@ -36,10 +36,8 @@ warning[redundant-cast]: Value is already of type `Foo2` | ^^^^^^^^^^^^^^^ help: Remove the redundant `cast` | -9 | foo: Foo2 = {"x": 1} - - _ = cast(Foo2, foo) # error: [redundant-cast] +10 - _ = cast(Foo2, foo) # error: [redundant-cast] 10 + _ = foo # error: [redundant-cast] -11 | _ = cast(Bar2, foo) # error: [redundant-cast] | ``` @@ -53,8 +51,7 @@ warning[redundant-cast]: Value is already of type `Bar2` info: `Bar2` is equivalent to `Foo2` help: Remove the redundant `cast` | -10 | _ = cast(Foo2, foo) # error: [redundant-cast] - - _ = cast(Bar2, foo) # error: [redundant-cast] +11 - _ = cast(Bar2, foo) # error: [redundant-cast] 11 + _ = foo # error: [redundant-cast] | diff --git a/crates/ty_python_semantic/resources/mdtest/suppressions/ty_ignore.md b/crates/ty_python_semantic/resources/mdtest/suppressions/ty_ignore.md index 29b8829eaa4c7..fee4fd0a2843b 100644 --- a/crates/ty_python_semantic/resources/mdtest/suppressions/ty_ignore.md +++ b/crates/ty_python_semantic/resources/mdtest/suppressions/ty_ignore.md @@ -128,8 +128,7 @@ warning[unused-ignore-comment]: Unused `ty: ignore` directive | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove the unused suppression comment | -2 | # snapshot - - a = test + 3 # ty: ignore[possibly-unresolved-reference] +3 - a = test + 3 # ty: ignore[possibly-unresolved-reference] 3 + a = test + 3 | ``` @@ -151,10 +150,8 @@ warning[unused-ignore-comment]: Unused `ty: ignore` directive | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove the unused suppression comment | -2 | # error: [unresolved-reference] - - a = test + 3 # ty: ignore[possibly-unresolved-reference] +3 - a = test + 3 # ty: ignore[possibly-unresolved-reference] 3 + a = test + 3 -4 | print(a) | ``` @@ -184,8 +181,7 @@ warning[unused-ignore-comment]: Unused `ty: ignore` directive: 'unused-ignore-co | ^^^^^^^^^^^^^^^^^^^^^ help: Remove the unused suppression code | -1 | # snapshot - - a = 10 / 0 # ty: ignore[division-by-zero, unused-ignore-comment] +2 - a = 10 / 0 # ty: ignore[division-by-zero, unused-ignore-comment] 2 + a = 10 / 0 # ty: ignore[division-by-zero] | ``` @@ -207,10 +203,8 @@ warning[unused-ignore-comment]: Unused `ty: ignore` directive | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove the unused suppression comment | -1 | # snapshot - - a = 10 / 2 # ty: ignore[division-by-zero, unresolved-reference] +2 - a = 10 / 2 # ty: ignore[division-by-zero, unresolved-reference] 2 + a = 10 / 2 -3 | # snapshot | ``` @@ -228,10 +222,8 @@ warning[unused-ignore-comment]: Unused `ty: ignore` directive: 'invalid-assignme | ^^^^^^^^^^^^^^^^^^ help: Remove the unused suppression code | -4 | # snapshot - - a = 10 / 0 # ty: ignore[invalid-assignment, division-by-zero, unresolved-reference] +5 - a = 10 / 0 # ty: ignore[invalid-assignment, division-by-zero, unresolved-reference] 5 + a = 10 / 0 # ty: ignore[division-by-zero, unresolved-reference] -6 | # snapshot | @@ -242,10 +234,8 @@ warning[unused-ignore-comment]: Unused `ty: ignore` directive: 'unresolved-refer | ^^^^^^^^^^^^^^^^^^^^ help: Remove the unused suppression code | -4 | # snapshot - - a = 10 / 0 # ty: ignore[invalid-assignment, division-by-zero, unresolved-reference] +5 - a = 10 / 0 # ty: ignore[invalid-assignment, division-by-zero, unresolved-reference] 5 + a = 10 / 0 # ty: ignore[invalid-assignment, division-by-zero] -6 | # snapshot | ``` @@ -262,8 +252,7 @@ warning[unused-ignore-comment]: Unused `ty: ignore` directive: 'invalid-assignme | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove the unused suppression codes | -6 | # snapshot - - a = 10 / 0 # ty: ignore[invalid-assignment, unresolved-reference, division-by-zero] +7 - a = 10 / 0 # ty: ignore[invalid-assignment, unresolved-reference, division-by-zero] 7 + a = 10 / 0 # ty: ignore[division-by-zero] | ``` @@ -306,12 +295,10 @@ warning[unused-ignore-comment]: Unused `ty: ignore` directive 9 | # fmt: off # ty: ignore[division-by-zero] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove the unused suppression comment - | -8 | # snapshot - - # fmt: off # ty: ignore[division-by-zero] -9 + # fmt: off -10 | value = 1 - | + | +9 - # fmt: off # ty: ignore[division-by-zero] +9 + # fmt: off + | ``` ```py @@ -331,10 +318,8 @@ warning[unused-ignore-comment]: Unused `ty: ignore` directive | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove the unused suppression comment | -14 | # snapshot - - # ty: ignore[division-by-zero] # fmt: off +15 - # ty: ignore[division-by-zero] # fmt: off 15 + # fmt: off -16 | value = 1 | note: This is an unsafe fix and may change runtime behavior ``` diff --git a/crates/ty_python_semantic/resources/mdtest/suppressions/type_ignore.md b/crates/ty_python_semantic/resources/mdtest/suppressions/type_ignore.md index 6ba5bdbc6f711..869913de8d64e 100644 --- a/crates/ty_python_semantic/resources/mdtest/suppressions/type_ignore.md +++ b/crates/ty_python_semantic/resources/mdtest/suppressions/type_ignore.md @@ -171,12 +171,10 @@ warning[unused-ignore-comment]: Unused `ty: ignore` directive 9 | + 2) # ty:ignore[division-by-zero] # fmt: skip | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove the unused suppression comment - | -8 | # snapshot - - + 2) # ty:ignore[division-by-zero] # fmt: skip -9 + + 2) # fmt: skip -10 | a = (3 - | + | +9 - + 2) # ty:ignore[division-by-zero] # fmt: skip +9 + + 2) # fmt: skip + | ``` ```py @@ -193,8 +191,7 @@ warning[unused-ignore-comment]: Unused `ty: ignore` directive | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove the unused suppression comment | -11 | # snapshot - - + 2) # fmt: skip # ty:ignore[division-by-zero] +12 - + 2) # fmt: skip # ty:ignore[division-by-zero] 12 + + 2) # fmt: skip | ``` @@ -319,8 +316,7 @@ warning[unused-type-ignore-comment]: Unused `type: ignore` directive: 'division- | ^^^^^^^^^^^^^^^^^^^ help: Remove the unused suppression code | -1 | # snapshot - - a = 10 / 2 # type: ignore[mypy-code, ty:division-by-zero] +2 - a = 10 / 2 # type: ignore[mypy-code, ty:division-by-zero] 2 + a = 10 / 2 # type: ignore[mypy-code] | ``` @@ -340,8 +336,7 @@ warning[unused-type-ignore-comment]: Unused `type: ignore` directive | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove the unused suppression comment | -1 | # snapshot - - a = 10 / 2 # type: ignore[ty:division-by-zero] +2 - a = 10 / 2 # type: ignore[ty:division-by-zero] 2 + a = 10 / 2 | ``` diff --git a/crates/ty_python_semantic/src/fixes.rs b/crates/ty_python_semantic/src/fixes.rs index bdb82dbac88c4..76822c14d613c 100644 --- a/crates/ty_python_semantic/src/fixes.rs +++ b/crates/ty_python_semantic/src/fixes.rs @@ -907,8 +907,7 @@ mod tests { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove the unused suppression comment | - 1 | import sys - - a = 5 + 10 # ty: ignore[unresolved-reference] + 2 - a = 5 + 10 # ty: ignore[unresolved-reference] 2 + a = 5 + 10 | "); @@ -1156,10 +1155,8 @@ class B(A): | help: Remove the unused suppression code | - 6 | class B(A): - - def test( # ty:ignore[unresolved-reference, invalid-method-override] + 7 - def test( # ty:ignore[unresolved-reference, invalid-method-override] 7 + def test( # ty:ignore[invalid-method-override] - 8 | self, | "#); } @@ -1206,7 +1203,7 @@ class B(A): | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Remove the unused suppression comment | - - value = missing # ty: ignore[] tracked by [123] # ty: ignore[unresolved-reference] + 1 - value = missing # ty: ignore[] tracked by [123] # ty: ignore[unresolved-reference] 1 + value = missing # ty: ignore[unresolved-reference] | " @@ -1252,9 +1249,7 @@ class B(A): | help: Remove the unused suppression comment | - 3 | values = [ - - # ty: ignore[] tracked by [123] - 4 | missing, + 4 - # ty: ignore[] tracked by [123] | " ); @@ -1293,10 +1288,8 @@ class B(A): | help: Remove the unused suppression comment | - 1 | seen_code = True - - # ty: ignore[ignore-comment-unknown-rule] # ty: ignore[not-a-rule] # ty: ignore[division-by-zero] + 2 - # ty: ignore[ignore-comment-unknown-rule] # ty: ignore[not-a-rule] # ty: ignore[division-by-zero] 2 + # ty: ignore[ignore-comment-unknown-rule] # ty: ignore[not-a-rule] - 3 | value = 1 / 0 | " ); @@ -1352,8 +1345,7 @@ class B(A): | ^^^^^^^^^^^^^^^^ help: Remove the unused suppression code | - 2 | - - result: int = f(missing) # ty: ignore[division-by-zero, invalid-assignment, too-many-positional-arguments, unresolved-reference] + 3 - result: int = f(missing) # ty: ignore[division-by-zero, invalid-assignment, too-many-positional-arguments, unresolved-reference] 3 + result: int = f(missing) # ty: ignore[invalid-assignment, too-many-positional-arguments, unresolved-reference] | "# @@ -1582,10 +1574,8 @@ class B(A): | help: Remove the unused suppression code | - 1 | seen_code = True - - # ty: ignore[too-many-positional-arguments, unresolved-reference] + 2 - # ty: ignore[too-many-positional-arguments, unresolved-reference] 2 + # ty: ignore[unresolved-reference] - 3 | values = [ | warning[unused-ignore-comment]: Unused `ty: ignore` directive: 'invalid-argument-type' @@ -1600,10 +1590,8 @@ class B(A): | help: Remove the unused suppression code | - 3 | values = [ - - # ty: ignore[invalid-argument-type, unresolved-reference] + 4 - # ty: ignore[invalid-argument-type, unresolved-reference] 4 + # ty: ignore[unresolved-reference] - 5 | missing, | " );