[Numpy-discussion] who owns the data?
Wed Nov 30 15:00:57 CST 2011
On Wed, Nov 30, 2011 at 20:30, <email@example.com> wrote:
> just a basic question (since I haven't looked at this in some time)
> I'm creating a structured array in a function. However, I want to
> return the array with just a simple dtype
> uni = uni.view(dt).reshape(-1, ncols)
> return uni
> the returned uni has owndata=False. Who owns the data, since the
> underlying, original array went out of scope?
Every time you make a view through .view(), slicing, .T, certain
restricted .reshape() calls , etc. a reference to the original object
is stored on the view. Consequently, the original object does not get
garbage collected until all of the views go away too. Making view of a
view just adds another link in the chain. In your example, the
original object that was assigned to `uni` before that last assignment
statement was executed maintains ownership of the memory. The new
ndarray object that gets assigned to `uni` for the return statement
refers to the temporary ndarray returned by .view() which in turn
refers to the original `uni` array which owns the actual memory.
> uni.dtype = dt
> uni.reshape(-1, ncols)
> return uni
> this works and uni owns the data.
uni.reshape() doesn't reshape `uni` inplace, though. It is possible
that your `uni` array wasn't contiguous to begin with. In all of the
cases that your first example would have owndata=False, this one
> I'm only worried whether assigning
> to dtype directly is not a dangerous thing to do.
It's no worse than .view(dt). The same kind of checking goes on in both places.
"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
-- Umberto Eco
More information about the NumPy-Discussion