Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy Array View and Garbage Collection

Tags:

python

numpy

Suppose I have a function like this:

def f():
    x = np.arange(100)
    return x[:5]

f returns a y, which is a view on x.

Will x still be using memory in the background?

like image 603
Ginger Avatar asked Dec 24 '22 15:12

Ginger


2 Answers

If you return a view x won't be garbage collected. Moreover it will be still accessible through base.

>>> y = f()
>>> y.base
array([ 0,  1,  2,  3,  4,  5,  6, ...., 99])
like image 149
zero323 Avatar answered Dec 29 '22 19:12

zero323


Short answer: yes. Whilst x will be kept alive by your slice. See the documentation for basic slicing.

You should copy the view before returning.

return x[:5].copy() 
like image 28
Dunes Avatar answered Dec 29 '22 19:12

Dunes