numpy/array-default-argument
| Pack | Severity | Fix | Versions |
|---|---|---|---|
| NumPy | warning | unsafe, with xpd check --fix --unsafe-fixes |
All versions |
A NumPy array as a default argument is one array that every call shares, so a write to it shows up in later calls. Default to None and build the array inside the function.
def add_one(acc=np.zeros(2)):def add_one(acc=None): acc = np.zeros(2) if acc is None else acc acc += 1 return accWhat the rule reports
Section titled “What the rule reports”The rule reports def f(acc=np.zeros(2)) when the function writes into acc, because every call shares the one default array.
Writes include augmented assignment, an indexed assignment and methods such as fill or sort.
How to fix it
Section titled “How to fix it”xpd has no automatic fix, so make the change by hand.
Diagnostic message
Section titled “Diagnostic message”The default for $P is one array that every call shares, and this function writes into it, so later calls see the change. Default to None and build the array inside the function.See all rules in the NumPy pack.