From 1718d928c5df15bef0a1bb92cbd7a22b10846051 Mon Sep 17 00:00:00 2001 From: Micha Reiser Date: Thu, 25 Jan 2024 10:00:47 +0100 Subject: [PATCH] Promote formatter preview styles to stable --- crates/ruff/tests/format.rs | 90 ++-- .../src/comments/format.rs | 6 +- crates/ruff_python_formatter/src/context.rs | 1 + .../src/expression/binary_like.rs | 5 +- .../src/other/arguments.rs | 5 - .../src/other/with_item.rs | 5 +- crates/ruff_python_formatter/src/preview.rs | 70 +-- .../src/statement/clause.rs | 4 +- .../src/statement/stmt_ann_assign.rs | 47 +- .../src/statement/stmt_assign.rs | 155 ++----- .../src/statement/stmt_aug_assign.rs | 4 +- .../src/statement/stmt_type_alias.rs | 19 +- .../src/statement/stmt_with.rs | 8 +- .../src/statement/suite.rs | 100 +---- .../ruff_python_formatter/src/string/mod.rs | 47 +- ...ack_compatibility@cases__comments5.py.snap | 273 ++++++++++++ ...lack_compatibility@cases__fmtonoff.py.snap | 28 +- ...ack_compatibility@cases__fmtonoff5.py.snap | 15 +- ...lack_compatibility@cases__function.py.snap | 16 +- ...@cases__long_strings_flag_disabled.py.snap | 19 +- ...ility@cases__pep_572_remove_parens.py.snap | 21 +- ...patibility@cases__power_op_newline.py.snap | 47 -- ...lack_compatibility@cases__python39.py.snap | 90 ++++ .../black_compatibility@cases__stub.pyi.snap | 47 +- ...black_compatibility@cases__torture.py.snap | 11 +- ...atibility@miscellaneous__force_pyi.py.snap | 102 ++--- ...tibility@miscellaneous__force_pyi.pyi.snap | 128 ------ .../black_compatibility@raw_docstring.py.snap | 12 +- .../format@docstring_code_examples.py.snap | 288 +----------- ...ion__optional_parentheses_comments.py.snap | 58 +-- .../format@expression__string.py.snap | 62 +-- ...rmat@fmt_on_off__trailing_comments.py.snap | 20 +- ...format@multiline_string_deviations.py.snap | 30 +- .../tests/snapshots/format@newlines.py.snap | 91 +--- .../format@notebook_docstring.py.snap | 21 +- .../tests/snapshots/format@preview.py.snap | 107 +---- .../snapshots/format@quote_style.py.snap | 45 +- .../format@statement__ann_assign.py.snap | 42 +- .../format@statement__assign.py.snap | 50 +-- ...format@statement__class_definition.py.snap | 79 +--- .../format@statement__function.py.snap | 214 +-------- ...t@statement__long_type_annotations.py.snap | 213 +++------ ...ormat@statement__return_annotation.py.snap | 411 ++---------------- .../format@statement__top_level.py.snap | 80 +--- .../snapshots/format@statement__with.py.snap | 24 +- .../format@stub_files__suite.pyi.snap | 25 +- 46 files changed, 854 insertions(+), 2381 deletions(-) create mode 100644 crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__comments5.py.snap delete mode 100644 crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__power_op_newline.py.snap create mode 100644 crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__python39.py.snap delete mode 100644 crates/ruff_python_formatter/tests/snapshots/black_compatibility@miscellaneous__force_pyi.pyi.snap diff --git a/crates/ruff/tests/format.rs b/crates/ruff/tests/format.rs index c04eb21db4c9d..2fdb4f84aae47 100644 --- a/crates/ruff/tests/format.rs +++ b/crates/ruff/tests/format.rs @@ -350,58 +350,52 @@ def f(x): ''' pass "#), @r###" -success: true -exit_code: 0 ------ stdout ----- -def f(x): - """ - Something about `f`. And an example: - - .. code-block:: python - - ( - foo, - bar, - quux, - ) = this_is_a_long_line( - lion, - hippo, - lemur, - bear, + success: true + exit_code: 0 + ----- stdout ----- + def f(x): + """ + Something about `f`. And an example: + + .. code-block:: python + + foo, bar, quux = ( + this_is_a_long_line( + lion, + hippo, + lemur, + bear, + ) + ) + + Another example: + + ```py + foo, bar, quux = ( + this_is_a_long_line( + lion, + hippo, + lemur, + bear, + ) ) + ``` - Another example: + And another: - ```py - ( - foo, - bar, - quux, - ) = this_is_a_long_line( - lion, - hippo, - lemur, - bear, - ) - ``` - - And another: + >>> foo, bar, quux = ( + ... this_is_a_long_line( + ... lion, + ... hippo, + ... lemur, + ... bear, + ... ) + ... ) + """ + pass - >>> ( - ... foo, - ... bar, - ... quux, - ... ) = this_is_a_long_line( - ... lion, - ... hippo, - ... lemur, - ... bear, - ... ) - """ - pass - ------ stderr ----- -"###); + ----- stderr ----- + "###); Ok(()) } diff --git a/crates/ruff_python_formatter/src/comments/format.rs b/crates/ruff_python_formatter/src/comments/format.rs index 13f1cdf2880f1..9fc66eab2b521 100644 --- a/crates/ruff_python_formatter/src/comments/format.rs +++ b/crates/ruff_python_formatter/src/comments/format.rs @@ -10,7 +10,6 @@ use ruff_text_size::{Ranged, TextLen, TextRange}; use crate::comments::{CommentLinePosition, SourceComment}; use crate::context::NodeLevel; use crate::prelude::*; -use crate::preview::is_blank_line_after_nested_stub_class_enabled; use crate::statement::suite::should_insert_blank_line_after_class_in_stub_file; /// Formats the leading comments of a node. @@ -544,10 +543,7 @@ pub(crate) fn empty_lines_before_trailing_comments<'a>( // Black has different rules for stub vs. non-stub and top level vs. indented let empty_lines = match (f.options().source_type(), f.context().node_level()) { (PySourceType::Stub, NodeLevel::TopLevel(_)) => 1, - (PySourceType::Stub, _) => u32::from( - is_blank_line_after_nested_stub_class_enabled(f.context()) - && node_kind == NodeKind::StmtClassDef, - ), + (PySourceType::Stub, _) => u32::from(node_kind == NodeKind::StmtClassDef), (_, NodeLevel::TopLevel(_)) => 2, (_, _) => 1, }; diff --git a/crates/ruff_python_formatter/src/context.rs b/crates/ruff_python_formatter/src/context.rs index b5dc85fcb3039..884c2f4a6cb43 100644 --- a/crates/ruff_python_formatter/src/context.rs +++ b/crates/ruff_python_formatter/src/context.rs @@ -87,6 +87,7 @@ impl<'a> PyFormatContext<'a> { } /// Returns `true` if preview mode is enabled. + #[allow(unused)] pub(crate) const fn is_preview(&self) -> bool { self.options.preview().is_enabled() } diff --git a/crates/ruff_python_formatter/src/expression/binary_like.rs b/crates/ruff_python_formatter/src/expression/binary_like.rs index 828b1e73b7c19..1c466701a9f7c 100644 --- a/crates/ruff_python_formatter/src/expression/binary_like.rs +++ b/crates/ruff_python_formatter/src/expression/binary_like.rs @@ -20,7 +20,6 @@ use crate::expression::parentheses::{ }; use crate::expression::OperatorPrecedence; use crate::prelude::*; -use crate::preview::is_fix_power_op_line_length_enabled; use crate::string::{AnyString, FormatStringContinuation}; #[derive(Copy, Clone, Debug)] @@ -722,9 +721,7 @@ impl Format> for FlatBinaryExpressionSlice<'_> { { hard_line_break().fmt(f)?; } else if is_pow { - if is_fix_power_op_line_length_enabled(f.context()) { - in_parentheses_only_if_group_breaks(&space()).fmt(f)?; - } + in_parentheses_only_if_group_breaks(&space()).fmt(f)?; } else { space().fmt(f)?; } diff --git a/crates/ruff_python_formatter/src/other/arguments.rs b/crates/ruff_python_formatter/src/other/arguments.rs index 7328c39eeccc2..a92c3f3e0fc48 100644 --- a/crates/ruff_python_formatter/src/other/arguments.rs +++ b/crates/ruff_python_formatter/src/other/arguments.rs @@ -9,7 +9,6 @@ use crate::expression::is_expression_huggable; use crate::expression::parentheses::{empty_parenthesized, parenthesized, Parentheses}; use crate::other::commas; use crate::prelude::*; -use crate::preview::is_multiline_string_handling_enabled; use crate::string::AnyString; #[derive(Default)] @@ -238,10 +237,6 @@ fn is_huggable_string_argument( arguments: &Arguments, context: &PyFormatContext, ) -> bool { - if !is_multiline_string_handling_enabled(context) { - return false; - } - if string.is_implicit_concatenated() || !string.is_multiline(context.source()) { return false; } diff --git a/crates/ruff_python_formatter/src/other/with_item.rs b/crates/ruff_python_formatter/src/other/with_item.rs index fc815a97d6211..3ea82b8a9df69 100644 --- a/crates/ruff_python_formatter/src/other/with_item.rs +++ b/crates/ruff_python_formatter/src/other/with_item.rs @@ -7,7 +7,6 @@ use crate::expression::parentheses::{ is_expression_parenthesized, parenthesized, Parentheses, Parenthesize, }; use crate::prelude::*; -use crate::preview::is_wrap_multiple_context_managers_in_parens_enabled; #[derive(Default)] pub struct FormatWithItem; @@ -30,9 +29,7 @@ impl FormatNodeRule for FormatWithItem { ); // Remove the parentheses of the `with_items` if the with statement adds parentheses - if f.context().node_level().is_parenthesized() - && is_wrap_multiple_context_managers_in_parens_enabled(f.context()) - { + if f.context().node_level().is_parenthesized() { if is_parenthesized { // ...except if the with item is parenthesized, then use this with item as a preferred breaking point // or when it has comments, then parenthesize it to prevent comments from moving. diff --git a/crates/ruff_python_formatter/src/preview.rs b/crates/ruff_python_formatter/src/preview.rs index 712a7da417088..3cc6ce46eef09 100644 --- a/crates/ruff_python_formatter/src/preview.rs +++ b/crates/ruff_python_formatter/src/preview.rs @@ -4,12 +4,8 @@ //! to stable. The challenge with directly using [`is_preview`](PyFormatContext::is_preview) is that it is unclear //! for which specific feature this preview check is for. Having named functions simplifies the promotion: //! Simply delete the function and let Rust tell you which checks you have to remove. -use crate::PyFormatContext; -/// Returns `true` if the [`fix_power_op_line_length`](https://github.com/astral-sh/ruff/issues/8938) preview style is enabled. -pub(crate) const fn is_fix_power_op_line_length_enabled(context: &PyFormatContext) -> bool { - context.is_preview() -} +use crate::PyFormatContext; /// Returns `true` if the [`hug_parens_with_braces_and_square_brackets`](https://github.com/astral-sh/ruff/issues/8279) preview style is enabled. pub(crate) const fn is_hug_parens_with_braces_and_square_brackets_enabled( @@ -17,67 +13,3 @@ pub(crate) const fn is_hug_parens_with_braces_and_square_brackets_enabled( ) -> bool { context.is_preview() } - -/// Returns `true` if the [`prefer_splitting_right_hand_side_of_assignments`](https://github.com/astral-sh/ruff/issues/6975) preview style is enabled. -pub(crate) const fn is_prefer_splitting_right_hand_side_of_assignments_enabled( - context: &PyFormatContext, -) -> bool { - context.is_preview() -} - -/// Returns `true` if the [`parenthesize_long_type_hints`](https://github.com/astral-sh/ruff/issues/8894) preview style is enabled. -pub(crate) const fn is_parenthesize_long_type_hints_enabled(context: &PyFormatContext) -> bool { - context.is_preview() -} - -/// Returns `true` if the [`no_blank_line_before_class_docstring`] preview style is enabled. -/// -/// [`no_blank_line_before_class_docstring`]: https://github.com/astral-sh/ruff/issues/8888 -pub(crate) const fn is_no_blank_line_before_class_docstring_enabled( - context: &PyFormatContext, -) -> bool { - context.is_preview() -} - -/// Returns `true` if the [`wrap_multiple_context_managers_in_parens`](https://github.com/astral-sh/ruff/issues/8889) preview style is enabled. -/// -/// Unlike Black, we re-use the same preview style feature flag for [`improved_async_statements_handling`](https://github.com/astral-sh/ruff/issues/8890) -pub(crate) const fn is_wrap_multiple_context_managers_in_parens_enabled( - context: &PyFormatContext, -) -> bool { - context.is_preview() -} - -/// Returns `true` if the [`blank_line_after_nested_stub_class`](https://github.com/astral-sh/ruff/issues/8891) preview style is enabled. -pub(crate) const fn is_blank_line_after_nested_stub_class_enabled( - context: &PyFormatContext, -) -> bool { - context.is_preview() -} - -/// Returns `true` if the [`module_docstring_newlines`](https://github.com/astral-sh/ruff/issues/7995) preview style is enabled. -pub(crate) const fn is_module_docstring_newlines_enabled(context: &PyFormatContext) -> bool { - context.is_preview() -} - -/// Returns `true` if the [`dummy_implementations`](https://github.com/astral-sh/ruff/issues/8357) preview style is enabled. -pub(crate) const fn is_dummy_implementations_enabled(context: &PyFormatContext) -> bool { - context.is_preview() -} - -/// Returns `true` if the [`hex_codes_in_unicode_sequences`](https://github.com/psf/black/pull/2916) preview style is enabled. -pub(crate) const fn is_hex_codes_in_unicode_sequences_enabled(context: &PyFormatContext) -> bool { - context.is_preview() -} - -/// Returns `true` if the [`multiline_string_handling`](https://github.com/astral-sh/ruff/issues/8896) preview style is enabled. -pub(crate) const fn is_multiline_string_handling_enabled(context: &PyFormatContext) -> bool { - context.is_preview() -} - -/// Returns `true` if the [`multiline_string_handling`](https://github.com/astral-sh/ruff/pull/9725) preview style is enabled. -/// Black does not [`format docstrings`](https://github.com/psf/black/issues/3493) so we keep this -/// preview for compatibility with Black. -pub(crate) const fn is_format_module_docstring_enabled(context: &PyFormatContext) -> bool { - context.is_preview() -} diff --git a/crates/ruff_python_formatter/src/statement/clause.rs b/crates/ruff_python_formatter/src/statement/clause.rs index 7592c94f1c0e2..5d63184fe3405 100644 --- a/crates/ruff_python_formatter/src/statement/clause.rs +++ b/crates/ruff_python_formatter/src/statement/clause.rs @@ -11,7 +11,6 @@ use crate::comments::{ leading_alternate_branch_comments, trailing_comments, SourceComment, SuppressionKind, }; use crate::prelude::*; -use crate::preview::is_dummy_implementations_enabled; use crate::statement::suite::{contains_only_an_ellipsis, SuiteKind}; use crate::verbatim::write_suppressed_clause_header; @@ -407,8 +406,7 @@ impl Format> for FormatClauseBody<'_> { // In stable, stubs are only collapsed in stub files, in preview stubs in functions // or classes are collapsed too let should_collapse_stub = f.options().source_type().is_stub() - || (is_dummy_implementations_enabled(f.context()) - && matches!(self.kind, SuiteKind::Function | SuiteKind::Class)); + || matches!(self.kind, SuiteKind::Function | SuiteKind::Class); if should_collapse_stub && contains_only_an_ellipsis(self.body, f.context().comments()) diff --git a/crates/ruff_python_formatter/src/statement/stmt_ann_assign.rs b/crates/ruff_python_formatter/src/statement/stmt_ann_assign.rs index 5d0a2d2f31eed..c123895110f45 100644 --- a/crates/ruff_python_formatter/src/statement/stmt_ann_assign.rs +++ b/crates/ruff_python_formatter/src/statement/stmt_ann_assign.rs @@ -2,13 +2,9 @@ use ruff_formatter::write; use ruff_python_ast::StmtAnnAssign; use crate::comments::{SourceComment, SuppressionKind}; +use crate::expression::is_splittable_expression; use crate::expression::parentheses::Parentheses; -use crate::expression::{has_parentheses, is_splittable_expression}; use crate::prelude::*; -use crate::preview::{ - is_parenthesize_long_type_hints_enabled, - is_prefer_splitting_right_hand_side_of_assignments_enabled, -}; use crate::statement::stmt_assign::{ AnyAssignmentOperator, AnyBeforeOperator, FormatStatementsLastExpression, }; @@ -30,13 +26,7 @@ impl FormatNodeRule for FormatStmtAnnAssign { write!(f, [target.format(), token(":"), space()])?; if let Some(value) = value { - if is_prefer_splitting_right_hand_side_of_assignments_enabled(f.context()) - // The `has_parentheses` check can be removed when stabilizing `is_parenthesize_long_type_hints`. - // because `is_splittable_expression` covers both. - && (has_parentheses(annotation, f.context()).is_some() - || (is_parenthesize_long_type_hints_enabled(f.context()) - && is_splittable_expression(annotation, f.context()))) - { + if is_splittable_expression(annotation, f.context()) { FormatStatementsLastExpression::RightToLeft { before_operator: AnyBeforeOperator::Expression(annotation), operator: AnyAssignmentOperator::Assign, @@ -47,23 +37,20 @@ impl FormatNodeRule for FormatStmtAnnAssign { } else { // Remove unnecessary parentheses around the annotation if the parenthesize long type hints preview style is enabled. // Ensure we keep the parentheses if the annotation has any comments. - if is_parenthesize_long_type_hints_enabled(f.context()) { - if f.context().comments().has_leading(annotation.as_ref()) - || f.context().comments().has_trailing(annotation.as_ref()) - { - annotation - .format() - .with_options(Parentheses::Always) - .fmt(f)?; - } else { - annotation - .format() - .with_options(Parentheses::Never) - .fmt(f)?; - } + if f.context().comments().has_leading(annotation.as_ref()) + || f.context().comments().has_trailing(annotation.as_ref()) + { + annotation + .format() + .with_options(Parentheses::Always) + .fmt(f)?; } else { - annotation.format().fmt(f)?; + annotation + .format() + .with_options(Parentheses::Never) + .fmt(f)?; } + write!( f, [ @@ -83,11 +70,7 @@ impl FormatNodeRule for FormatStmtAnnAssign { // Decimal # the user's age, used to determine if it's safe for them to use ruff // ) // ``` - if is_parenthesize_long_type_hints_enabled(f.context()) { - FormatStatementsLastExpression::left_to_right(annotation, item).fmt(f)?; - } else { - annotation.format().fmt(f)?; - } + FormatStatementsLastExpression::left_to_right(annotation, item).fmt(f)?; } if f.options().source_type().is_ipynb() diff --git a/crates/ruff_python_formatter/src/statement/stmt_assign.rs b/crates/ruff_python_formatter/src/statement/stmt_assign.rs index b709c1a08340f..22c42b4ffa489 100644 --- a/crates/ruff_python_formatter/src/statement/stmt_assign.rs +++ b/crates/ruff_python_formatter/src/statement/stmt_assign.rs @@ -17,10 +17,6 @@ use crate::expression::{ maybe_parenthesize_expression, }; use crate::prelude::*; -use crate::preview::{ - is_parenthesize_long_type_hints_enabled, - is_prefer_splitting_right_hand_side_of_assignments_enabled, -}; use crate::statement::trailing_semicolon; #[derive(Default)] @@ -44,53 +40,47 @@ impl FormatNodeRule for FormatStmtAssign { preserve_parentheses: true, }; - if is_prefer_splitting_right_hand_side_of_assignments_enabled(f.context()) { - // Avoid parenthesizing the value if the last target before the assigned value expands. - if let Some((last, head)) = rest.split_last() { - format_first.fmt(f)?; - - for target in head { - FormatTargetWithEqualOperator { - target, - preserve_parentheses: false, - } - .fmt(f)?; - } + // Avoid parenthesizing the value if the last target before the assigned value expands. + if let Some((last, head)) = rest.split_last() { + format_first.fmt(f)?; - FormatStatementsLastExpression::RightToLeft { - before_operator: AnyBeforeOperator::Expression(last), - operator: AnyAssignmentOperator::Assign, - value, - statement: item.into(), + for target in head { + FormatTargetWithEqualOperator { + target, + preserve_parentheses: false, } .fmt(f)?; } - // Avoid parenthesizing the value for single-target assignments where the - // target has its own parentheses (list, dict, tuple, ...) and the target expands. - else if has_target_own_parentheses(first, f.context()) - && !is_expression_parenthesized( - first.into(), - f.context().comments().ranges(), - f.context().source(), - ) - { - FormatStatementsLastExpression::RightToLeft { - before_operator: AnyBeforeOperator::Expression(first), - operator: AnyAssignmentOperator::Assign, - value, - statement: item.into(), - } - .fmt(f)?; + + FormatStatementsLastExpression::RightToLeft { + before_operator: AnyBeforeOperator::Expression(last), + operator: AnyAssignmentOperator::Assign, + value, + statement: item.into(), } - // For single targets that have no split points, parenthesize the value only - // if it makes it fit. Otherwise omit the parentheses. - else { - format_first.fmt(f)?; - FormatStatementsLastExpression::left_to_right(value, item).fmt(f)?; + .fmt(f)?; + } + // Avoid parenthesizing the value for single-target assignments where the + // target has its own parentheses (list, dict, tuple, ...) and the target expands. + else if has_target_own_parentheses(first, f.context()) + && !is_expression_parenthesized( + first.into(), + f.context().comments().ranges(), + f.context().source(), + ) + { + FormatStatementsLastExpression::RightToLeft { + before_operator: AnyBeforeOperator::Expression(first), + operator: AnyAssignmentOperator::Assign, + value, + statement: item.into(), } - } else { - write!(f, [format_first, FormatTargets { targets: rest }])?; - + .fmt(f)?; + } + // For single targets that have no split points, parenthesize the value only + // if it makes it fit. Otherwise omit the parentheses. + else { + format_first.fmt(f)?; FormatStatementsLastExpression::left_to_right(value, item).fmt(f)?; } @@ -114,77 +104,6 @@ impl FormatNodeRule for FormatStmtAssign { } } -/// Formats the targets so that they split left-to right. -#[derive(Debug)] -struct FormatTargets<'a> { - targets: &'a [Expr], -} - -impl Format> for FormatTargets<'_> { - fn fmt(&self, f: &mut PyFormatter) -> FormatResult<()> { - if let Some((first, rest)) = self.targets.split_first() { - let comments = f.context().comments(); - - let parenthesize = if comments.has_leading(first) || comments.has_trailing(first) { - ParenthesizeTarget::Always - } else if has_target_own_parentheses(first, f.context()) { - ParenthesizeTarget::Never - } else { - ParenthesizeTarget::IfBreaks - }; - - let group_id = if parenthesize == ParenthesizeTarget::Never { - Some(f.group_id("assignment_parentheses")) - } else { - None - }; - - let format_first = format_with(|f: &mut PyFormatter| { - let mut f = WithNodeLevel::new(NodeLevel::Expression(group_id), f); - match parenthesize { - ParenthesizeTarget::Always => { - write!(f, [first.format().with_options(Parentheses::Always)]) - } - ParenthesizeTarget::Never => { - write!(f, [first.format().with_options(Parentheses::Never)]) - } - ParenthesizeTarget::IfBreaks => { - write!( - f, - [ - if_group_breaks(&token("(")), - soft_block_indent(&first.format().with_options(Parentheses::Never)), - if_group_breaks(&token(")")) - ] - ) - } - } - }); - - write!( - f, - [group(&format_args![ - format_first, - space(), - token("="), - space(), - FormatTargets { targets: rest } - ]) - .with_group_id(group_id)] - ) - } else { - Ok(()) - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum ParenthesizeTarget { - Always, - Never, - IfBreaks, -} - /// Formats a single target with the equal operator. struct FormatTargetWithEqualOperator<'a> { target: &'a Expr, @@ -693,9 +612,7 @@ impl Format> for AnyBeforeOperator<'_> { } // Never parenthesize targets that come with their own parentheses, e.g. don't parenthesize lists or dictionary literals. else if should_parenthesize_target(expression, f.context()) { - if is_parenthesize_long_type_hints_enabled(f.context()) - && can_omit_optional_parentheses(expression, f.context()) - { + if can_omit_optional_parentheses(expression, f.context()) { optional_parentheses(&expression.format().with_options(Parentheses::Never)) .fmt(f) } else { diff --git a/crates/ruff_python_formatter/src/statement/stmt_aug_assign.rs b/crates/ruff_python_formatter/src/statement/stmt_aug_assign.rs index 003c10a32a8e1..70038ff3a9776 100644 --- a/crates/ruff_python_formatter/src/statement/stmt_aug_assign.rs +++ b/crates/ruff_python_formatter/src/statement/stmt_aug_assign.rs @@ -4,7 +4,6 @@ use ruff_python_ast::StmtAugAssign; use crate::comments::{SourceComment, SuppressionKind}; use crate::expression::parentheses::is_expression_parenthesized; use crate::prelude::*; -use crate::preview::is_prefer_splitting_right_hand_side_of_assignments_enabled; use crate::statement::stmt_assign::{ has_target_own_parentheses, AnyAssignmentOperator, AnyBeforeOperator, FormatStatementsLastExpression, @@ -24,8 +23,7 @@ impl FormatNodeRule for FormatStmtAugAssign { range: _, } = item; - if is_prefer_splitting_right_hand_side_of_assignments_enabled(f.context()) - && has_target_own_parentheses(target, f.context()) + if has_target_own_parentheses(target, f.context()) && !is_expression_parenthesized( target.into(), f.context().comments().ranges(), diff --git a/crates/ruff_python_formatter/src/statement/stmt_type_alias.rs b/crates/ruff_python_formatter/src/statement/stmt_type_alias.rs index b6ae69b4430af..ef2cd8cef37d6 100644 --- a/crates/ruff_python_formatter/src/statement/stmt_type_alias.rs +++ b/crates/ruff_python_formatter/src/statement/stmt_type_alias.rs @@ -3,7 +3,6 @@ use ruff_python_ast::StmtTypeAlias; use crate::comments::{SourceComment, SuppressionKind}; use crate::prelude::*; -use crate::preview::is_prefer_splitting_right_hand_side_of_assignments_enabled; use crate::statement::stmt_assign::{ AnyAssignmentOperator, AnyBeforeOperator, FormatStatementsLastExpression, }; @@ -23,17 +22,13 @@ impl FormatNodeRule for FormatStmtTypeAlias { write!(f, [token("type"), space(), name.as_ref().format()])?; if let Some(type_params) = type_params { - if is_prefer_splitting_right_hand_side_of_assignments_enabled(f.context()) { - return FormatStatementsLastExpression::RightToLeft { - before_operator: AnyBeforeOperator::TypeParams(type_params), - operator: AnyAssignmentOperator::Assign, - value, - statement: item.into(), - } - .fmt(f); - }; - - write!(f, [type_params.format()])?; + return FormatStatementsLastExpression::RightToLeft { + before_operator: AnyBeforeOperator::TypeParams(type_params), + operator: AnyAssignmentOperator::Assign, + value, + statement: item.into(), + } + .fmt(f); } write!( diff --git a/crates/ruff_python_formatter/src/statement/stmt_with.rs b/crates/ruff_python_formatter/src/statement/stmt_with.rs index 3e8970f4aa154..ce0af821f101d 100644 --- a/crates/ruff_python_formatter/src/statement/stmt_with.rs +++ b/crates/ruff_python_formatter/src/statement/stmt_with.rs @@ -12,7 +12,6 @@ use crate::expression::parentheses::{ }; use crate::other::commas; use crate::prelude::*; -use crate::preview::is_wrap_multiple_context_managers_in_parens_enabled; use crate::statement::clause::{clause_body, clause_header, ClauseHeader}; use crate::{PyFormatOptions, PythonVersion}; @@ -152,8 +151,7 @@ fn should_parenthesize( return Ok(ParenthesizeWith::IfExpands); } - let can_parenthesize = (is_wrap_multiple_context_managers_in_parens_enabled(context) - && options.target_version() >= PythonVersion::Py39) + let can_parenthesize = options.target_version() >= PythonVersion::Py39 || are_with_items_parenthesized(with, context)?; if !can_parenthesize { @@ -176,9 +174,7 @@ fn should_parenthesize( // Preserve the parentheses around the context expression instead of parenthesizing the entire // with items. ParenthesizeWith::UnlessCommented - } else if is_wrap_multiple_context_managers_in_parens_enabled(context) - && can_omit_optional_parentheses(&single.context_expr, context) - { + } else if can_omit_optional_parentheses(&single.context_expr, context) { ParenthesizeWith::Optional } else { ParenthesizeWith::IfExpands diff --git a/crates/ruff_python_formatter/src/statement/suite.rs b/crates/ruff_python_formatter/src/statement/suite.rs index df1cb3be516f3..844fcc0bec5e6 100644 --- a/crates/ruff_python_formatter/src/statement/suite.rs +++ b/crates/ruff_python_formatter/src/statement/suite.rs @@ -13,11 +13,6 @@ use crate::comments::{ use crate::context::{NodeLevel, TopLevelStatementPosition, WithIndentLevel, WithNodeLevel}; use crate::expression::expr_string_literal::ExprStringLiteralKind; use crate::prelude::*; -use crate::preview::{ - is_blank_line_after_nested_stub_class_enabled, is_dummy_implementations_enabled, - is_format_module_docstring_enabled, is_module_docstring_newlines_enabled, - is_no_blank_line_before_class_docstring_enabled, -}; use crate::statement::stmt_expr::FormatStmtExpr; use crate::verbatim::{ suppressed_node, write_suppressed_statements_starting_with_leading_comment, @@ -102,7 +97,7 @@ impl FormatRule> for FormatSuite { SuiteChildStatement::Other(first) } - SuiteKind::Function => { + SuiteKind::Function | SuiteKind::Class | SuiteKind::TopLevel => { if let Some(docstring) = DocstringStmt::try_from_statement(first, self.kind, source_type) { @@ -111,53 +106,6 @@ impl FormatRule> for FormatSuite { SuiteChildStatement::Other(first) } } - - SuiteKind::Class => { - if let Some(docstring) = - DocstringStmt::try_from_statement(first, self.kind, source_type) - { - if !comments.has_leading(first) - && lines_before(first.start(), source) > 1 - && !source_type.is_stub() - && !is_no_blank_line_before_class_docstring_enabled(f.context()) - { - // Allow up to one empty line before a class docstring, e.g., this is - // stable formatting: - // - // ```python - // class Test: - // - // """Docstring""" - // ``` - // - // But, in preview mode, we don't want to allow any empty lines before a - // class docstring, e.g., this is preview formatting: - // - // ```python - // class Test: - // """Docstring""" - // ``` - empty_line().fmt(f)?; - } - - SuiteChildStatement::Docstring(docstring) - } else { - SuiteChildStatement::Other(first) - } - } - SuiteKind::TopLevel => { - if is_format_module_docstring_enabled(f.context()) { - if let Some(docstring) = - DocstringStmt::try_from_statement(first, self.kind, source_type) - { - SuiteChildStatement::Docstring(docstring) - } else { - SuiteChildStatement::Other(first) - } - } else { - SuiteChildStatement::Other(first) - } - } }; let first_comments = comments.leading_dangling_trailing(first); @@ -188,16 +136,12 @@ impl FormatRule> for FormatSuite { && self.kind == SuiteKind::Class { true - } else if is_module_docstring_newlines_enabled(f.context()) - && self.kind == SuiteKind::TopLevel - && DocstringStmt::try_from_statement(first.statement(), self.kind, source_type) - .is_some() - { - // Only in preview mode, insert a newline after a module level docstring, but treat - // it as a docstring otherwise. See: https://github.com/psf/black/pull/3932. - true } else { - false + // Insert a newline after a module level docstring, but treat + // it as a docstring otherwise. See: https://github.com/psf/black/pull/3932. + self.kind == SuiteKind::TopLevel + && DocstringStmt::try_from_statement(first.statement(), self.kind, source_type) + .is_some() }; (first.statement(), empty_line_after_docstring) @@ -284,20 +228,19 @@ impl FormatRule> for FormatSuite { } else { // Preserve empty lines after a stub implementation but don't insert a new one if there isn't any present in the source. // This is useful when having multiple function overloads that should be grouped to getter by omitting new lines between them. - let is_preceding_stub_function_without_empty_line = - is_dummy_implementations_enabled(f.context()) - && following.is_function_def_stmt() - && preceding - .as_function_def_stmt() - .is_some_and(|preceding_stub| { - contains_only_an_ellipsis( - &preceding_stub.body, - f.context().comments(), - ) && lines_after_ignoring_end_of_line_trivia( - preceding_stub.end(), - f.context().source(), - ) < 2 - }); + let is_preceding_stub_function_without_empty_line = following + .is_function_def_stmt() + && preceding + .as_function_def_stmt() + .is_some_and(|preceding_stub| { + contains_only_an_ellipsis( + &preceding_stub.body, + f.context().comments(), + ) && lines_after_ignoring_end_of_line_trivia( + preceding_stub.end(), + f.context().source(), + ) < 2 + }); if !is_preceding_stub_function_without_empty_line { match self.kind { @@ -529,11 +472,10 @@ pub(crate) fn should_insert_blank_line_after_class_in_stub_file( following: Option>, context: &PyFormatContext, ) -> bool { - if !(is_blank_line_after_nested_stub_class_enabled(context) - && context.options().source_type().is_stub()) - { + if !context.options().source_type().is_stub() { return false; } + let comments = context.comments(); match preceding.as_stmt_class_def() { Some(class) if contains_only_an_ellipsis(&class.body, comments) => { diff --git a/crates/ruff_python_formatter/src/string/mod.rs b/crates/ruff_python_formatter/src/string/mod.rs index 047ae7cd36306..2f8b81a05f16e 100644 --- a/crates/ruff_python_formatter/src/string/mod.rs +++ b/crates/ruff_python_formatter/src/string/mod.rs @@ -18,7 +18,6 @@ use crate::expression::parentheses::in_parentheses_only_soft_line_break_or_space use crate::other::f_string::FormatFString; use crate::other::string_literal::{FormatStringLiteral, StringLiteralKind}; use crate::prelude::*; -use crate::preview::is_hex_codes_in_unicode_sequences_enabled; use crate::QuoteStyle; pub(crate) mod docstring; @@ -312,7 +311,6 @@ pub(crate) struct StringNormalizer { quoting: Quoting, preferred_quote_style: QuoteStyle, parent_docstring_quote_char: Option, - normalize_hex: bool, } impl StringNormalizer { @@ -321,7 +319,6 @@ impl StringNormalizer { quoting: Quoting::default(), preferred_quote_style: QuoteStyle::default(), parent_docstring_quote_char: context.docstring(), - normalize_hex: is_hex_codes_in_unicode_sequences_enabled(context), } } @@ -423,7 +420,7 @@ impl StringNormalizer { let quotes = self.choose_quotes(string, locator); - let normalized = normalize_string(raw_content, quotes, string.prefix(), self.normalize_hex); + let normalized = normalize_string(raw_content, quotes, string.prefix()); NormalizedString { prefix: string.prefix(), @@ -830,7 +827,6 @@ pub(crate) fn normalize_string( input: &str, quotes: StringQuotes, prefix: StringPrefix, - normalize_hex: bool, ) -> Cow { // The normalized string if `input` is not yet normalized. // `output` must remain empty if `input` is already normalized. @@ -881,27 +877,25 @@ pub(crate) fn normalize_string( if next == '\\' { // Skip over escaped backslashes chars.next(); - } else if normalize_hex { - if let Some(normalised) = UnicodeEscape::new(next, !prefix.is_byte()) - .and_then(|escape| { - escape.normalize(&input[index + c.len_utf8() + next.len_utf8()..]) - }) - { - // Length of the `\` plus the length of the escape sequence character (`u` | `U` | `x`) - let escape_start_len = '\\'.len_utf8() + next.len_utf8(); - let escape_start_offset = index + escape_start_len; - if let Cow::Owned(normalised) = &normalised { - output.push_str(&input[last_index..escape_start_offset]); - output.push_str(normalised); - last_index = escape_start_offset + normalised.len(); - }; - - // Move the `chars` iterator passed the escape sequence. - // Simply reassigning `chars` doesn't work because the indices` would - // then be off. - for _ in 0..next.len_utf8() + normalised.len() { - chars.next(); - } + } else if let Some(normalised) = UnicodeEscape::new(next, !prefix.is_byte()) + .and_then(|escape| { + escape.normalize(&input[index + c.len_utf8() + next.len_utf8()..]) + }) + { + // Length of the `\` plus the length of the escape sequence character (`u` | `U` | `x`) + let escape_start_len = '\\'.len_utf8() + next.len_utf8(); + let escape_start_offset = index + escape_start_len; + if let Cow::Owned(normalised) = &normalised { + output.push_str(&input[last_index..escape_start_offset]); + output.push_str(normalised); + last_index = escape_start_offset + normalised.len(); + }; + + // Move the `chars` iterator passed the escape sequence. + // Simply reassigning `chars` doesn't work because the indices` would + // then be off. + for _ in 0..next.len_utf8() + normalised.len() { + chars.next(); } } @@ -1081,7 +1075,6 @@ mod tests { quote_char: QuoteChar::Double, }, StringPrefix::BYTE, - true, ); assert_eq!(r"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a", &normalized); diff --git a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__comments5.py.snap b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__comments5.py.snap new file mode 100644 index 0000000000000..a6e70835e0d97 --- /dev/null +++ b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__comments5.py.snap @@ -0,0 +1,273 @@ +--- +source: crates/ruff_python_formatter/tests/fixtures.rs +input_file: crates/ruff_python_formatter/resources/test/fixtures/black/cases/comments5.py +--- +## Input + +```python +while True: + if something.changed: + do.stuff() # trailing comment + # Comment belongs to the `if` block. + # This one belongs to the `while` block. + + # Should this one, too? I guess so. + +# This one is properly standalone now. + +for i in range(100): + # first we do this + if i % 33 == 0: + break + + # then we do this + print(i) + # and finally we loop around + +with open(some_temp_file) as f: + data = f.read() + +try: + with open(some_other_file) as w: + w.write(data) + +except OSError: + print("problems") + +import sys + + +# leading function comment +def wat(): + ... + # trailing function comment + + +# SECTION COMMENT + + +# leading 1 +@deco1 +# leading 2 +@deco2(with_args=True) +# leading 3 +@deco3 +def decorated1(): + ... + + +# leading 1 +@deco1 +# leading 2 +@deco2(with_args=True) +# leading function comment +def decorated1(): + ... + + +# Note: this is fixed in +# Preview.empty_lines_before_class_or_def_with_leading_comments. +# In the current style, the user will have to split those lines by hand. +some_instruction + + +# This comment should be split from `some_instruction` by two lines but isn't. +def g(): + ... + + +if __name__ == "__main__": + main() +``` + +## Black Differences + +```diff +--- Black ++++ Ruff +@@ -45,8 +45,7 @@ + @deco2(with_args=True) + # leading 3 + @deco3 +-def decorated1(): +- ... ++def decorated1(): ... + + + # leading 1 +@@ -54,8 +53,7 @@ + # leading 2 + @deco2(with_args=True) + # leading function comment +-def decorated1(): +- ... ++def decorated1(): ... + + + # Note: this is fixed in +@@ -65,8 +63,7 @@ + + + # This comment should be split from `some_instruction` by two lines but isn't. +-def g(): +- ... ++def g(): ... + + + if __name__ == "__main__": +``` + +## Ruff Output + +```python +while True: + if something.changed: + do.stuff() # trailing comment + # Comment belongs to the `if` block. + # This one belongs to the `while` block. + + # Should this one, too? I guess so. + +# This one is properly standalone now. + +for i in range(100): + # first we do this + if i % 33 == 0: + break + + # then we do this + print(i) + # and finally we loop around + +with open(some_temp_file) as f: + data = f.read() + +try: + with open(some_other_file) as w: + w.write(data) + +except OSError: + print("problems") + +import sys + + +# leading function comment +def wat(): + ... + # trailing function comment + + +# SECTION COMMENT + + +# leading 1 +@deco1 +# leading 2 +@deco2(with_args=True) +# leading 3 +@deco3 +def decorated1(): ... + + +# leading 1 +@deco1 +# leading 2 +@deco2(with_args=True) +# leading function comment +def decorated1(): ... + + +# Note: this is fixed in +# Preview.empty_lines_before_class_or_def_with_leading_comments. +# In the current style, the user will have to split those lines by hand. +some_instruction + + +# This comment should be split from `some_instruction` by two lines but isn't. +def g(): ... + + +if __name__ == "__main__": + main() +``` + +## Black Output + +```python +while True: + if something.changed: + do.stuff() # trailing comment + # Comment belongs to the `if` block. + # This one belongs to the `while` block. + + # Should this one, too? I guess so. + +# This one is properly standalone now. + +for i in range(100): + # first we do this + if i % 33 == 0: + break + + # then we do this + print(i) + # and finally we loop around + +with open(some_temp_file) as f: + data = f.read() + +try: + with open(some_other_file) as w: + w.write(data) + +except OSError: + print("problems") + +import sys + + +# leading function comment +def wat(): + ... + # trailing function comment + + +# SECTION COMMENT + + +# leading 1 +@deco1 +# leading 2 +@deco2(with_args=True) +# leading 3 +@deco3 +def decorated1(): + ... + + +# leading 1 +@deco1 +# leading 2 +@deco2(with_args=True) +# leading function comment +def decorated1(): + ... + + +# Note: this is fixed in +# Preview.empty_lines_before_class_or_def_with_leading_comments. +# In the current style, the user will have to split those lines by hand. +some_instruction + + +# This comment should be split from `some_instruction` by two lines but isn't. +def g(): + ... + + +if __name__ == "__main__": + main() +``` + + diff --git a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__fmtonoff.py.snap b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__fmtonoff.py.snap index 44fe937154f9d..4b55126b9e887 100644 --- a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__fmtonoff.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__fmtonoff.py.snap @@ -206,7 +206,19 @@ d={'a':1, # fmt: off from third_party import (X, Y, Z) -@@ -63,15 +64,15 @@ +@@ -53,25 +54,21 @@ + g: int = 1 if False else 2, + h: str = "", + i: str = r"", +-): +- ... +- +- +-def spaces2(result=_core.Value(None)): +- ... ++): ... ++def spaces2(result=_core.Value(None)): ... + something = { # fmt: off @@ -225,7 +237,7 @@ d={'a':1, # fmt: on goes + here, andhere, -@@ -122,8 +123,10 @@ +@@ -122,8 +119,10 @@ """ # fmt: off @@ -237,7 +249,7 @@ d={'a':1, # fmt: on pass -@@ -138,7 +141,7 @@ +@@ -138,7 +137,7 @@ now . considers . multiple . fmt . directives . within . one . prefix # fmt: on # fmt: off @@ -246,7 +258,7 @@ d={'a':1, # fmt: on -@@ -178,14 +181,18 @@ +@@ -178,14 +177,18 @@ $ """, # fmt: off @@ -328,12 +340,8 @@ def spaces_types( g: int = 1 if False else 2, h: str = "", i: str = r"", -): - ... - - -def spaces2(result=_core.Value(None)): - ... +): ... +def spaces2(result=_core.Value(None)): ... something = { diff --git a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__fmtonoff5.py.snap b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__fmtonoff5.py.snap index 1346480b808e6..9e58c8142ef79 100644 --- a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__fmtonoff5.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__fmtonoff5.py.snap @@ -110,7 +110,17 @@ elif unformatted: }, ) -@@ -82,6 +81,6 @@ +@@ -72,8 +71,7 @@ + + + class Factory(t.Protocol): +- def this_will_be_formatted(self, **kwargs) -> Named: +- ... ++ def this_will_be_formatted(self, **kwargs) -> Named: ... + + # fmt: on + +@@ -82,6 +80,6 @@ if x: return x # fmt: off @@ -196,8 +206,7 @@ class Named(t.Protocol): class Factory(t.Protocol): - def this_will_be_formatted(self, **kwargs) -> Named: - ... + def this_will_be_formatted(self, **kwargs) -> Named: ... # fmt: on diff --git a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__function.py.snap b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__function.py.snap index df6fda9a85cac..37a465d6dbf38 100644 --- a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__function.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__function.py.snap @@ -107,8 +107,15 @@ def __await__(): return (yield) ```diff --- Black +++ Ruff -@@ -65,6 +65,7 @@ - +@@ -59,12 +59,10 @@ + g: int = 1 if False else 2, + h: str = "", + i: str = r"", +-): +- ... +- +- ++): ... def spaces2(result=_core.Value(None)): assert fut is self._read_fut, (fut, self._read_fut) + # EMPTY LINE WITH WHITESPACE (this comment will be removed) @@ -181,10 +188,7 @@ def spaces_types( g: int = 1 if False else 2, h: str = "", i: str = r"", -): - ... - - +): ... def spaces2(result=_core.Value(None)): assert fut is self._read_fut, (fut, self._read_fut) # EMPTY LINE WITH WHITESPACE (this comment will be removed) diff --git a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__long_strings_flag_disabled.py.snap b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__long_strings_flag_disabled.py.snap index 47c71cf9a2863..f397065d46b89 100644 --- a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__long_strings_flag_disabled.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__long_strings_flag_disabled.py.snap @@ -320,6 +320,19 @@ long_unmergable_string_with_pragma = ( "formatting" ) +@@ -255,9 +251,9 @@ + + "using the '+' operator." + ) + annotated_variable: Final = "This is a large string that has a type annotation attached to it. A type annotation should NOT stop a long string from being wrapped." +-annotated_variable: Literal[ +- "fakse_literal" +-] = "This is a large string that has a type annotation attached to it. A type annotation should NOT stop a long string from being wrapped." ++annotated_variable: Literal["fakse_literal"] = ( ++ "This is a large string that has a type annotation attached to it. A type annotation should NOT stop a long string from being wrapped." ++) + + backslashes = "This is a really long string with \"embedded\" double quotes and 'single' quotes that also handles checking for an even number of backslashes \\" + backslashes = "This is a really long string with \"embedded\" double quotes and 'single' quotes that also handles checking for an even number of backslashes \\\\" ``` ## Ruff Output @@ -578,9 +591,9 @@ annotated_variable: Final = ( + "using the '+' operator." ) annotated_variable: Final = "This is a large string that has a type annotation attached to it. A type annotation should NOT stop a long string from being wrapped." -annotated_variable: Literal[ - "fakse_literal" -] = "This is a large string that has a type annotation attached to it. A type annotation should NOT stop a long string from being wrapped." +annotated_variable: Literal["fakse_literal"] = ( + "This is a large string that has a type annotation attached to it. A type annotation should NOT stop a long string from being wrapped." +) backslashes = "This is a really long string with \"embedded\" double quotes and 'single' quotes that also handles checking for an even number of backslashes \\" backslashes = "This is a really long string with \"embedded\" double quotes and 'single' quotes that also handles checking for an even number of backslashes \\\\" diff --git a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__pep_572_remove_parens.py.snap b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__pep_572_remove_parens.py.snap index ac78124cef0f4..8ba666a838056 100644 --- a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__pep_572_remove_parens.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__pep_572_remove_parens.py.snap @@ -81,7 +81,20 @@ async def await_the_walrus(): ```diff --- Black +++ Ruff -@@ -34,7 +34,7 @@ +@@ -23,18 +23,16 @@ + foo(x=(y := f(x))) + + +-def foo(answer=(p := 42)): +- ... ++def foo(answer=(p := 42)): ... + + +-def foo2(answer: (p := 42) = 5): +- ... ++def foo2(answer: (p := 42) = 5): ... + + lambda: (x := 1) a[(x := 12)] @@ -120,12 +133,10 @@ assert (foo := 42 - 12) foo(x=(y := f(x))) -def foo(answer=(p := 42)): - ... +def foo(answer=(p := 42)): ... -def foo2(answer: (p := 42) = 5): - ... +def foo2(answer: (p := 42) = 5): ... lambda: (x := 1) diff --git a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__power_op_newline.py.snap b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__power_op_newline.py.snap deleted file mode 100644 index bb1b6eed95ecb..0000000000000 --- a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__power_op_newline.py.snap +++ /dev/null @@ -1,47 +0,0 @@ ---- -source: crates/ruff_python_formatter/tests/fixtures.rs -input_file: crates/ruff_python_formatter/resources/test/fixtures/black/cases/power_op_newline.py ---- -## Input - -```python -importA;()<<0**0# -``` - -## Black Differences - -```diff ---- Black -+++ Ruff -@@ -2,5 +2,5 @@ - ( - () - << 0 -- ** 0 -+ **0 - ) # -``` - -## Ruff Output - -```python -importA -( - () - << 0 - **0 -) # -``` - -## Black Output - -```python -importA -( - () - << 0 - ** 0 -) # -``` - - diff --git a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__python39.py.snap b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__python39.py.snap new file mode 100644 index 0000000000000..246553339b6d5 --- /dev/null +++ b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__python39.py.snap @@ -0,0 +1,90 @@ +--- +source: crates/ruff_python_formatter/tests/fixtures.rs +input_file: crates/ruff_python_formatter/resources/test/fixtures/black/cases/python39.py +--- +## Input + +```python +@relaxed_decorator[0] +def f(): + ... + +@relaxed_decorator[extremely_long_name_that_definitely_will_not_fit_on_one_line_of_standard_length] +def f(): + ... + +@extremely_long_variable_name_that_doesnt_fit := complex.expression(with_long="arguments_value_that_wont_fit_at_the_end_of_the_line") +def f(): + ... +``` + +## Black Differences + +```diff +--- Black ++++ Ruff +@@ -1,17 +1,14 @@ + @relaxed_decorator[0] +-def f(): +- ... ++def f(): ... + + + @relaxed_decorator[ + extremely_long_name_that_definitely_will_not_fit_on_one_line_of_standard_length + ] +-def f(): +- ... ++def f(): ... + + + @extremely_long_variable_name_that_doesnt_fit := complex.expression( + with_long="arguments_value_that_wont_fit_at_the_end_of_the_line" + ) +-def f(): +- ... ++def f(): ... +``` + +## Ruff Output + +```python +@relaxed_decorator[0] +def f(): ... + + +@relaxed_decorator[ + extremely_long_name_that_definitely_will_not_fit_on_one_line_of_standard_length +] +def f(): ... + + +@extremely_long_variable_name_that_doesnt_fit := complex.expression( + with_long="arguments_value_that_wont_fit_at_the_end_of_the_line" +) +def f(): ... +``` + +## Black Output + +```python +@relaxed_decorator[0] +def f(): + ... + + +@relaxed_decorator[ + extremely_long_name_that_definitely_will_not_fit_on_one_line_of_standard_length +] +def f(): + ... + + +@extremely_long_variable_name_that_doesnt_fit := complex.expression( + with_long="arguments_value_that_wont_fit_at_the_end_of_the_line" +) +def f(): + ... +``` + + diff --git a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__stub.pyi.snap b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__stub.pyi.snap index 14b894cda7a0d..a2ebb5280a749 100644 --- a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__stub.pyi.snap +++ b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__stub.pyi.snap @@ -87,39 +87,7 @@ class Conditional: ```diff --- Black +++ Ruff -@@ -24,31 +24,24 @@ - if sys.version_info >= (3, 8): - class E: - def f(self): ... -- - class F: - def f(self): ... -- - class G: ... - class H: ... -- - else: - class I: ... - class J: ... -- - def f(): ... - - class K: - def f(self): ... -- - def f(): ... - - class Nested: - class dirty: ... - class little: ... -- - class secret: - def who_has_to_know(self): ... -- - def verse(self): ... - - class Conditional: -@@ -57,17 +50,14 @@ +@@ -57,12 +57,10 @@ def g(self): ... else: def g(self): ... @@ -132,11 +100,6 @@ class Conditional: def k(self): ... if sys.version_info >= (3, 8): class A: ... - class B: ... -- - class C: - def l(self): ... - def m(self): ... ``` ## Ruff Output @@ -168,24 +131,31 @@ def h(): ... if sys.version_info >= (3, 8): class E: def f(self): ... + class F: def f(self): ... + class G: ... class H: ... + else: class I: ... class J: ... + def f(): ... class K: def f(self): ... + def f(): ... class Nested: class dirty: ... class little: ... + class secret: def who_has_to_know(self): ... + def verse(self): ... class Conditional: @@ -202,6 +172,7 @@ class Conditional: if sys.version_info >= (3, 8): class A: ... class B: ... + class C: def l(self): ... def m(self): ... diff --git a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__torture.py.snap b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__torture.py.snap index f8e78b1ac0e15..3ad322d6b770a 100644 --- a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__torture.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@cases__torture.py.snap @@ -41,15 +41,6 @@ assert ( ```diff --- Black +++ Ruff -@@ -2,7 +2,7 @@ - ( - () - << 0 -- ** 101234234242352525425252352352525234890264906820496920680926538059059209922523523525 -+ **101234234242352525425252352352525234890264906820496920680926538059059209922523523525 - ) # - - assert sort_by_dependency( @@ -25,9 +25,9 @@ class A: def foo(self): @@ -71,7 +62,7 @@ importA ( () << 0 - **101234234242352525425252352352525234890264906820496920680926538059059209922523523525 + ** 101234234242352525425252352352525234890264906820496920680926538059059209922523523525 ) # assert sort_by_dependency( diff --git a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@miscellaneous__force_pyi.py.snap b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@miscellaneous__force_pyi.py.snap index c2d79524f4838..6a1fd9706d5d5 100644 --- a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@miscellaneous__force_pyi.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@miscellaneous__force_pyi.py.snap @@ -42,77 +42,52 @@ def eggs() -> Union[str, int]: ... ```diff --- Black +++ Ruff -@@ -1,32 +1,58 @@ +@@ -1,32 +1,45 @@ from typing import Union + @bird --def zoo(): ... -+def zoo(): -+ ... + def zoo(): ... --class A: ... - -+class A: -+ ... + + class A: ... + + @bar class B: -- def BMethod(self) -> None: ... -+ def BMethod(self) -> None: -+ ... -+ + def BMethod(self) -> None: ... @overload -- def BMethod(self, arg: List[str]) -> None: ... -+ def BMethod(self, arg: List[str]) -> None: -+ ... -+ -+ -+class C: -+ ... + def BMethod(self, arg: List[str]) -> None: ... --class C: ... - - @hmm --class D: ... -+class D: -+ ... + + class C: ... + + -+class E: -+ ... + @hmm + class D: ... --class E: ... ++ + class E: ... ++ @baz --def foo() -> None: ... -+def foo() -> None: -+ ... - --class F(A, C): ... + def foo() -> None: ... --def spam() -> None: ... -+class F(A, C): -+ ... + + class F(A, C): ... + + -+def spam() -> None: -+ ... + def spam() -> None: ... + + @overload --def spam(arg: str) -> str: ... -+def spam(arg: str) -> str: -+ ... -+ + def spam(arg: str) -> str: ... ++ var: int = 1 --def eggs() -> Union[str, int]: ... + -+def eggs() -> Union[str, int]: -+ ... + def eggs() -> Union[str, int]: ... ``` ## Ruff Output @@ -122,60 +97,47 @@ from typing import Union @bird -def zoo(): - ... +def zoo(): ... -class A: - ... +class A: ... @bar class B: - def BMethod(self) -> None: - ... - + def BMethod(self) -> None: ... @overload - def BMethod(self, arg: List[str]) -> None: - ... + def BMethod(self, arg: List[str]) -> None: ... -class C: - ... +class C: ... @hmm -class D: - ... +class D: ... -class E: - ... +class E: ... @baz -def foo() -> None: - ... +def foo() -> None: ... -class F(A, C): - ... +class F(A, C): ... -def spam() -> None: - ... +def spam() -> None: ... @overload -def spam(arg: str) -> str: - ... +def spam(arg: str) -> str: ... var: int = 1 -def eggs() -> Union[str, int]: - ... +def eggs() -> Union[str, int]: ... ``` ## Black Output diff --git a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@miscellaneous__force_pyi.pyi.snap b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@miscellaneous__force_pyi.pyi.snap deleted file mode 100644 index 2eb67a391b12b..0000000000000 --- a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@miscellaneous__force_pyi.pyi.snap +++ /dev/null @@ -1,128 +0,0 @@ ---- -source: crates/ruff_python_formatter/tests/fixtures.rs -input_file: crates/ruff_python_formatter/resources/test/fixtures/black/miscellaneous/force_pyi.pyi ---- -## Input - -```python -from typing import Union - -@bird -def zoo(): ... - -class A: ... -@bar -class B: - def BMethod(self) -> None: ... - @overload - def BMethod(self, arg : List[str]) -> None: ... - -class C: ... -@hmm -class D: ... -class E: ... - -@baz -def foo() -> None: - ... - -class F (A , C): ... -def spam() -> None: ... - -@overload -def spam(arg: str) -> str: ... - -var : int = 1 - -def eggs() -> Union[str, int]: ... -``` - -## Black Differences - -```diff ---- Black -+++ Ruff -@@ -15,7 +15,6 @@ - - @hmm - class D: ... -- - class E: ... - - @baz -``` - -## Ruff Output - -```python -from typing import Union - -@bird -def zoo(): ... - -class A: ... - -@bar -class B: - def BMethod(self) -> None: ... - @overload - def BMethod(self, arg: List[str]) -> None: ... - -class C: ... - -@hmm -class D: ... -class E: ... - -@baz -def foo() -> None: ... - -class F(A, C): ... - -def spam() -> None: ... -@overload -def spam(arg: str) -> str: ... - -var: int = 1 - -def eggs() -> Union[str, int]: ... -``` - -## Black Output - -```python -from typing import Union - -@bird -def zoo(): ... - -class A: ... - -@bar -class B: - def BMethod(self) -> None: ... - @overload - def BMethod(self, arg: List[str]) -> None: ... - -class C: ... - -@hmm -class D: ... - -class E: ... - -@baz -def foo() -> None: ... - -class F(A, C): ... - -def spam() -> None: ... -@overload -def spam(arg: str) -> str: ... - -var: int = 1 - -def eggs() -> Union[str, int]: ... -``` - - diff --git a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@raw_docstring.py.snap b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@raw_docstring.py.snap index 25946da099349..833cc46882f7c 100644 --- a/crates/ruff_python_formatter/tests/snapshots/black_compatibility@raw_docstring.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/black_compatibility@raw_docstring.py.snap @@ -28,24 +28,20 @@ class UpperCaseR: ```diff --- Black +++ Ruff -@@ -1,4 +1,6 @@ +@@ -1,3 +1,4 @@ +# flags: --preview --skip-string-normalization class C: -+ r"""Raw""" - -@@ -7,8 +9,9 @@ +@@ -7,7 +8,7 @@ class SingleQuotes: - r'''Raw''' - + r"""Raw""" -+ + class UpperCaseR: - R"""Raw""" ``` ## Ruff Output @@ -53,7 +49,6 @@ class UpperCaseR: ```python # flags: --preview --skip-string-normalization class C: - r"""Raw""" @@ -62,7 +57,6 @@ def f(): class SingleQuotes: - r"""Raw""" diff --git a/crates/ruff_python_formatter/tests/snapshots/format@docstring_code_examples.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@docstring_code_examples.py.snap index 11d4e36d4774e..f1e571e0eae14 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@docstring_code_examples.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@docstring_code_examples.py.snap @@ -7343,10 +7343,8 @@ def rst_literal_subsequent_line_not_indented(): Do cool stuff:: if True: - cool_stuff( - ''' - hiya''' - ) + cool_stuff(''' + hiya''') Done. """ @@ -7821,13 +7819,11 @@ def markdown_nested_fences(): Do cool stuff. `````` - do_something( - ''' + do_something(''' ``` did i trick you? ``` - ''' - ) + ''') `````` Done. @@ -8214,42 +8210,6 @@ def markdown_skipped_rst_directive(): ``` -#### Preview changes -```diff ---- Stable -+++ Preview -@@ -480,10 +480,8 @@ - Do cool stuff:: - - if True: -- cool_stuff( -- ''' -- hiya''' -- ) -+ cool_stuff(''' -+ hiya''') - - Done. - """ -@@ -958,13 +956,11 @@ - Do cool stuff. - - `````` -- do_something( -- ''' -+ do_something(''' - ``` - did i trick you? - ``` -- ''' -- ) -+ ''') - `````` - - Done. -``` - - ### Output 6 ``` indent-style = space @@ -8748,10 +8708,8 @@ def rst_literal_subsequent_line_not_indented(): Do cool stuff:: if True: - cool_stuff( - ''' - hiya''' - ) + cool_stuff(''' + hiya''') Done. """ @@ -9226,13 +9184,11 @@ def markdown_nested_fences(): Do cool stuff. `````` - do_something( - ''' + do_something(''' ``` did i trick you? ``` - ''' - ) + ''') `````` Done. @@ -9619,42 +9575,6 @@ def markdown_skipped_rst_directive(): ``` -#### Preview changes -```diff ---- Stable -+++ Preview -@@ -480,10 +480,8 @@ - Do cool stuff:: - - if True: -- cool_stuff( -- ''' -- hiya''' -- ) -+ cool_stuff(''' -+ hiya''') - - Done. - """ -@@ -958,13 +956,11 @@ - Do cool stuff. - - `````` -- do_something( -- ''' -+ do_something(''' - ``` - did i trick you? - ``` -- ''' -- ) -+ ''') - `````` - - Done. -``` - - ### Output 7 ``` indent-style = tab @@ -10162,10 +10082,8 @@ def rst_literal_subsequent_line_not_indented(): Do cool stuff:: if True: - cool_stuff( - ''' - hiya''' - ) + cool_stuff(''' + hiya''') Done. """ @@ -10640,13 +10558,11 @@ def markdown_nested_fences(): Do cool stuff. `````` - do_something( - ''' + do_something(''' ``` did i trick you? ``` - ''' - ) + ''') `````` Done. @@ -11033,42 +10949,6 @@ def markdown_skipped_rst_directive(): ``` -#### Preview changes -```diff ---- Stable -+++ Preview -@@ -489,10 +489,8 @@ - Do cool stuff:: - - if True: -- cool_stuff( -- ''' -- hiya''' -- ) -+ cool_stuff(''' -+ hiya''') - - Done. - """ -@@ -967,13 +965,11 @@ - Do cool stuff. - - `````` -- do_something( -- ''' -+ do_something(''' - ``` - did i trick you? - ``` -- ''' -- ) -+ ''') - `````` - - Done. -``` - - ### Output 8 ``` indent-style = tab @@ -11567,10 +11447,8 @@ def rst_literal_subsequent_line_not_indented(): Do cool stuff:: if True: - cool_stuff( - ''' - hiya''' - ) + cool_stuff(''' + hiya''') Done. """ @@ -12045,13 +11923,11 @@ def markdown_nested_fences(): Do cool stuff. `````` - do_something( - ''' + do_something(''' ``` did i trick you? ``` - ''' - ) + ''') `````` Done. @@ -12438,42 +12314,6 @@ def markdown_skipped_rst_directive(): ``` -#### Preview changes -```diff ---- Stable -+++ Preview -@@ -480,10 +480,8 @@ - Do cool stuff:: - - if True: -- cool_stuff( -- ''' -- hiya''' -- ) -+ cool_stuff(''' -+ hiya''') - - Done. - """ -@@ -958,13 +956,11 @@ - Do cool stuff. - - `````` -- do_something( -- ''' -+ do_something(''' - ``` - did i trick you? - ``` -- ''' -- ) -+ ''') - `````` - - Done. -``` - - ### Output 9 ``` indent-style = space @@ -12981,10 +12821,8 @@ def rst_literal_subsequent_line_not_indented(): Do cool stuff:: if True: - cool_stuff( - ''' - hiya''' - ) + cool_stuff(''' + hiya''') Done. """ @@ -13459,13 +13297,11 @@ def markdown_nested_fences(): Do cool stuff. `````` - do_something( - ''' + do_something(''' ``` did i trick you? ``` - ''' - ) + ''') `````` Done. @@ -13852,42 +13688,6 @@ def markdown_skipped_rst_directive(): ``` -#### Preview changes -```diff ---- Stable -+++ Preview -@@ -489,10 +489,8 @@ - Do cool stuff:: - - if True: -- cool_stuff( -- ''' -- hiya''' -- ) -+ cool_stuff(''' -+ hiya''') - - Done. - """ -@@ -967,13 +965,11 @@ - Do cool stuff. - - `````` -- do_something( -- ''' -+ do_something(''' - ``` - did i trick you? - ``` -- ''' -- ) -+ ''') - `````` - - Done. -``` - - ### Output 10 ``` indent-style = space @@ -14386,10 +14186,8 @@ def rst_literal_subsequent_line_not_indented(): Do cool stuff:: if True: - cool_stuff( - ''' - hiya''' - ) + cool_stuff(''' + hiya''') Done. """ @@ -14864,13 +14662,11 @@ def markdown_nested_fences(): Do cool stuff. `````` - do_something( - ''' + do_something(''' ``` did i trick you? ``` - ''' - ) + ''') `````` Done. @@ -15257,40 +15053,4 @@ def markdown_skipped_rst_directive(): ``` -#### Preview changes -```diff ---- Stable -+++ Preview -@@ -480,10 +480,8 @@ - Do cool stuff:: - - if True: -- cool_stuff( -- ''' -- hiya''' -- ) -+ cool_stuff(''' -+ hiya''') - - Done. - """ -@@ -958,13 +956,11 @@ - Do cool stuff. - - `````` -- do_something( -- ''' -+ do_something(''' - ``` - did i trick you? - ``` -- ''' -- ) -+ ''') - `````` - - Done. -``` - - diff --git a/crates/ruff_python_formatter/tests/snapshots/format@expression__optional_parentheses_comments.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@expression__optional_parentheses_comments.py.snap index 23c95ef3a2756..d577bea205aee 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@expression__optional_parentheses_comments.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@expression__optional_parentheses_comments.py.snap @@ -288,13 +288,13 @@ ____aaa = 1111111111111111111111111111111111111111111111111111111111111111111111 ## Breaking left # Should break `[a]` first -____[ - a -] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbvvvvvvvvvvv # c +____[a] = ( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbvvvvvvvvvvv # c +) -____[ - a -] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbvvvvvvvvvvv # cc +____[a] = ( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbvvvvvvvvvvv # cc +) ( # some weird comments @@ -352,9 +352,9 @@ ____a: a = ( # 89 characters parenthesized (collapse) ____a: a = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbvvvvvvvvvvvv # c -_a: a[ - b -] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbvvvvvvvvvvvv # c +_a: a[b] = ( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbvvvvvvvvvvvv # c +) ## Augmented Assign @@ -421,44 +421,4 @@ def test6(): ``` -## Preview changes -```diff ---- Stable -+++ Preview -@@ -72,13 +72,13 @@ - ## Breaking left - - # Should break `[a]` first --____[ -- a --] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbvvvvvvvvvvv # c -+____[a] = ( -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbvvvvvvvvvvv # c -+) - --____[ -- a --] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbvvvvvvvvvvv # cc -+____[a] = ( -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbvvvvvvvvvvv # cc -+) - - ( - # some weird comments -@@ -136,9 +136,9 @@ - # 89 characters parenthesized (collapse) - ____a: a = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbvvvvvvvvvvvv # c - --_a: a[ -- b --] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbvvvvvvvvvvvv # c -+_a: a[b] = ( -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbvvvvvvvvvvvv # c -+) - - ## Augmented Assign - -``` - - diff --git a/crates/ruff_python_formatter/tests/snapshots/format@expression__string.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@expression__string.py.snap index 564dbd6c34ac1..96a35c577ad56 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@expression__string.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@expression__string.py.snap @@ -164,6 +164,7 @@ source_type = Python ```python "' test" + '" test' '" test' @@ -323,34 +324,10 @@ x = ( # https://github.com/astral-sh/ruff/issues/7460 trailing_preferred_quote_texts = [''' "''', ''' ""''', ''' """''', ''' """"'''] -a = f"""\x1F""" -a = """\x1F""" +a = f"""\x1f""" +a = """\x1f""" a = """\\x1F""" -a = """\\\x1F""" -``` - - -#### Preview changes -```diff ---- Stable -+++ Preview -@@ -1,4 +1,5 @@ - "' test" -+ - '" test' - - '" test' -@@ -158,7 +159,7 @@ - # https://github.com/astral-sh/ruff/issues/7460 - trailing_preferred_quote_texts = [''' "''', ''' ""''', ''' """''', ''' """"'''] - --a = f"""\x1F""" --a = """\x1F""" -+a = f"""\x1f""" -+a = """\x1f""" - a = """\\x1F""" --a = """\\\x1F""" -+a = """\\\x1f""" +a = """\\\x1f""" ``` @@ -371,6 +348,7 @@ source_type = Python ```python "' test" + '" test' '" test' @@ -530,34 +508,10 @@ x = ( # https://github.com/astral-sh/ruff/issues/7460 trailing_preferred_quote_texts = [''' "''', ''' ""''', ''' """''', ''' """"'''] -a = f"""\x1F""" -a = """\x1F""" +a = f"""\x1f""" +a = """\x1f""" a = """\\x1F""" -a = """\\\x1F""" -``` - - -#### Preview changes -```diff ---- Stable -+++ Preview -@@ -1,4 +1,5 @@ - "' test" -+ - '" test' - - '" test' -@@ -158,7 +159,7 @@ - # https://github.com/astral-sh/ruff/issues/7460 - trailing_preferred_quote_texts = [''' "''', ''' ""''', ''' """''', ''' """"'''] - --a = f"""\x1F""" --a = """\x1F""" -+a = f"""\x1f""" -+a = """\x1f""" - a = """\\x1F""" --a = """\\\x1F""" -+a = """\\\x1f""" +a = """\\\x1f""" ``` diff --git a/crates/ruff_python_formatter/tests/snapshots/format@fmt_on_off__trailing_comments.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@fmt_on_off__trailing_comments.py.snap index 948572efbbf83..c56a1c47b23cb 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@fmt_on_off__trailing_comments.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@fmt_on_off__trailing_comments.py.snap @@ -71,8 +71,7 @@ b = 20 # formatted -def test2(): - ... +def test2(): ... a = 10 @@ -93,21 +92,4 @@ def test3 (): ``` -## Preview changes -```diff ---- Stable -+++ Preview -@@ -21,8 +21,7 @@ - - - # formatted --def test2(): -- ... -+def test2(): ... - - - a = 10 -``` - - diff --git a/crates/ruff_python_formatter/tests/snapshots/format@multiline_string_deviations.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@multiline_string_deviations.py.snap index 6486e0be54777..b04238a5ca7bf 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@multiline_string_deviations.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@multiline_string_deviations.py.snap @@ -84,14 +84,12 @@ call( # Black applies the hugging recursively. We don't (consistent with the hugging style). path.write_text( - textwrap.dedent( - """\ + textwrap.dedent("""\ A triple-quoted string actually leveraging the textwrap.dedent functionality that ends in a trailing newline, representing e.g. file contents. -""" - ) +""") ) @@ -109,28 +107,4 @@ generated_readme = ( ``` -## Preview changes -```diff ---- Stable -+++ Preview -@@ -31,14 +31,12 @@ - - # Black applies the hugging recursively. We don't (consistent with the hugging style). - path.write_text( -- textwrap.dedent( -- """\ -+ textwrap.dedent("""\ - A triple-quoted string - actually leveraging the textwrap.dedent functionality - that ends in a trailing newline, - representing e.g. file contents. --""" -- ) -+""") - ) - - -``` - - diff --git a/crates/ruff_python_formatter/tests/snapshots/format@newlines.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@newlines.py.snap index c275dc4c16a10..08abf4bbeec2b 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@newlines.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@newlines.py.snap @@ -530,13 +530,11 @@ print("below nested functions") class Path: if sys.version_info >= (3, 11): - def joinpath(self): - ... + def joinpath(self): ... # The .open method comes from pathlib.pyi and should be kept in sync. @overload - def open(self): - ... + def open(self): ... def fakehttp(): @@ -568,20 +566,14 @@ if True: pass -def overload1(): - ... # trailing comment - - -def overload1(a: int): - ... +def overload1(): ... # trailing comment +def overload1(a: int): ... -def overload2(): - ... # trailing comment +def overload2(): ... # trailing comment -def overload2(a: int): - ... +def overload2(a: int): ... def overload3(): @@ -589,8 +581,7 @@ def overload3(): # trailing comment -def overload3(a: int): - ... +def overload3(a: int): ... def overload4(): @@ -598,73 +589,7 @@ def overload4(): # trailing comment -def overload4(a: int): - ... -``` - - -## Preview changes -```diff ---- Stable -+++ Preview -@@ -245,13 +245,11 @@ - class Path: - if sys.version_info >= (3, 11): - -- def joinpath(self): -- ... -+ def joinpath(self): ... - - # The .open method comes from pathlib.pyi and should be kept in sync. - @overload -- def open(self): -- ... -+ def open(self): ... - - - def fakehttp(): -@@ -283,20 +281,14 @@ - pass - - --def overload1(): -- ... # trailing comment -+def overload1(): ... # trailing comment -+def overload1(a: int): ... - - --def overload1(a: int): -- ... -+def overload2(): ... # trailing comment - - --def overload2(): -- ... # trailing comment -- -- --def overload2(a: int): -- ... -+def overload2(a: int): ... - - - def overload3(): -@@ -304,8 +296,7 @@ - # trailing comment - - --def overload3(a: int): -- ... -+def overload3(a: int): ... - - - def overload4(): -@@ -313,5 +304,4 @@ - # trailing comment - - --def overload4(a: int): -- ... -+def overload4(a: int): ... +def overload4(a: int): ... ``` diff --git a/crates/ruff_python_formatter/tests/snapshots/format@notebook_docstring.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@notebook_docstring.py.snap index f1ec8638e3ef4..ffda594e165bf 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@notebook_docstring.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@notebook_docstring.py.snap @@ -54,26 +54,11 @@ source_type = Python ```python """ - This looks like a docstring but is not in a notebook because notebooks can't be imported as a module. - Ruff should leave it as is +This looks like a docstring but is not in a notebook because notebooks can't be imported as a module. +Ruff should leave it as is """ -"another normal string" -``` - -#### Preview changes -```diff ---- Stable -+++ Preview -@@ -1,5 +1,6 @@ - """ -- This looks like a docstring but is not in a notebook because notebooks can't be imported as a module. -- Ruff should leave it as is -+This looks like a docstring but is not in a notebook because notebooks can't be imported as a module. -+Ruff should leave it as is - """ -+ - "another normal string" +"another normal string" ``` diff --git a/crates/ruff_python_formatter/tests/snapshots/format@preview.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@preview.py.snap index 3dbe31a6aa70d..96c34a25aaa4d 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@preview.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@preview.py.snap @@ -92,13 +92,13 @@ source_type = Python """ Black's `Preview.module_docstring_newlines` """ + first_stmt_after_module_level_docstring = 1 class CachedRepository: # Black's `Preview.dummy_implementations` - def get_release_info(self): - ... + def get_release_info(self): ... def raw_docstring(): @@ -118,23 +118,22 @@ def reference_docstring_newlines(): class RemoveNewlineBeforeClassDocstring: - """Black's `Preview.no_blank_line_before_class_docstring`""" def f(): """Black's `Preview.prefer_splitting_right_hand_side_of_assignments`""" - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[ - bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb - ] = cccccccc.ccccccccccccc.cccccccc + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ( + cccccccc.ccccccccccccc.cccccccc + ) - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[ - bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb - ] = cccccccc.ccccccccccccc().cccccccc + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ( + cccccccc.ccccccccccccc().cccccccc + ) - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[ - bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb - ] = cccccccc.ccccccccccccc(d).cccccccc + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ( + cccccccc.ccccccccccccc(d).cccccccc + ) aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ( cccccccc.ccccccccccccc(d).cccccccc + e @@ -148,84 +147,12 @@ def f(): + eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee ) - self._cache: dict[ - DependencyCacheKey, list[list[DependencyPackage]] - ] = collections.defaultdict(list) - self._cached_dependencies_by_level: dict[ - int, list[DependencyCacheKey] - ] = collections.defaultdict(list) -``` - - -#### Preview changes -```diff ---- Stable -+++ Preview -@@ -1,13 +1,13 @@ - """ - Black's `Preview.module_docstring_newlines` - """ -+ - first_stmt_after_module_level_docstring = 1 - - - class CachedRepository: - # Black's `Preview.dummy_implementations` -- def get_release_info(self): -- ... -+ def get_release_info(self): ... - - - def raw_docstring(): -@@ -27,23 +27,22 @@ - - - class RemoveNewlineBeforeClassDocstring: -- - """Black's `Preview.no_blank_line_before_class_docstring`""" - - - def f(): - """Black's `Preview.prefer_splitting_right_hand_side_of_assignments`""" -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[ -- bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb -- ] = cccccccc.ccccccccccccc.cccccccc -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ( -+ cccccccc.ccccccccccccc.cccccccc -+ ) - -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[ -- bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb -- ] = cccccccc.ccccccccccccc().cccccccc -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ( -+ cccccccc.ccccccccccccc().cccccccc -+ ) - -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[ -- bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb -- ] = cccccccc.ccccccccccccc(d).cccccccc -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ( -+ cccccccc.ccccccccccccc(d).cccccccc -+ ) - - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ( - cccccccc.ccccccccccccc(d).cccccccc + e -@@ -57,9 +56,9 @@ - + eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee - ) - -- self._cache: dict[ -- DependencyCacheKey, list[list[DependencyPackage]] -- ] = collections.defaultdict(list) -- self._cached_dependencies_by_level: dict[ -- int, list[DependencyCacheKey] -- ] = collections.defaultdict(list) -+ self._cache: dict[DependencyCacheKey, list[list[DependencyPackage]]] = ( -+ collections.defaultdict(list) -+ ) -+ self._cached_dependencies_by_level: dict[int, list[DependencyCacheKey]] = ( -+ collections.defaultdict(list) -+ ) + self._cache: dict[DependencyCacheKey, list[list[DependencyPackage]]] = ( + collections.defaultdict(list) + ) + self._cached_dependencies_by_level: dict[int, list[DependencyCacheKey]] = ( + collections.defaultdict(list) + ) ``` diff --git a/crates/ruff_python_formatter/tests/snapshots/format@quote_style.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@quote_style.py.snap index 9ee59a8d6d7e7..d00f653417462 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@quote_style.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@quote_style.py.snap @@ -73,7 +73,8 @@ source_type = Python ``` ```python -'single' # this string is treated as a docstring +"single" # this string is treated as a docstring + 'double' r'r single' r'r double' @@ -130,20 +131,6 @@ def docstring_single(): ``` -#### Preview changes -```diff ---- Stable -+++ Preview -@@ -1,4 +1,5 @@ --'single' # this string is treated as a docstring -+"single" # this string is treated as a docstring -+ - 'double' - r'r single' - r'r double' -``` - - ### Output 2 ``` indent-style = space @@ -161,6 +148,7 @@ source_type = Python ```python "single" # this string is treated as a docstring + "double" r"r single" r"r double" @@ -217,19 +205,6 @@ def docstring_single(): ``` -#### Preview changes -```diff ---- Stable -+++ Preview -@@ -1,4 +1,5 @@ - "single" # this string is treated as a docstring -+ - "double" - r"r single" - r"r double" -``` - - ### Output 3 ``` indent-style = space @@ -247,6 +222,7 @@ source_type = Python ```python 'single' # this string is treated as a docstring + "double" r'r single' r"r double" @@ -303,17 +279,4 @@ def docstring_single(): ``` -#### Preview changes -```diff ---- Stable -+++ Preview -@@ -1,4 +1,5 @@ - 'single' # this string is treated as a docstring -+ - "double" - r'r single' - r"r double" -``` - - diff --git a/crates/ruff_python_formatter/tests/snapshots/format@statement__ann_assign.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@statement__ann_assign.py.snap index f89b29a9add25..05c361381644a 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@statement__ann_assign.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@statement__ann_assign.py.snap @@ -39,9 +39,9 @@ bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: Bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb = ( Bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb() ) -bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: ( - Bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb -) = Bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb() +bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: Bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb = ( + Bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb() +) JSONSerializable: TypeAlias = ( "str | int | float | bool | None | list | tuple | JSONMapping" @@ -61,39 +61,9 @@ JSONSerializable: str | int | float | bool | None | list | tuple | JSONMapping = # Regression test: Don't forget the parentheses in the annotation when breaking class DefaultRunner: - task_runner_cls: TaskRunnerProtocol | typing.Callable[ - [], typing.Any - ] = DefaultTaskRunner -``` - - -## Preview changes -```diff ---- Stable -+++ Preview -@@ -7,9 +7,9 @@ - Bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb() - ) - --bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: ( -- Bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb --) = Bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb() -+bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: Bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb = ( -+ Bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb() -+) - - JSONSerializable: TypeAlias = ( - "str | int | float | bool | None | list | tuple | JSONMapping" -@@ -29,6 +29,6 @@ - - # Regression test: Don't forget the parentheses in the annotation when breaking - class DefaultRunner: -- task_runner_cls: TaskRunnerProtocol | typing.Callable[ -- [], typing.Any -- ] = DefaultTaskRunner -+ task_runner_cls: TaskRunnerProtocol | typing.Callable[[], typing.Any] = ( -+ DefaultTaskRunner -+ ) + task_runner_cls: TaskRunnerProtocol | typing.Callable[[], typing.Any] = ( + DefaultTaskRunner + ) ``` diff --git a/crates/ruff_python_formatter/tests/snapshots/format@statement__assign.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@statement__assign.py.snap index b78a7687774c4..832fadbd6b32e 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@statement__assign.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@statement__assign.py.snap @@ -87,9 +87,7 @@ c = b[dddddd, aaaaaa] = ( ## Output ```python # break left hand side -a1akjdshflkjahdslkfjlasfdahjlfds = ( - bakjdshflkjahdslkfjlasfdahjlfds -) = ( +a1akjdshflkjahdslkfjlasfdahjlfds = bakjdshflkjahdslkfjlasfdahjlfds = ( cakjdshflkjahdslkfjlasfdahjlfds ) = kjaödkjaföjfahlfdalfhaöfaöfhaöfha = fkjaödkjaföjfahlfdalfhaöfaöfhaöfha = g = 3 @@ -97,15 +95,13 @@ a1akjdshflkjahdslkfjlasfdahjlfds = ( a2 = b2 = 2 # Break the last element -a = ( - asdf -) = ( +a = asdf = ( fjhalsdljfalflaflapamsakjsdhflakjdslfjhalsdljfalflaflapamsakjsdhflakjdslfjhalsdljfal ) = 1 -aa = [ - bakjdshflkjahdslkfjlasfdahjlfds -] = dddd = ddd = fkjaödkjaföjfahlfdalfhaöfaöfhaöfha = g = [3] +aa = [bakjdshflkjahdslkfjlasfdahjlfds] = dddd = ddd = ( + fkjaödkjaföjfahlfdalfhaöfaöfhaöfha +) = g = [3] aa = [] = dddd = ddd = fkjaödkjaföjfahlfdalfhaöfaöfhaöfha = g = [3] @@ -169,40 +165,4 @@ c = b[dddddd, aaaaaa] = ( ``` -## Preview changes -```diff ---- Stable -+++ Preview -@@ -1,7 +1,5 @@ - # break left hand side --a1akjdshflkjahdslkfjlasfdahjlfds = ( -- bakjdshflkjahdslkfjlasfdahjlfds --) = ( -+a1akjdshflkjahdslkfjlasfdahjlfds = bakjdshflkjahdslkfjlasfdahjlfds = ( - cakjdshflkjahdslkfjlasfdahjlfds - ) = kjaödkjaföjfahlfdalfhaöfaöfhaöfha = fkjaödkjaföjfahlfdalfhaöfaöfhaöfha = g = 3 - -@@ -9,15 +7,13 @@ - a2 = b2 = 2 - - # Break the last element --a = ( -- asdf --) = ( -+a = asdf = ( - fjhalsdljfalflaflapamsakjsdhflakjdslfjhalsdljfalflaflapamsakjsdhflakjdslfjhalsdljfal - ) = 1 - --aa = [ -- bakjdshflkjahdslkfjlasfdahjlfds --] = dddd = ddd = fkjaödkjaföjfahlfdalfhaöfaöfhaöfha = g = [3] -+aa = [bakjdshflkjahdslkfjlasfdahjlfds] = dddd = ddd = ( -+ fkjaödkjaföjfahlfdalfhaöfaöfhaöfha -+) = g = [3] - - aa = [] = dddd = ddd = fkjaödkjaföjfahlfdalfhaöfaöfhaöfha = g = [3] - -``` - - diff --git a/crates/ruff_python_formatter/tests/snapshots/format@statement__class_definition.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@statement__class_definition.py.snap index eec7f540f77b5..6368fd730b71e 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@statement__class_definition.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@statement__class_definition.py.snap @@ -264,8 +264,7 @@ class Test( # trailing class comment pass -class Test((Aaaa)): - ... +class Test((Aaaa)): ... class Test( @@ -330,7 +329,6 @@ class Test: class Test: - """Docstring""" @@ -347,14 +345,12 @@ class Test: class Test: - """Docstring""" x = 1 class Test: - """Docstring""" # comment @@ -395,20 +391,17 @@ class C( @dataclass # Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->AltCLIP -class AltCLIPOutput(ModelOutput): - ... +class AltCLIPOutput(ModelOutput): ... @dataclass -class AltCLIPOutput: # Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->AltCLIP - ... +class AltCLIPOutput: ... # Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->AltCLIP @dataclass class AltCLIPOutput( # Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->AltCLIP -): - ... +): ... class TestTypeParams[ @@ -499,68 +492,4 @@ class QuerySet(AltersData): ``` -## Preview changes -```diff ---- Stable -+++ Preview -@@ -28,8 +28,7 @@ - pass - - --class Test((Aaaa)): -- ... -+class Test((Aaaa)): ... - - - class Test( -@@ -94,7 +93,6 @@ - - - class Test: -- - """Docstring""" - - -@@ -111,14 +109,12 @@ - - - class Test: -- - """Docstring""" - - x = 1 - - - class Test: -- - """Docstring""" - - # comment -@@ -159,20 +155,17 @@ - - @dataclass - # Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->AltCLIP --class AltCLIPOutput(ModelOutput): -- ... -+class AltCLIPOutput(ModelOutput): ... - - - @dataclass --class AltCLIPOutput: # Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->AltCLIP -- ... -+class AltCLIPOutput: ... # Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->AltCLIP - - - @dataclass - class AltCLIPOutput( - # Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->AltCLIP --): -- ... -+): ... - - - class TestTypeParams[ -``` - - diff --git a/crates/ruff_python_formatter/tests/snapshots/format@statement__function.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@statement__function.py.snap index 4c040409d7c33..fe55e253b1edc 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@statement__function.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@statement__function.py.snap @@ -434,8 +434,7 @@ def function_with_one_argument_and_a_keyword_separator( def test( # comment # another -): - ... +): ... # Argument empty line spacing @@ -444,8 +443,7 @@ def test( a, # another b, -): - ... +): ... ### Different function argument wrappings @@ -489,8 +487,7 @@ def varg_with_leading_comments( b, # comment *args, -): - ... +): ... def kwarg_with_leading_comments( @@ -498,8 +495,7 @@ def kwarg_with_leading_comments( b, # comment **kwargs, -): - ... +): ... def argument_with_long_default( @@ -507,8 +503,7 @@ def argument_with_long_default( b=ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc + [dddddddddddddddddddd, eeeeeeeeeeeeeeeeeeee, ffffffffffffffffffffffff], h=[], -): - ... +): ... def argument_with_long_type_annotation( @@ -517,12 +512,10 @@ def argument_with_long_type_annotation( | yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy | zzzzzzzzzzzzzzzzzzz = [0, 1, 2, 3], h=[], -): - ... +): ... -def test(): - ... +def test(): ... # Type parameter empty line spacing @@ -531,8 +524,7 @@ def test[ A, # another B, -](): - ... +](): ... # Type parameter comments @@ -591,8 +583,7 @@ def single_line_trailing_comma[ # Comment -def with_leading_comment(): - ... +def with_leading_comment(): ... # Comment that could be mistaken for a trailing comment of the function declaration when @@ -624,8 +615,7 @@ def f(arg1=1, *, kwonlyarg1, kwonlyarg2=2): # Regression test for https://github.com/astral-sh/ruff/issues/5176#issuecomment-1598171989 def foo( b=3 + 2, # comment -): - ... +): ... # Comments on the slash or the star, both of which don't have a node @@ -886,8 +876,7 @@ def f( def f( # first # second -): - ... +): ... def f( # first @@ -907,8 +896,7 @@ def f( # first b, # second -): - ... +): ... def f( # first @@ -916,8 +904,7 @@ def f( # first # second b, # third -): - ... +): ... def f( # first @@ -926,8 +913,7 @@ def f( # first # third b, # fourth -): - ... +): ... def f( # first @@ -954,17 +940,14 @@ def f( # first a, # third /, # second -): - ... +): ... # Walrus operator in return type. -def this_is_unusual() -> (please := no): - ... +def this_is_unusual() -> (please := no): ... -def this_is_unusual(x) -> (please := no): - ... +def this_is_unusual(x) -> (please := no): ... # Regression test for: https://github.com/astral-sh/ruff/issues/7465 @@ -1018,167 +1001,4 @@ def function_with_one_argument_and_a_keyword_separator( ``` -## Preview changes -```diff ---- Stable -+++ Preview -@@ -2,8 +2,7 @@ - def test( - # comment - # another --): -- ... -+): ... - - - # Argument empty line spacing -@@ -12,8 +11,7 @@ - a, - # another - b, --): -- ... -+): ... - - - ### Different function argument wrappings -@@ -57,8 +55,7 @@ - b, - # comment - *args, --): -- ... -+): ... - - - def kwarg_with_leading_comments( -@@ -66,8 +63,7 @@ - b, - # comment - **kwargs, --): -- ... -+): ... - - - def argument_with_long_default( -@@ -75,8 +71,7 @@ - b=ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc - + [dddddddddddddddddddd, eeeeeeeeeeeeeeeeeeee, ffffffffffffffffffffffff], - h=[], --): -- ... -+): ... - - - def argument_with_long_type_annotation( -@@ -85,12 +80,10 @@ - | yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy - | zzzzzzzzzzzzzzzzzzz = [0, 1, 2, 3], - h=[], --): -- ... -+): ... - - --def test(): -- ... -+def test(): ... - - - # Type parameter empty line spacing -@@ -99,8 +92,7 @@ - A, - # another - B, --](): -- ... -+](): ... - - - # Type parameter comments -@@ -159,8 +151,7 @@ - - - # Comment --def with_leading_comment(): -- ... -+def with_leading_comment(): ... - - - # Comment that could be mistaken for a trailing comment of the function declaration when -@@ -192,8 +183,7 @@ - # Regression test for https://github.com/astral-sh/ruff/issues/5176#issuecomment-1598171989 - def foo( - b=3 + 2, # comment --): -- ... -+): ... - - - # Comments on the slash or the star, both of which don't have a node -@@ -454,8 +444,7 @@ - def f( - # first - # second --): -- ... -+): ... - - - def f( # first -@@ -475,8 +464,7 @@ - # first - b, - # second --): -- ... -+): ... - - - def f( # first -@@ -484,8 +472,7 @@ - # second - b, - # third --): -- ... -+): ... - - - def f( # first -@@ -494,8 +481,7 @@ - # third - b, - # fourth --): -- ... -+): ... - - - def f( # first -@@ -522,17 +508,14 @@ - a, - # third - /, # second --): -- ... -+): ... - - - # Walrus operator in return type. --def this_is_unusual() -> (please := no): -- ... -+def this_is_unusual() -> (please := no): ... - - --def this_is_unusual(x) -> (please := no): -- ... -+def this_is_unusual(x) -> (please := no): ... - - - # Regression test for: https://github.com/astral-sh/ruff/issues/7465 -``` - - diff --git a/crates/ruff_python_formatter/tests/snapshots/format@statement__long_type_annotations.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@statement__long_type_annotations.py.snap index 184509d8063f1..39bde3ee75bc6 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@statement__long_type_annotations.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@statement__long_type_annotations.py.snap @@ -165,11 +165,21 @@ nested_comment: None | [ ## Output ```python -x1: A[b] | EventHandler | EventSpec | list[ - EventHandler | EventSpec -] | Other | More | AndMore | None = None +x1: ( + A[b] + | EventHandler + | EventSpec + | list[EventHandler | EventSpec] + | Other + | More + | AndMore + | None +) = None -x2: "VeryLongClassNameWithAwkwardGenericSubtype[int] |" "VeryLongClassNameWithAwkwardGenericSubtype[str]" +x2: ( + "VeryLongClassNameWithAwkwardGenericSubtype[int] |" + "VeryLongClassNameWithAwkwardGenericSubtype[str]" +) x6: VeryLongClassNameWithAwkwardGenericSubtype[ integeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeer, @@ -215,12 +225,16 @@ x11: None | [ datasets.VideoDataset, ] = None -x12: None | [ - datasets.ImageDataset, - datasets.TabularDataset, - datasets.TextDataset, - datasets.VideoDataset, -] | Other = None +x12: ( + None + | [ + datasets.ImageDataset, + datasets.TabularDataset, + datasets.TextDataset, + datasets.VideoDataset, + ] + | Other +) = None x13: [ @@ -242,27 +256,34 @@ x14: [ datasets.VideoDataset, ] = None -x15: [ - datasets.ImageDataset, - datasets.TabularDataset, - datasets.TextDataset, - datasets.VideoDataset, -] | [ - datasets.ImageDataset, - datasets.TabularDataset, - datasets.TextDataset, - datasets.VideoDataset, -] | Other = None +x15: ( + [ + datasets.ImageDataset, + datasets.TabularDataset, + datasets.TextDataset, + datasets.VideoDataset, + ] + | [ + datasets.ImageDataset, + datasets.TabularDataset, + datasets.TextDataset, + datasets.VideoDataset, + ] + | Other +) = None -x16: None | Literal[ - "split", - "a bit longer", - "records", - "index", - "table", - "columns", - "values", -] = None +x16: ( + None + | Literal[ + "split", + "a bit longer", + "records", + "index", + "table", + "columns", + "values", + ] +) = None x17: None | [ datasets.ImageDataset, @@ -273,9 +294,13 @@ x17: None | [ class Test: - safe_age: Decimal # the user's age, used to determine if it's safe for them to use ruff + safe_age: ( + Decimal # the user's age, used to determine if it's safe for them to use ruff + ) applied_fixes: int # the number of fixes that this user applied. Used for ranking the users with the most applied fixes. - string_annotation: "Test" # a long comment after a quoted, runtime-only type annotation + string_annotation: ( + "Test" # a long comment after a quoted, runtime-only type annotation + ) ########## @@ -324,128 +349,4 @@ nested_comment: None | [ ``` -## Preview changes -```diff ---- Stable -+++ Preview -@@ -1,8 +1,18 @@ --x1: A[b] | EventHandler | EventSpec | list[ -- EventHandler | EventSpec --] | Other | More | AndMore | None = None -+x1: ( -+ A[b] -+ | EventHandler -+ | EventSpec -+ | list[EventHandler | EventSpec] -+ | Other -+ | More -+ | AndMore -+ | None -+) = None - --x2: "VeryLongClassNameWithAwkwardGenericSubtype[int] |" "VeryLongClassNameWithAwkwardGenericSubtype[str]" -+x2: ( -+ "VeryLongClassNameWithAwkwardGenericSubtype[int] |" -+ "VeryLongClassNameWithAwkwardGenericSubtype[str]" -+) - - x6: VeryLongClassNameWithAwkwardGenericSubtype[ - integeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeer, -@@ -48,12 +58,16 @@ - datasets.VideoDataset, - ] = None - --x12: None | [ -- datasets.ImageDataset, -- datasets.TabularDataset, -- datasets.TextDataset, -- datasets.VideoDataset, --] | Other = None -+x12: ( -+ None -+ | [ -+ datasets.ImageDataset, -+ datasets.TabularDataset, -+ datasets.TextDataset, -+ datasets.VideoDataset, -+ ] -+ | Other -+) = None - - - x13: [ -@@ -75,27 +89,34 @@ - datasets.VideoDataset, - ] = None - --x15: [ -- datasets.ImageDataset, -- datasets.TabularDataset, -- datasets.TextDataset, -- datasets.VideoDataset, --] | [ -- datasets.ImageDataset, -- datasets.TabularDataset, -- datasets.TextDataset, -- datasets.VideoDataset, --] | Other = None -+x15: ( -+ [ -+ datasets.ImageDataset, -+ datasets.TabularDataset, -+ datasets.TextDataset, -+ datasets.VideoDataset, -+ ] -+ | [ -+ datasets.ImageDataset, -+ datasets.TabularDataset, -+ datasets.TextDataset, -+ datasets.VideoDataset, -+ ] -+ | Other -+) = None - --x16: None | Literal[ -- "split", -- "a bit longer", -- "records", -- "index", -- "table", -- "columns", -- "values", --] = None -+x16: ( -+ None -+ | Literal[ -+ "split", -+ "a bit longer", -+ "records", -+ "index", -+ "table", -+ "columns", -+ "values", -+ ] -+) = None - - x17: None | [ - datasets.ImageDataset, -@@ -106,9 +127,13 @@ - - - class Test: -- safe_age: Decimal # the user's age, used to determine if it's safe for them to use ruff -+ safe_age: ( -+ Decimal # the user's age, used to determine if it's safe for them to use ruff -+ ) - applied_fixes: int # the number of fixes that this user applied. Used for ranking the users with the most applied fixes. -- string_annotation: "Test" # a long comment after a quoted, runtime-only type annotation -+ string_annotation: ( -+ "Test" # a long comment after a quoted, runtime-only type annotation -+ ) - - - ########## -``` - - diff --git a/crates/ruff_python_formatter/tests/snapshots/format@statement__return_annotation.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@statement__return_annotation.py.snap index d7e7f4074a620..7bfe9f4aca89e 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@statement__return_annotation.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@statement__return_annotation.py.snap @@ -211,8 +211,7 @@ def zrevrangebylex( start: int | None = None, num: int | None = None, ) -> ( # type: ignore[override] -): - ... +): ... def zrevrangebylex( @@ -224,8 +223,7 @@ def zrevrangebylex( num: int | None = None, ) -> ( # type: ignore[override] # comment -): - ... +): ... def zrevrangebylex( @@ -237,8 +235,7 @@ def zrevrangebylex( num: int | None = None, ) -> ( # type: ignore[override] 1 -): - ... +): ... def zrevrangebylex( @@ -251,8 +248,7 @@ def zrevrangebylex( ) -> ( # type: ignore[override] 1, 2, -): - ... +): ... def zrevrangebylex( @@ -264,14 +260,12 @@ def zrevrangebylex( num: int | None = None, ) -> ( # type: ignore[override] (1, 2) -): - ... +): ... def handleMatch( # type: ignore[override] # https://github.com/python/mypy/issues/10197 self, m: Match[str], data: str -) -> Union[Tuple[None, None, None], Tuple[Element, int, int]]: - ... +) -> Union[Tuple[None, None, None], Tuple[Element, int, int]]: ... def double( @@ -299,50 +293,44 @@ def double( # function arguments break here with a single argument; we do not.) def f( aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, -) -> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: - ... +) -> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: ... def f( aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, a -) -> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: - ... +) -> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: ... def f( aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, -) -> a: - ... +) -> a: ... def f( a, -) -> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: - ... +) -> ( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +): ... def f[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]() -> ( aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - ... +): ... def f[ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -]() -> a: - ... +]() -> a: ... def f[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]( aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, -) -> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: - ... +) -> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: ... def f[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]( aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, -) -> a: - ... +) -> a: ... # Breaking return type annotations. Black adds parentheses if the parameters are @@ -351,137 +339,126 @@ def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> ( Set[ "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ] -): - ... +): ... def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> ( Set[ "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ] -): - ... +): ... def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> ( Set[ "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ] -): - ... +): ... def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> ( Set[ "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ] -): - ... +): ... def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( x, ) -> Set[ "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -]: - ... +]: ... def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( x, ) -> Set[ "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -]: - ... +]: ... def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( *args, ) -> Set[ "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -]: - ... +]: ... def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( # foo ) -> Set[ "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -]: - ... +]: ... def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( # bar ) -> Set[ "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -]: - ... +]: ... def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> ( xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -): - ... +): ... def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> ( xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -): - ... +): ... def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( x, -) -> xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: - ... +) -> xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: ... def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( x, -) -> xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: - ... +) -> ( + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +): ... -def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> X + Y + foooooooooooooooooooooooooooooooooooo(): - ... +def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> ( + X + Y + foooooooooooooooooooooooooooooooooooo() +): ... -def xxxxxxxxxxxxxxxxxxxxxxxxxxxx(x) -> X + Y + foooooooooooooooooooooooooooooooooooo(): - ... +def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( + x, +) -> X + Y + foooooooooooooooooooooooooooooooooooo(): ... def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> ( X and Y and foooooooooooooooooooooooooooooooooooo() -): - ... +): ... def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( x, -) -> X and Y and foooooooooooooooooooooooooooooooooooo(): - ... +) -> X and Y and foooooooooooooooooooooooooooooooooooo(): ... -def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> X | Y | foooooooooooooooooooooooooooooooooooo(): - ... +def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> ( + X | Y | foooooooooooooooooooooooooooooooooooo() +): ... -def xxxxxxxxxxxxxxxxxxxxxxxxxxxx(x) -> X | Y | foooooooooooooooooooooooooooooooooooo(): - ... +def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( + x, +) -> X | Y | foooooooooooooooooooooooooooooooooooo(): ... def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> ( X | Y | foooooooooooooooooooooooooooooooooooo() # comment -): - ... +): ... def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( x, ) -> ( X | Y | foooooooooooooooooooooooooooooooooooo() # comment -): - ... +): ... def double() -> ( @@ -544,298 +521,4 @@ def process_board_action( ``` -## Preview changes -```diff ---- Stable -+++ Preview -@@ -7,8 +7,7 @@ - start: int | None = None, - num: int | None = None, - ) -> ( # type: ignore[override] --): -- ... -+): ... - - - def zrevrangebylex( -@@ -20,8 +19,7 @@ - num: int | None = None, - ) -> ( # type: ignore[override] - # comment --): -- ... -+): ... - - - def zrevrangebylex( -@@ -33,8 +31,7 @@ - num: int | None = None, - ) -> ( # type: ignore[override] - 1 --): -- ... -+): ... - - - def zrevrangebylex( -@@ -47,8 +44,7 @@ - ) -> ( # type: ignore[override] - 1, - 2, --): -- ... -+): ... - - - def zrevrangebylex( -@@ -60,14 +56,12 @@ - num: int | None = None, - ) -> ( # type: ignore[override] - (1, 2) --): -- ... -+): ... - - - def handleMatch( # type: ignore[override] # https://github.com/python/mypy/issues/10197 - self, m: Match[str], data: str --) -> Union[Tuple[None, None, None], Tuple[Element, int, int]]: -- ... -+) -> Union[Tuple[None, None, None], Tuple[Element, int, int]]: ... - - - def double( -@@ -95,50 +89,44 @@ - # function arguments break here with a single argument; we do not.) - def f( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, --) -> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: -- ... -+) -> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: ... - - - def f( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, a --) -> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: -- ... -+) -> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: ... - - - def f( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, --) -> a: -- ... -+) -> a: ... - - - def f( - a, --) -> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: -- ... -+) -> ( -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+): ... - - - def f[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]() -> ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa --): -- ... -+): ... - - - def f[ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa --]() -> a: -- ... -+]() -> a: ... - - - def f[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, --) -> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: -- ... -+) -> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: ... - - - def f[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, --) -> a: -- ... -+) -> a: ... - - - # Breaking return type annotations. Black adds parentheses if the parameters are -@@ -147,137 +135,126 @@ - Set[ - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" - ] --): -- ... -+): ... - - - def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> ( - Set[ - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" - ] --): -- ... -+): ... - - - def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> ( - Set[ - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" - ] --): -- ... -+): ... - - - def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> ( - Set[ - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" - ] --): -- ... -+): ... - - - def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( - x, - ) -> Set[ - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" --]: -- ... -+]: ... - - - def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( - x, - ) -> Set[ - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" --]: -- ... -+]: ... - - - def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( - *args, - ) -> Set[ - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" --]: -- ... -+]: ... - - - def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( # foo - ) -> Set[ - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" --]: -- ... -+]: ... - - - def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( - # bar - ) -> Set[ - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" --]: -- ... -+]: ... - - - def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> ( - xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx --): -- ... -+): ... - - - def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> ( - xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx --): -- ... -+): ... - - - def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( - x, --) -> xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: -- ... -+) -> xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: ... - - - def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( - x, --) -> xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: -- ... -+) -> ( -+ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -+): ... - - --def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> X + Y + foooooooooooooooooooooooooooooooooooo(): -- ... -+def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> ( -+ X + Y + foooooooooooooooooooooooooooooooooooo() -+): ... - - --def xxxxxxxxxxxxxxxxxxxxxxxxxxxx(x) -> X + Y + foooooooooooooooooooooooooooooooooooo(): -- ... -+def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( -+ x, -+) -> X + Y + foooooooooooooooooooooooooooooooooooo(): ... - - - def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> ( - X and Y and foooooooooooooooooooooooooooooooooooo() --): -- ... -+): ... - - - def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( - x, --) -> X and Y and foooooooooooooooooooooooooooooooooooo(): -- ... -+) -> X and Y and foooooooooooooooooooooooooooooooooooo(): ... - - --def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> X | Y | foooooooooooooooooooooooooooooooooooo(): -- ... -+def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> ( -+ X | Y | foooooooooooooooooooooooooooooooooooo() -+): ... - - --def xxxxxxxxxxxxxxxxxxxxxxxxxxxx(x) -> X | Y | foooooooooooooooooooooooooooooooooooo(): -- ... -+def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( -+ x, -+) -> X | Y | foooooooooooooooooooooooooooooooooooo(): ... - - - def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> ( - X | Y | foooooooooooooooooooooooooooooooooooo() # comment --): -- ... -+): ... - - - def xxxxxxxxxxxxxxxxxxxxxxxxxxxx( - x, - ) -> ( - X | Y | foooooooooooooooooooooooooooooooooooo() # comment --): -- ... -+): ... - - - def double() -> ( -``` - - diff --git a/crates/ruff_python_formatter/tests/snapshots/format@statement__top_level.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@statement__top_level.py.snap index d0ecb00410678..ad0b0871dd379 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@statement__top_level.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@statement__top_level.py.snap @@ -61,25 +61,20 @@ def foo(): pass -class Del(expr_context): - ... +class Del(expr_context): ... -class Load(expr_context): - ... +class Load(expr_context): ... # Some comment. -class Other(expr_context): - ... +class Other(expr_context): ... -class Store(expr_context): - ... +class Store(expr_context): ... -class Foo(Bar): - ... +class Foo(Bar): ... class Baz(Qux): @@ -98,14 +93,8 @@ class Quuz(Qux): pass -def bar(): - ... - - -def baz(): - ... - - +def bar(): ... +def baz(): ... def quux(): """Some docstring.""" @@ -115,59 +104,4 @@ def quuz(): ``` -## Preview changes -```diff ---- Stable -+++ Preview -@@ -12,25 +12,20 @@ - pass - - --class Del(expr_context): -- ... -+class Del(expr_context): ... - - --class Load(expr_context): -- ... -+class Load(expr_context): ... - - - # Some comment. --class Other(expr_context): -- ... -+class Other(expr_context): ... - - --class Store(expr_context): -- ... -+class Store(expr_context): ... - - --class Foo(Bar): -- ... -+class Foo(Bar): ... - - - class Baz(Qux): -@@ -49,14 +44,8 @@ - pass - - --def bar(): -- ... -- -- --def baz(): -- ... -- -- -+def bar(): ... -+def baz(): ... - def quux(): - """Some docstring.""" - -``` - - diff --git a/crates/ruff_python_formatter/tests/snapshots/format@statement__with.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@statement__with.py.snap index 5a7f05c3e5c9d..fb2a0b081c264 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@statement__with.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@statement__with.py.snap @@ -629,8 +629,9 @@ with ( pass with ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb as b, + ( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + ) as b, c as d, ): pass @@ -668,25 +669,6 @@ with Child(aaaaaaaaa, bbbbbbbbbbbbbbb, cccccc), Document( ``` -#### Preview changes -```diff ---- Stable -+++ Preview -@@ -295,8 +295,9 @@ - pass - - with ( -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -- + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb as b, -+ ( -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb -+ ) as b, - c as d, - ): - pass -``` - - ### Output 2 ``` indent-style = space diff --git a/crates/ruff_python_formatter/tests/snapshots/format@stub_files__suite.pyi.snap b/crates/ruff_python_formatter/tests/snapshots/format@stub_files__suite.pyi.snap index cea732f045fe3..214efa79175ba 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@stub_files__suite.pyi.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@stub_files__suite.pyi.snap @@ -269,6 +269,7 @@ class NewlinesBetweenInnerClasses: class InnerClass5: def a(self): ... + field1 = 1 class InnerClass6: @@ -278,6 +279,7 @@ class NewlinesBetweenInnerClasses: class InnerClass7: def a(self): ... + print("hi") class InnerClass8: @@ -309,27 +311,4 @@ class ComplexStatements: ``` -## Preview changes -```diff ---- Stable -+++ Preview -@@ -110,6 +110,7 @@ - - class InnerClass5: - def a(self): ... -+ - field1 = 1 - - class InnerClass6: -@@ -119,6 +120,7 @@ - - class InnerClass7: - def a(self): ... -+ - print("hi") - - class InnerClass8: -``` - -