[Numpy-discussion] how does numpy handle views and garbage collection?

Travis Oliphant oliphant at enthought.com
Wed Sep 30 10:10:58 EDT 2009


On Sep 30, 2009, at 6:43 AM, Chris Colbert wrote:

> Lets say I have function that applies a homogeneous transformation
> matrix to an Nx3 array of points using np.dot.
>
> since the matrix is 4x4 I have to add a 4 column of ones to the array
> so the function looks something like this:
>
> def foo():
>     <--snip-->
>     pts = np.column_stack((Xquad, Yquad, Zquad, np.ones(Zquad.shape)))
>
>     transpts = np.dot(transmat, pts.T).T
>
>     return transpts[:,:3]
>
> Since i'm returning just the view of the array, I imagine python
> doesnt garbage collect transpts once the function returns and falls
> out of scope (because numpy has increfed it in the view operation?).
>
> So in essence, I still have that whole column of ones hanging around
> wasting memory, is that about right?

Yes.  You will have the entire underlying array sitting there until  
the last view on it is deleted.

You can make return a copy explicitly using:

  return transpts[:,:3].copy()

Then, the transpts array will be removed when the function returns.

-Travis



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20090930/71858fa9/attachment.html>


More information about the NumPy-Discussion mailing list