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

Limit commutative non-augmented-assignments to primitive data types #10912

Merged
merged 1 commit into from
Apr 12, 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
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,4 @@ def t(self):
index = a_number = a_number + 1
a_number = index = a_number + 1
index = index * index + 10
some_string = "a very long start to the string" + some_string
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,18 @@ use crate::checkers::ast::Checker;
/// When performing such an operation, augmented assignments are more concise
/// and idiomatic.
///
/// ## Known problems
/// In some cases, this rule will not detect assignments in which the target
/// is on the right-hand side of a binary operation (e.g., `x = y + x`, as
/// opposed to `x = x + y`), as such operations are not commutative for
/// certain data types, like strings.
///
/// For example, `x = "prefix-" + x` is not equivalent to `x += "prefix-"`,
/// while `x = 1 + x` is equivalent to `x += 1`.
///
/// If the type of the left-hand side cannot be inferred trivially, the rule
/// will ignore the assignment.
///
/// ## Example
/// ```python
/// x = x + 1
Expand Down Expand Up @@ -101,8 +113,10 @@ pub(crate) fn non_augmented_assignment(checker: &mut Checker, assign: &ast::Stmt
return;
}

// If the operator is commutative, match, e.g., `x = 1 + x`.
// If the operator is commutative, match, e.g., `x = 1 + x`, but limit such matches to primitive
// types.
if operator.is_commutative()
&& (value.left.is_number_literal_expr() || value.left.is_boolean_literal_expr())
&& ComparableExpr::from(target) == ComparableExpr::from(&value.right)
{
let mut diagnostic = Diagnostic::new(NonAugmentedAssignment { operator }, assign.range());
Expand Down
Loading