Multiple coercion problem for a left-handed binary operator

I am implementing an array-like object, which should be compatible with standard numpy arrays. I just find an annoying problem that boils 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 gives the following result:

[<__main__.MyArray instance at 0x91903ec>
 <__main__.MyArray instance at 0x919038c>
 <__main__.MyArray instance at 0x919042c>]

Obviously, instead of calling MyArray().__rmul__( array([1,2,3]) ), as I hoped, it __rmul__is called for each individual element of the array and the result wrapped in an array of objects. This seems to me incompatible with python rules. More importantly, it makes my left multiplication useless.

Does anyone know about this?

(I thought this could be fixed with __coerce__, but the linked document explains that this call is no longer called in response to binary operators ...)

+5
1

, numpy . .

class MyArray( object ):
  __array_priority__ = 1. # <- fixes the problem
  def __rmul__( self, other ):
    return MyArray()

.

+1

All Articles