Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy coercion problem for left-sided binary operator

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...)

like image 829
gertjan Avatar asked Nov 14 '22 18:11

gertjan


1 Answers

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.

like image 168
gertjan Avatar answered Dec 18 '22 10:12

gertjan