[SciPy-dev] Adding to an array with __radd__()

Ed Schofield schofield at ftw.at
Tue Nov 1 05:39:49 CST 2005



Robert Cimrman wrote:
> Travis Oliphant wrote:
> >
> > I think this is a result of the fact that arrays are now new style
> > numbers and the fact that array(B) created a perfectly nice object array.
> >
> > I've committed a change that makes special cases this case so the
> > reflected operands will work if they are defined for something that
> > becomes an object array.
>
> Is it possible, in principle, to call always the sparse matrix operator
> method when it enters an operation with a dense array?
> (a .. dense array, b sparse -- a + b calls b.__radd__, b + a calls
> b.__add__)
>
> The reason I would support this is, that IMHO the higher level object (a
> sparse matrix) knows well how to handle the lower level object (a dense
> array) in numeric operations, but not vice-versa -- there is already a
> number of sparse matrix formats, so the dense array object definitely
> cannot understand them all.

Travis's patch has this effect.  Python calls the left operand's __op__
method, but a dense array on the left now yields control to the right
operand's __rop__ if it can't interpret the right operand as a normal
(non-Object) array.  So the tests that were previously commented in
test_sparse.py now pass for CSC and CSR matrices.

There is one remaining problem with DOK matrices: it never gets this far,
first raising a ValueError while trying to interpret it as a sequence.  I
committed a patch for more graceful handling of such objects that claim to
be sequences but don't allow integer indexing.  I then reverted this,
thinking we should instead fix dok_matrix so PySequence_Check() doesn't
return true.  But I'm not sure if this is possible.  It seems that since
Python 2.2 PySequence_Check() returns true for dictionaries, even though
they don't allow integer indexing.  Isn't this a blatant violation of the
sequence protocol?  (cf http://docs.python.org/ref/sequence-types.html)
Is there any way to override PySequence_Check() to return false for a
subclassed dict like dok_matrix?  If not I suggest we apply my patch after
all -- and complain to the Python developers ;)


-- Ed




More information about the Scipy-dev mailing list