I am implementing an array-like object that should be interoperable with standard numpy arrays. I just hit an annoying problem that narrows down to the following:
class MyArray( object ):
def __rmul__( self, other ):
return MyArray() # value not important for current purpose
from numpy import array
print array([1,2,3]) * MyArray()
This yields the following output:
[<__main__.MyArray instance at 0x91903ec>
<__main__.MyArray instance at 0x919038c>
<__main__.MyArray instance at 0x919042c>]
Clearly, rather than calling MyArray().__rmul__( array([1,2,3]) )
as I had hoped, __rmul__
is called for every individual element of the array, and the result wrapped in an object array. This seems to me non compliant with python's coercion rules. More importantly, it renders my left multiplication useless.
Does anybody know a way around this?
(I thought a could fix it using __coerce__
but the linked document explains that that one is no longer invoked in response to binary operators...)
It turns out that numpy offers a simple fix for this problem. The following code works as intended.
class MyArray( object ):
__array_priority__ = 1. # <- fixes the problem
def __rmul__( self, other ):
return MyArray()
More information can be found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With