Python - 从函数内删除(从内存中删除)变量? [英] Python - Delete (remove from memory) a variable from inside a function?
问题描述
我必须加载这个需要传递给函数的巨大对象 A
(这可以减轻almsot 10go),从中提取一个参数 B
来进一步对它进行大量计算。
A = load(file)
def function(A):
B = transorm(A)
B = compute(B)
return(B)
$ c $为了释放一些内存(因为我已经有了一个MemoryError),我想删除 A $ b> code>从内存转换到B.
后立即尝试 del
,但它似乎没有影响脚本级别的
。我也试过 del global()[A]
,但它表示A没有被定义为全局变量。
有没有办法做到这一点?感谢!
解决方案也许从函数内部加载对象可以在这里工作,因为 A $一旦函数返回并且不再以相同的方式占用内存( A
)可能仍然存在于内存中,c $ c>将超出范围,但该内存应该现在可以在需要时再次用于其他用途)。也许试试这样的东西:
f = file#假设文件不是内存h
$ b $ def function_A(file):
A = load(file)#A在函数的本地作用域中创建
return transform(A)#A将超出作用域,释放内存以供使用
def function_B(file):
B = function_A(file)#当这个返回的内存应该再次可用时
return compute(B)
然后调用 function_B(file)
I have to load this massive object A
(that can weight almsot 10go) that I need to pass to a function, that extracts from it a parameter B
to further exert some heavy computations on it.
A = load(file)
def function(A):
B = transorm(A)
B = compute(B)
return(B)
In order to free some memory (as I already had a MemoryError), I'd like to remove A
from memory right after its transformation to B.
I tried del
but it doesn't seem to affect the existence of A
at the script level. I also tried del global()["A"]
but it says that A is not defined as a global variable.
Is there a way to do it? Thanks!
解决方案 Perhaps loading the object from inside the function would work here, since A
will go out of scope once the function returns and no longer take up the memory in the same way(A
will probably still exist in memory, but that memory should now be available for other use again when needed). Maybe try something like this:
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)
Then just call function_B(file)
这篇关于Python - 从函数内删除(从内存中删除)变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!