Skip to content
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

Reverse math operators (__rsub_, __radd__ etc.) interfere with non reverse operators of custom classes #1979

Open
PlasmaHH opened this issue May 8, 2024 · 1 comment

Comments

@PlasmaHH
Copy link

PlasmaHH commented May 8, 2024

I have a class (lets call it MyClass) that wraps a pint.Quantity object and wants to provide some maths on it via sub etc.

Now I have something like

m = MyClass(...) 
u = pint.Quantity(...)
x = m - u

Now what I would like to happen is that my classes sub handles this, however due to the python rules ( both are not the same type ) it first tries u.rsub(m) which will ultimately fail in quantity.py PlainQuantity._add_sub() because of the first checks there and a throw of DimensionalityError.

Now a common good practice is to handle the rsub case only for when you really know how to handle the other case, and otherwise return NotImplemented from within u.__rsub__(m) to then have python try m.__sub__(u) which would be the proper implementation in my case.

This might work if all the __r math functions would catch the DimensionalityError and return NotImplemented instead, because in most cases that error simply means that PlainQuantity got a type there it can't work with.

@andrewgsavage
Copy link
Collaborator

andrewgsavage commented May 8, 2024

Try adding MyClass to pint.compat.upcast_type_map

see also #1888

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

No branches or pull requests

2 participants