[Numpy-discussion] Ill-defined in-place operations (#1085)

josef.pktd at gmail.com josef.pktd at gmail.com
Wed Apr 15 16:36:09 EDT 2009


On Wed, Apr 15, 2009 at 4:10 PM, Charles R Harris
<charlesr.harris at gmail.com> wrote:
>
>
> On Wed, Apr 15, 2009 at 1:52 PM, Pauli Virtanen <pav at iki.fi> wrote:
>>
>> Mixing views and mutating (eg. in-place) operations can cause surprising
>> and ill-defined results. Consider
>> http://projects.scipy.org/numpy/ticket/1085:
>>
>> >>> import numpy as np
>> >>> x = np.array([[1,2], [3,4]])
>> >>> x
>> array([[1, 2],
>>       [3, 4]])
>> >>> x += x.T
>> >>> x
>> array([[2, 5],
>>       [8, 8]])
>> >>> y = np.array([[1,2], [3,4]], order='F')
>> >>> y
>> array([[1, 2],
>>       [3, 4]])
>> >>> y += y.T
>> >>> y
>> array([[2, 7],
>>       [5, 8]])
>>
>> The result depends on the order in which the elements happen to lie in
>> the memory. Predicting the outcome is nearly impossible. (Also, I think
>> Numpy tries to optimize the order of the loops, making it even more
>> difficult?)
>>
>> This is a sort of a pitfall. Should Numpy issue a warning every time a
>> mutating operation is performed on an array, with input data that is a
>> view on the same array?
>
> My first thought is yes, just because the result is hard to predict.
>
>>
>> Some alternatives:
>>
>>  a) Raise warning for all arrays, even 1-D.
>
> Yes again. Are there examples where one would not want a warning? Examples
> that couldn't be implemented otherwise?
>
> Chuck

I had a similar problem with changing the view or dtype of an array to
a structured array, that also worked directly on the base and only
threw an exception if the base was inconsistent with the change in
dtype.

Is there a list of gotchas for working with views that might produce
unexpected results?

Josef



More information about the NumPy-Discussion mailing list