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?
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])
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With