|
| 1 | +use itertools::Itertools; |
| 2 | +use ruff_macros::{ViolationMetadata, derive_message_formats}; |
| 3 | +use ruff_python_ast::{self as ast, CmpOp, Expr}; |
| 4 | +use ruff_text_size::{Ranged, TextRange}; |
| 5 | + |
| 6 | +use crate::checkers::ast::Checker; |
| 7 | +use crate::{FixAvailability, Violation}; |
| 8 | + |
| 9 | +/// ## What it does |
| 10 | +/// Checks for comparisons between floating-point values using `==` or `!=`. |
| 11 | +/// |
| 12 | +/// ## Why is this bad? |
| 13 | +/// Directly comparing floats can produce unreliable results due to the |
| 14 | +/// inherent imprecision of floating-point arithmetic. |
| 15 | +/// |
| 16 | +/// ## When to use `math.isclose()` vs `numpy.isclose()` |
| 17 | +/// |
| 18 | +/// **Use `math.isclose()` for scalar values:** |
| 19 | +/// - Comparing individual float numbers |
| 20 | +/// - Working with regular Python variables (not arrays) |
| 21 | +/// - When you need a single `True`/`False` result |
| 22 | +/// |
| 23 | +/// **Use `numpy.isclose()` for array-like objects:** |
| 24 | +/// - Comparing `pandas` Series, `numpy` arrays, or other vectorized objects |
| 25 | +/// - When you need element-wise comparison of arrays |
| 26 | +/// - Working in data science contexts with vectorized operations |
| 27 | +/// |
| 28 | +/// ## Example |
| 29 | +/// ```python |
| 30 | +/// assert 0.1 + 0.2 == 0.3 # AssertionError |
| 31 | +/// ``` |
| 32 | +/// Use instead: |
| 33 | +/// ```python |
| 34 | +/// import math |
| 35 | +/// |
| 36 | +/// # Scalar comparison |
| 37 | +/// assert math.isclose(0.1 + 0.2, 0.3, abs_tol=1e-9) |
| 38 | +/// ``` |
| 39 | +/// ## References |
| 40 | +/// - [Python documentation: `math.isclose`](https://docs.python.org/3/library/math.html#math.isclose) |
| 41 | +/// - [NumPy documentation: `numpy.isclose`](https://numpy.org/doc/stable/reference/generated/numpy.isclose.html#numpy-isclose) |
| 42 | +#[derive(ViolationMetadata)] |
| 43 | +#[violation_metadata(preview_since = "0.14.3")] |
| 44 | +pub(crate) struct FloatComparison { |
| 45 | + pub left: String, |
| 46 | + pub right: String, |
| 47 | + pub operand: String, |
| 48 | +} |
| 49 | + |
| 50 | +impl Violation for FloatComparison { |
| 51 | + const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; |
| 52 | + |
| 53 | + #[derive_message_formats] |
| 54 | + fn message(&self) -> String { |
| 55 | + format!( |
| 56 | + "Comparison `{} {} {}` should be replaced by `math.isclose()` or `numpy.isclose()`", |
| 57 | + self.left, self.operand, self.right, |
| 58 | + ) |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +/// RUF067 |
| 63 | +pub(crate) fn float_comparison(checker: &Checker, compare: &ast::ExprCompare) { |
| 64 | + let locator = checker.locator(); |
| 65 | + |
| 66 | + for (left, right, operand) in std::iter::once(&*compare.left) |
| 67 | + .chain(&compare.comparators) |
| 68 | + .tuple_windows() |
| 69 | + .zip(&compare.ops) |
| 70 | + .filter(|(_, op)| matches!(op, CmpOp::Eq | CmpOp::NotEq)) |
| 71 | + .filter(|((left, right), _)| has_float(left) || has_float(right)) |
| 72 | + .map(|((left, right), op)| (left, right, op)) |
| 73 | + { |
| 74 | + checker.report_diagnostic( |
| 75 | + FloatComparison { |
| 76 | + left: locator.slice(left.range()).to_string(), |
| 77 | + right: locator.slice(right.range()).to_string(), |
| 78 | + operand: operand.to_string(), |
| 79 | + }, |
| 80 | + TextRange::new(left.start(), right.end()), |
| 81 | + ); |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +fn has_float(expr: &Expr) -> bool { |
| 86 | + match expr { |
| 87 | + Expr::NumberLiteral(ast::ExprNumberLiteral { value, .. }) => { |
| 88 | + matches!(value, ast::Number::Float(_)) |
| 89 | + } |
| 90 | + Expr::BinOp(ast::ExprBinOp { left, right, .. }) => has_float(left) || has_float(right), |
| 91 | + Expr::UnaryOp(ast::ExprUnaryOp { operand, .. }) => has_float(operand), |
| 92 | + _ => false, |
| 93 | + } |
| 94 | +} |
0 commit comments