Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix parentheses around return type annotations #13381

Merged
merged 4 commits into from
Sep 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 29 additions & 8 deletions crates/ruff_dev/src/format_dev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,10 @@ pub(crate) struct Args {
/// Format the files. Without this flag, the python files are not modified
#[arg(long)]
pub(crate) write: bool,

#[arg(long)]
pub(crate) preview: bool,

/// Control the verbosity of the output
#[arg(long, default_value_t, value_enum)]
pub(crate) format: Format,
Expand Down Expand Up @@ -235,7 +239,8 @@ pub(crate) fn main(args: &Args) -> anyhow::Result<ExitCode> {
let all_success = if args.multi_project {
format_dev_multi_project(args, error_file)?
} else {
let result = format_dev_project(&args.files, args.stability_check, args.write)?;
let result =
format_dev_project(&args.files, args.stability_check, args.write, args.preview)?;
let error_count = result.error_count();

if result.error_count() > 0 {
Expand Down Expand Up @@ -344,7 +349,12 @@ fn format_dev_multi_project(
for project_path in project_paths {
debug!(parent: None, "Starting {}", project_path.display());

match format_dev_project(&[project_path.clone()], args.stability_check, args.write) {
match format_dev_project(
&[project_path.clone()],
args.stability_check,
args.write,
args.preview,
) {
Ok(result) => {
total_errors += result.error_count();
total_files += result.file_count;
Expand Down Expand Up @@ -442,6 +452,7 @@ fn format_dev_project(
files: &[PathBuf],
stability_check: bool,
write: bool,
preview: bool,
) -> anyhow::Result<CheckRepoResult> {
let start = Instant::now();

Expand Down Expand Up @@ -477,7 +488,14 @@ fn format_dev_project(
#[cfg(feature = "singlethreaded")]
let iter = { paths.into_iter() };
iter.map(|path| {
let result = format_dir_entry(path, stability_check, write, &black_options, &resolver);
let result = format_dir_entry(
path,
stability_check,
write,
preview,
&black_options,
&resolver,
);
pb_span.pb_inc(1);
result
})
Expand Down Expand Up @@ -532,6 +550,7 @@ fn format_dir_entry(
resolved_file: Result<ResolvedFile, ignore::Error>,
stability_check: bool,
write: bool,
preview: bool,
options: &BlackOptions,
resolver: &Resolver,
) -> anyhow::Result<(Result<Statistics, CheckFileError>, PathBuf), Error> {
Expand All @@ -544,16 +563,19 @@ fn format_dir_entry(
let path = resolved_file.into_path();
let mut options = options.to_py_format_options(&path);

if preview {
options = options.with_preview(PreviewMode::Enabled);
}

let settings = resolver.resolve(&path);
// That's a bad way of doing this but it's not worth doing something better for format_dev
if settings.formatter.line_width != LineWidth::default() {
options = options.with_line_width(settings.formatter.line_width);
}

// Handle panics (mostly in `debug_assert!`)
let result = match catch_unwind(|| format_dev_file(&path, stability_check, write, options)) {
Ok(result) => result,
Err(panic) => {
let result = catch_unwind(|| format_dev_file(&path, stability_check, write, options))
.unwrap_or_else(|panic| {
if let Some(message) = panic.downcast_ref::<String>() {
Err(CheckFileError::Panic {
message: message.clone(),
Expand All @@ -568,8 +590,7 @@ fn format_dir_entry(
message: "(Panic didn't set a string message)".to_string(),
})
}
}
};
});
Ok((result, path))
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,30 +82,6 @@

func([(x, y,) for (x, y) in z], bar)

# Ensure that return type annotations (which use `parenthesize_if_expands`) are also hugged.
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is no longer true. We never add parentheses around lists anymore

def func() -> [1, 2, 3,]:
pass

def func() -> ([1, 2, 3,]):
pass

def func() -> ([1, 2, 3,]):
pass

def func() -> ( # comment
[1, 2, 3,]):
pass

def func() -> (
[1, 2, 3,] # comment
):
pass

def func() -> (
[1, 2, 3,]
# comment
):
pass

# Ensure that nested lists are hugged.
func([
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
# Tests for functions without parameters or a dangling comment
# Black's overall behavior is to:
# 1. Print the return type on the same line as the function header if it fits
# 2. Parenthesize the return type if it doesn't fit.
# The exception to this are subscripts, see below


#########################################################################################
# Return types that use NeedsParantheses::BestFit layout with the exception of subscript
#########################################################################################
# String return type that fits on the same line
def no_parameters_string_return_type() -> "ALongIdentifierButDoesntGetParenthesized":
pass


# String return type that exceeds the line length
def no_parameters_overlong_string_return_type() -> (
"ALongIdentifierButDoesntGetParenthesized"
):
pass


# Name return type that fits on the same line as the function header
def no_parameters_name_return_type() -> ALongIdentifierButDoesntGetParenthesized:
pass


# Name return type that exceeds the configured line width
def no_parameters_overlong_name_return_type() -> (
ALongIdentifierButDoesntGetParenthesized
):
pass



#########################################################################################
# Unions
#########################################################################################

def test_return_overlong_union() -> (
A | B | C | DDDDDDDDDDDDDDDDDDDDDDDD | EEEEEEEEEEEEEEEEEEEEEE
):
pass



def test_return_union_with_elements_exceeding_length() -> (
A
| B
| Ccccccccccccccccccccccccccccccccc
| DDDDDDDDDDDDDDDDDDDDDDDD
| EEEEEEEEEEEEEEEEEEEEEE
):
pass



#########################################################################################
# Multiline strings (NeedsParentheses::Never)
#########################################################################################

def test_return_multiline_string_type_annotation() -> """str
| list[str]
""":
pass


def test_return_multiline_string_binary_expression_return_type_annotation() -> """str
| list[str]
""" + "b":
pass


#########################################################################################
# Implicit concatenated strings (NeedsParentheses::Multiline)
#########################################################################################


def test_implicit_concatenated_string_return_type() -> "str" "bbbbbbbbbbbbbbbb":
pass


def test_overlong_implicit_concatenated_string_return_type() -> (
"liiiiiiiiiiiisssssst[str]" "bbbbbbbbbbbbbbbb"
):
pass


def test_extralong_implicit_concatenated_string_return_type() -> (
"liiiiiiiiiiiisssssst[str]"
"bbbbbbbbbbbbbbbbbbbb"
"cccccccccccccccccccccccccccccccccccccc"
):
pass


#########################################################################################
# Subscript
#########################################################################################
def no_parameters_subscript_return_type() -> list[str]:
pass


# 1. Black tries to keep the list flat by parenthesizing the list as shown below even when the `list` identifier
# fits on the header line. IMO, this adds unnecessary parentheses that can be avoided
# and supporting it requires extra complexity (best_fitting! layout)
def no_parameters_overlong_subscript_return_type_with_single_element() -> (
list[xxxxxxxxxxxxxxxxxxxxx]
):
pass


# 2. Black: Removes the parentheses when the subscript fits after breaking individual elements.
# This is somewhat wasteful because the below list actually fits on a single line when splitting after
# `list[`. It is also inconsistent with how subscripts are normally formatted where it first tries to fit the entire subscript,
# then splits after `list[` but keeps all elements on a single line, and finally, splits after each element.
# IMO: Splitting after the `list[` and trying to keep the elements together when possible seems more consistent.
def no_parameters_subscript_return_type_multiple_elements() -> list[
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
]:
pass


# Black removes the parentheses even the elements exceed the configured line width.
# So does Ruff.
def no_parameters_subscript_return_type_multiple_overlong_elements() -> list[
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
]:
pass


# Black parenthesizes the subscript if its name doesn't fit on the header line.
# So does Ruff
def no_parameters_subscriptreturn_type_with_overlong_value_() -> (
liiiiiiiiiiiiiiiiiiiiist[
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
]
):
pass


# Black: It removes the parentheses when the subscript contains multiple elements as
# `no_parameters_subscript_return_type_multiple_overlong_elements` shows. However, it doesn't
# when the subscript contains a single element. Black then keeps the parentheses.
# Ruff removes the parentheses in this case for consistency.
def no_parameters_overlong_subscript_return_type_with_overlong_single_element() -> (
list[
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
]
):
pass


#########################################################################################
# can_omit_optional_parentheses_layout
#########################################################################################

def test_binary_expression_return_type_annotation() -> aaaaaaaaaaaaaaaaaaaaaaaaaa > [
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
bbbbbbbbbbbbbbbbbbbbbbbbb,
]:
pass


#########################################################################################
# Other
#########################################################################################

# Don't paranthesize lists
def f() -> [
a,
b,
]: pass
Loading
Loading