NumPy
The NumPy pack catches silent bugs, NumPy 2.5 deprecations and removals, slow Python element loops, and suboptimal array math on files that import numpy. Examples assume import numpy as np.
| Rules | Safe fix | Unsafe fix | Manual fix |
|---|---|---|---|
| 64 | 1 | 49 | 14 |
Code that gives a wrong result or raises on NumPy 2.5
Section titled “Code that gives a wrong result or raises on NumPy 2.5”| Rule | Severity | Fix | What it finds |
|---|---|---|---|
| compare-to-nan | error | unsafe | A comparison with NaN is False for every value, NaN included. |
| argument-in-wrong-slot | error | unsafe | These calls put an argument where NumPy expects another one, such as a second size where np.zeros expects the dtype, so they raise or give a wrong result. |
| percentile-of-fraction | warning | unsafe | np.percentile takes percents from 0 to 100, so 0.95 asks for a value near the minimum. |
| positional-tolerance | warning | safe | The third argument of np.isclose and np.allclose is rtol, a relative tolerance, and many readers expect an absolute one. |
| arange-float-step | warning | none | With a float step such as 0.1, the length of np.arange depends on rounding, and the stop value can appear in the result. |
| randint-single-value | error | unsafe | The upper bound of randint is excluded, so randint(0, 1) always returns 0. |
| result-is-none | error | unsafe | Methods such as sort() and shuffle() change the array in place and return None, so x = x.sort() sets x to None. |
| result-discarded | error | unsafe | Functions such as np.sort and np.append return a new array and leave the input alone, so a call on its own line does nothing. |
| write-to-copy | error | unsafe | Indexing with a mask or a list of positions gives a copy, so writing into that result never reaches the array. |
| array-truth-value | error | unsafe | and, or, not and chained comparisons ask for the truth of a whole array, which raises ValueError. |
| mask-operator-precedence | error | unsafe | Python applies & and | before comparisons, so x > 2 & x < 8 compares against the wrong value. |
| int-mask-as-index | error | unsafe | mask.astype(int) turns a mask into 0s and 1s, so indexing with it picks element 0 and element 1 over and over. |
| iterator-to-array | error | unsafe | np.array and NumPy reductions do not read values out of a generator, map or a set, so the call gives a wrong value or raises. |
| nan-to-int | warning | unsafe | Casting an array that holds NaN to an int type turns each NaN into -9223372036854775808. |
| read-uninitialized | error | unsafe | np.empty leaves the values unset, so computing with them uses whatever bytes were in memory. |
| array-default-argument | warning | unsafe | A NumPy array as a default argument is one array that every call shares, so a write to it shows up in later calls. |
| append-flattens | error | none | Without axis, np.append and np.insert flatten both arrays, so a row you add becomes loose values in one dimension. |
| compare-reductions | error | unsafe | a.all() == b.all() compares two single booleans, so it is True for many arrays that differ. |
| where-tuple-length | error | unsafe | np.where with one argument returns a tuple with one array per dimension, so its length counts dimensions and not matches. |
Code that raises or warns on NumPy 2.5
Section titled “Code that raises or warns on NumPy 2.5”| Rule | Severity | Fix | What it finds |
|---|---|---|---|
| removed-in-numpy-2 | error | unsafe | These names, modules and keywords were removed between NumPy 1.24 and 2.5, so the code raises. |
| deprecated-in-numpy-2 | warning | unsafe | These names and modules warn on NumPy 2.5 and will stop working in a later release. |
Python work per value on arrays
Section titled “Python work per value on arrays”| Rule | Severity | Fix | What it finds |
|---|---|---|---|
| element-loop | warning | none | A loop that computes one element of an array per pass runs Python once for every value, which was 70 to 530 times slower. |
| axis-reduce-loop | warning | none | A loop or comprehension that reduces one column of an array per pass calls NumPy once for every column. |
| growth-in-loop | warning | none | Growing an array with np.append or np.concatenate in a loop copies every earlier value on each pass. |
| per-value-comprehension | warning | unsafe | A comprehension that applies arithmetic or a math function to each value runs Python once for every value, which was 60 to 470 times slower. |
| builtin-on-array | warning | unsafe | Python's sum, min, max, sorted and list walk an array one value at a time, which was 37 to 47 times slower. |
| np-vectorize | warning | none | np.vectorize, np.frompyfunc and np.apply_along_axis still call a Python function once per value or slice. |
| recurrence-loop | warning | none | A loop that computes each value from the one before runs Python once for every step. |
| slice-fill-loop | warning | none | A loop that fills an array from one start after another writes the same positions many times. |
| mask-per-label | warning | none | Comparing an array with one label per pass makes one pass for every label. |
| random-draw-loop | warning | none | Drawing from a Generator once per pass of a loop makes one call for every pass. |
Arrays built, copied and stored the slow way
Section titled “Arrays built, copied and stored the slow way”| Rule | Severity | Fix | What it finds |
|---|---|---|---|
| array-construction | warning | unsafe | Building an array from range or a Python list makes a Python int for every value first, and np.ones(n) * 3 builds the values twice. |
| needless-copy | warning | unsafe | flatten() and copy() on an array that is already a new copy copy it again. |
| file-roundtrip | warning | none | Writing an array as text with np.savetxt and parsing it back is slow and loses the dtype and the shape. |
Math on whole arrays with a faster or more exact function
Section titled “Math on whole arrays with a faster or more exact function”| Rule | Severity | Fix | What it finds |
|---|---|---|---|
| sort-then-select | warning | unsafe | Sorting every value to read the smallest or largest few was up to 39 times slower. |
| count-nonzero | warning | unsafe | Summing a comparison or taking the length of np.where counts matches the slow way. |
| where-shortcut | warning | unsafe | np.where(x > 0, True, False) copies a mask that is already an array of booleans, which was 17 times slower. |
| expm1-log1p | warning | unsafe | np.exp(x) - 1 and np.log(1 + x) lose digits to rounding when x is near 0. |
| logaddexp | warning | unsafe | np.exp overflows to inf above 709 and underflows to 0 below -745, so a log of a sum of exponentials can be inf where the answer is finite. |
| log-of-product | warning | unsafe | A product can overflow to inf or underflow to 0 before the log is taken. |
| reduce-last | warning | unsafe | np.cumsum(x)[-1] builds every running total to read the last one, which was 8 times slower and adds rounding. |
| power-half | warning | unsafe | np.power(x, 0.5) runs the general power function, which was 2 times slower. |
| sum-of-products | warning | unsafe | np.sum(a * b) builds the array of products to add it up, which was 2.4 times slower. |
| norm-by-hand | warning | unsafe | Building the array of squares to add them up was 3.9 times slower. |
| vecdot | warning | unsafe | Summing squares or products along the last axis builds a temporary array, which was 2.8 times slower. |
| inv-then-multiply | warning | unsafe | Multiplying by an inverse loses more digits than solving, and was 3.8 times slower. |
| log-of-det | warning | unsafe | The determinant can overflow to inf or underflow to 0 before the log is taken. |
| eig-on-symmetric | warning | unsafe | eig treats a symmetric matrix as a general one, which was 3.6 times slower and returns complex values. |
| matmul-diagonal | warning | unsafe | Computing a whole matrix product to read its diagonal or trace was 34 times slower than needed. |
| einsum-optimize | warning | unsafe | Without optimize=, einsum loops over every index at once, which was 339 times slower for three 100 by 100 matrices. |
The API that NumPy's docs prefer on NumPy 2.5
Section titled “The API that NumPy's docs prefer on NumPy 2.5”| Rule | Severity | Fix | What it finds |
|---|---|---|---|
| legacy-random | warning | unsafe | np.random.seed and the functions beside it use a hidden global state that NumPy keeps only for old code. |
| rng-in-loop | warning | none | np.random.default_rng() inside a loop builds a new Generator on every pass. |
| clock-seed | warning | unsafe | A seed taken from the clock repeats whenever two runs start in the same tick. |
| legacy-polynomial | info | unsafe | np.polyfit and its kin are NumPy's legacy polynomial API, and the docs recommend Polynomial.fit as more stable. |
| almost-equal-assert | info | unsafe | assert_almost_equal and its kin are on NumPy's not recommended list, and their default test hides an absolute tolerance of 1.5e-7. |
| assert-on-arrays | info | unsafe | A failed assert np.allclose(a, b) reports only False. |
| legacy-testing-helper | info | unsafe | numpy.testing.assert_ is the legacy form of the assert statement. |
| char-module | info | unsafe | numpy.char is legacy, and NumPy's docs point to numpy.strings. |
| dot-on-matrices | info | unsafe | For two 2-D arrays, NumPy's docs prefer the @ operator to np.dot. |
| mergesort-kind | info | unsafe | kind="mergesort" is kept only for old code and runs the same stable sort as kind="stable". |
| printoptions-restore | info | unsafe | Restoring print options by hand leaves them changed when an error is raised. |
| as-strided | info | none | as_strided reads memory outside the array when a shape or a stride is wrong. |
| numpy-import-alias | info | none | NumPy's docs import it as np, and other code and the fixes of this pack expect that name. |
| unpackbits-popcount | warning | unsafe | Unpacking every byte into eight bits to count the set ones was 37 times slower. |