On Sat, 2018-12-29 at 17:16 +0100, Matthias Geier wrote:
> Hi Sebastian.
> 
> I don't have an opinion (yet) about this matter, but I have a
> question:
> 
> On Thu, Dec 27, 2018 at 12:30 AM Sebastian Berg wrote:
> 
> [...]
> 
> > new_arr = arr.reshape(new_shape)
> > assert np.may_share_memory(arr, new_arr)
> > 
> > # Which is sometimes -- but should not be -- written as:
> > arr.shape = new_shape  # unnecessary container modification
> 
> [...]
> 
> Why is this discouraged?
> 
> Why do you call this "unnecessary container modification"?
> 
> I've used this idiom in the past for exactly those cases where I
> wanted to make sure no copy is made.
> 
> And if we are not supposed to assign to arr.shape, why is it allowed
> in the first place?

Well, this may be a matter of taste, but say you have an object that
stores an array:

class MyObject:
    def __init__(self):
        self.myarr = some_array


Now, lets say I do:

def some_func(arr):
    # Do something with the array:
    arr.shape = -1

myobject = MyObject()
some_func(myobject)

then myobject will suddenly have the wrong shape stored. In most cases
this is harmless, but I truly believe this is exactly why we have views
and why they are so awesome.
The content of arrays is mutable, but the array object itself should
not be muted normally. There may be some corner cases, but a lot of the
"than why is it allowed" questions are answered with: for history
reasons.

By the way, on error the `arr.shape = ...` code currently creates the
copy temporarily.

- Sebastian


> 
> cheers,
> Matthias
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@python.org
> https://mail.python.org/mailman/listinfo/numpy-discussion
> 

Attachment: signature.asc
Description: This is a digitally signed message part

_______________________________________________
NumPy-Discussion mailing list
NumPy-Discussion@python.org
https://mail.python.org/mailman/listinfo/numpy-discussion

Reply via email to