Reputation: 687
I have a class that contains a function inside which I build and store a potentially very large bumpy array which I read form an HDF5 file. (I store the array as a class object so that when I read the various HDF5 datasets from the file I can use a list comprehension rather than a manual loop.) What I would like is to return and delete the stored array simultaneously (i.e. clean up the memory after the return statement).
class MWE(object):
def __init__(self,*args):
pass
return
def example(self,**kwargs):
self.array = readLargeArrayFromHDF5File(...)
return self.array # And simultaneously clean up self.array?
I know that I could simply delete the array using something like del MWE.array
later on in my script, but is there any way to automatically clean up without me having to remember to do this?
Thanks!
Upvotes: 1
Views: 3465
Reputation: 1162
you ned to use context manager for this kind of stuff! it automatically clears object when it gets out of the with
code block.
from contextlib import contextmanager
class MWE(object):
def __init__(self, *args):
pass
return
@contextmanager
def example(self, **kwargs):
array = readLargeArrayFromHDF5File(...)
try:
yield array
finally:
array = None
@contextmanager
def example_two(self, **kwargs):
array = readLargeArrayFromHDF5File(...)
try:
for item in array:
yield item
finally:
array = None
# usage
with mwe_obj.example_two(kwargs) as result:
for r in result:
# work with your result here
print (r)
# when your code hits this block self.array would get set to None
print ('cleared large array')
Upvotes: 3