FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Fix inplace arithmetic operators for numpy>=2 by apdavison · Pull Request #271 · python-quantities/python-quantities · GitHub

Fix inplace arithmetic operators for numpy>=2 - #271

Merged
apdavison merged 3 commits into
python-quantities:masterfrom
apdavison:fix-inplace
Jan 16, 2026
Merged

Fix inplace arithmetic operators for numpy>=2#271
apdavison merged 3 commits into
python-quantities:masterfrom
apdavison:fix-inplace

Conversation

Copy link
Copy Markdown
Contributor

The reason for the broken in-place behaviour reported in #254 and #258 is that with NumPy 1.x, super().__imul__(other) calls self.__array_prepare__(self, context), which calculates the correct units, but _array_prepare__ was removed from NumPy in NumPy 2.0.

This is an inelegant quick fix, calling self.__array_prepare__(self, context) explicitly. It's inelegant because we have to reconstruct context, and we have similar code in multiple places. This will hopefully be enough to get a release out quickly, then we can revisit this when we have more time and fix it properly, probably by implementing __array_ufunc__.

See:

…on and division with NumPy 2.x

The reason for the failure is that with NumPy 1.25, `super().__imul__(other)` calls `self.__array_prepare__(self, context)`,
but `_array_prepare__` was removed in NumPy 2.0.
Long-term, we should probably implement `__array_ufunc__`.
This inelegant fix will hopefully be enough to get a release out quickly, then we can revisit this when we have more time and fix it properly

bjodah commented Jan 16, 2026

Copy link
Copy Markdown
Contributor

I think this looks good, thank you for taking the time to fix this!

Possibly a minor nit:

cself = self.copy()
cother = other.copy()

I guess those calls to copy could be made in the else branch only, no?

Anyhow, +1 to merge from me.

Copy link
Copy Markdown
Contributor Author

@bjodah I had the copy() calls outside the if..else to avoid repeating super().__imul__(other) (which changes self), but on reflection, it's better to repeat the code than to make unnecessary copies, so I've changed it as you suggest.

apdavison merged commit 276789d into python-quantities:master Jan 16, 2026
58 checks passed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants


Back | FazBrowse Home | New Git URL