我有一个包含函数的类,我在其中构建并存储一个可能非常大的颠簸数组,我从HDF5文件中读取该数组。 (我将数组存储为类对象,以便当我从文件中读取各种HDF5数据集时,我可以使用列表解析而不是手动循环。)我想要的是同时返回和删除存储的数组(即清理)返回语句后的内存。)
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?
我知道我可以在我的脚本中稍后使用类似del MWE.array
的内容删除数组,但有没有办法自动清理而不必记住这样做?
谢谢!
答案 0 :(得分:1)
您需要使用context manager来获取此类内容!当它离开with
代码块时,它会自动清除对象。
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')