Skip to content

FBT001: exclude boolean operators #14203

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

Merged
merged 6 commits into from
Nov 10, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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 @@ -94,7 +94,7 @@ def foo(self) -> None:
object.__setattr__(self, "flag", True)


from typing import Optional, Union
from typing import Optional, Union, Self


def func(x: Union[list, Optional[int | str | float | bool]]):
Expand Down Expand Up @@ -154,3 +154,23 @@ def __post_init__(self, force: bool) -> None:

class Settings(BaseSettings):
foo: bool = Field(True, exclude=True)


# https://github.com/astral-sh/ruff/issues/14202
class SupportsXorBool:
def __xor__(self, other: bool) -> Self: ...

# check overload
class CustomFloat:
@overload
def __mul__(self, other: bool) -> Self: ...
@overload
def __mul__(self, other: float) -> Self: ...
@overload
def __mul__(self, other: Self) -> Self: ...

# check union
class BooleanArray:
def __or__(self, other: Self | bool) -> Self: ...
def __ror__(self, other: Self | bool) -> Self: ...
def __ior__(self, other: Self | bool) -> Self: ...
79 changes: 78 additions & 1 deletion crates/ruff_linter/src/rules/flake8_boolean_trap/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,86 @@ pub(super) fn is_user_allowed_func_call(
})
}

/// Returns `true` if a function defines a binary operator.
/// This only includes operators, i.e. functions that are usually not called directly.
/// See: <https://docs.python.org/3/library/operator.html>
pub(super) fn is_operator_method(name: &str) -> bool {
matches!(
name,
"__contains__" // in
// item access ([])
| "__getitem__" // []
| "__setitem__" // []=
| "__delitem__" // del []
// addition (+)
| "__add__" // +
| "__radd__" // +
| "__iadd__" // +=
// subtraction (-)
| "__sub__" // -
| "__rsub__" // -
| "__isub__" // -=
// multiplication (*)
| "__mul__" // *
| "__rmul__" // *
| "__imul__" // *=
// division (/)
| "__truediv__" // /
| "__rtruediv__" // /
| "__itruediv__" // /=
// floor division (//)
| "__floordiv__" // //
| "__rfloordiv__" // //
| "__ifloordiv__" // //=
// remainder (%)
| "__mod__" // %
| "__rmod__" // %
| "__imod__" // %=
// exponentiation (**)
| "__pow__" // **
| "__rpow__" // **
| "__ipow__" // **=
// left shift (<<)
| "__lshift__" // <<
| "__rlshift__" // <<
| "__ilshift__" // <<=
// right shift (>>)
| "__rshift__" // >>
| "__rrshift__" // >>
| "__irshift__" // >>=
// matrix multiplication (@)
| "__matmul__" // @
| "__rmatmul__" // @
| "__imatmul__" // @=
// meet (&)
| "__and__" // &
| "__rand__" // &
| "__iand__" // &=
// join (|)
| "__or__" // |
| "__ror__" // |
| "__ior__" // |=
// xor (^)
| "__xor__" // ^
| "__rxor__" // ^
| "__ixor__" // ^=
// comparison (>, <, >=, <=, ==, !=)
| "__gt__" // >
| "__lt__" // <
| "__ge__" // >=
| "__le__" // <=
| "__eq__" // ==
| "__ne__" // !=
// unary operators (included for completeness)
| "__pos__" // +
| "__neg__" // -
| "__invert__" // ~
)
}

/// Returns `true` if a function definition is allowed to use a boolean trap.
pub(super) fn is_allowed_func_def(name: &str) -> bool {
matches!(name, "__setitem__" | "__post_init__")
matches!(name, "__post_init__") || is_operator_method(name)
}

/// Returns `true` if an argument is allowed to use a boolean trap. To return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use crate::rules::flake8_boolean_trap::helpers::is_allowed_func_def;
/// ## What it does
/// Checks for the use of boolean positional arguments in function definitions,
/// as determined by the presence of a `bool` type hint.
/// Dunder methods that define operators are exempt from this rule.
///
/// ## Why is this bad?
/// Calling a function with boolean positional arguments is confusing as the
Expand Down Expand Up @@ -93,6 +94,7 @@ use crate::rules::flake8_boolean_trap::helpers::is_allowed_func_def;
/// ## References
/// - [Python documentation: Calls](https://docs.python.org/3/reference/expressions.html#calls)
/// - [_How to Avoid “The Boolean Trap”_ by Adam Johnson](https://adamj.eu/tech/2021/07/10/python-type-hints-how-to-avoid-the-boolean-trap/)
/// - [operator module](https://docs.python.org/3/library/operator.html)
///
/// [preview]: https://docs.astral.sh/ruff/preview/
#[violation]
Expand Down
Loading