[Numpy-discussion] Curious behavior of __radd__

Travis Oliphant travis@continuum...
Thu Feb 2 01:50:43 CST 2012


Hey Andreas,

As previously described:  what changes the type of np.complex64(1j) during the A() call is that when a is an array scalar it is converted to an object array because that is the only signature that matches.   During this conversion, what is extracted from the object array is piped through the equivalent of .item() which tries to map to a standard Python object.  

It must be different to break the infinite recursion that would otherwise get setup as the ufunc registered for "Object" loops just calls PyNumber_Add with the extracted objects.   If the extracted object were again the original array scalar, it's __add__ method would be called, which would just call back into the ufunc machinery setting up the cycle again...

I've confirmed this has been the behavior since at least 1.4.x.      So, it's not a regression.    It is actually intentionally to avoid the recursion. 

The proper fix is to add actual scalar math methods instead of re-using the ufunc machinery for the array scalars (this would be much faster as well...)

-Travis



On Feb 1, 2012, at 1:26 PM, Andreas Kloeckner wrote:

> Hi all,
> 
> here's something I don't understand. Consider the following code snippet:
> 
> ---------------------------------------------------
> class A(object):
>    def __radd__(self, other):
>        print(type(other))
> 
> import numpy as np
> np.complex64(1j) + A()
> ---------------------------------------------------
> 
> In my world, this should print <type 'numpy.complex64'>.
> It does print <type 'complex'>.
> 
> Who is casting my sized complex to a built-in complex, and why?
> 
> It can be Python's type coercion, because the behavior is the same in
> Python 3.2. (And the docs say Python 3 doesn't support coercion.)
> 
> (Please cc me.)
> 
> Thanks,
> Andreas
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion



More information about the NumPy-Discussion mailing list