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

[pyupgrade] Unwrap unary expressions correctly (UP018) #15919

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

InSyncWithFoo
Copy link
Contributor

Summary

Resolves #15859.

The rule now adds parentheses if the original call wraps an unary expression and is:

  • The left-hand side of a binary expression where the operator is **.
  • The caller of a call expression.
  • The subscripted of a subscript expression.
  • The object of an attribute access.

The fix will also be marked as unsafe if there are any comments in its range.

Test Plan

cargo nextest run and cargo insta test.

Copy link
Contributor

github-actions bot commented Feb 4, 2025

ruff-ecosystem results

Linter (stable)

✅ ecosystem check detected no linter changes.

Linter (preview)

✅ ecosystem check detected no linter changes.

@dscorbett
Copy link

Another case to consider is await int(-1).

(Some(Expr::Attribute(_)), LiteralType::Float, true) => format!("({arg_code})"),

(
Some(
Copy link
Member

Choose a reason for hiding this comment

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

Could we reuse the Precedence infrastructure introduced in #15762 over implementing the correct precedence manually here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm not sure how to use that OperatorPrecedence to differentiate foo(int(-1)) and int(-1)().

By the way, there are now four OperatorPrecedences around the codebase: two in the formatter, one in the parser and one in the linter.

Copy link
Member

Choose a reason for hiding this comment

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

Copy link
Member

Choose a reason for hiding this comment

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

Couldn't we use the precedence to represent int's position? I think it's: For the second it's CallAttribute, for the first it's parenthesized (may require adding a new operator precedence)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

UP018 fix ignores operator precedence for numbers with unary operators
3 participants