I have a class method which constructs a numpy
array as a class attribute. I want this attribute to be set to None
after it is returned. I'm using an attribute instead of a variable because the creating the array is done in a parallel way. These arrays can be very large so I want to avoid having it in memory twice. What would be the best way to do this?
import numpy as np
class foo:
def __init__(self):
self.values = None
def bar(self):
self.values = np.arange(1e9) # Large array
return self.values
self.values = None # To be set to None after returning
CodePudding user response:
Python does not copy objects on assignment, it only passes a reference to the same object.
return np.arange(1e9)
will simply return a reference to the created array. Creating any new variable holding it, like var = np.arange(1e9)
, will just assign a reference of the array to the variable.
You're welcome to visualize it if it helps.