Python-从函数内部删除(从内存中删除)变量?

Dom*_*ski 5 python memory optimization global-variables del

我必须加载A需要传递给函数的这个庞大的对象(可以加权10ms的权重),该函数从中提取参数B以进一步对其施加大量计算。

A = load(file)

def function(A):    
   B = transorm(A)    
   B = compute(B)
   return(B)
Run Code Online (Sandbox Code Playgroud)

为了释放一些内存(因为我已经遇到了MemoryError),我想在将A其转换为B后立即从内存中删除。我尝试过,del但它似乎并不影响A脚本级别的存在。我也尝试过,del global()["A"]但是它说A没有定义为全局变量。

有办法吗?谢谢!

Tot*_*tem 0

也许从函数内部加载对象在这里可以工作,因为A一旦函数返回就会超出范围并且不再以相同的方式占用内存(A可能仍然存在于内存中,但是该内存现在应该可用于其他对象)需要时再次使用)。也许尝试这样的事情:

f = file                 # assuming file is not the memory hog

def function_A(file):
    A = load(file)       # A is created in the local scope of the function
    return transform(A)  # A will go out of scope, freeing the memory for use

def function_B(file): 
   B = function_A(file)  # when this returns the memory should be available again
   return compute(B)
Run Code Online (Sandbox Code Playgroud)

然后只需调用function_B(file)