python什么时候删除变量?

2022-01-16 00:00:00 python memory garbage-collection

问题描述

我知道 python 有一个自动垃圾收集器,因此它应该在不再引用变量时自动删除变量.

I know that python has an automatic garbage collector and so it should automatically delete variables when there are no more reference to them.

我的印象是局部变量(函数内部)不会发生这种情况.

My impression is that this does not happen for local variables (inside a function).

def funz(z):
    x = f(z) # x is a np.array and contains a lot of data
    x0 = x[0]
    y = f(z + 1) # y is a np.array and contains a lot of data
    y0 = y[0]

    # is x and y still available here?
    return y0, x0

del x是节省内存的正确方法吗?

Is del x the right way to save memory?

def funz(z):
    x = f(z) # x is a np.array and contains a lot of data
    x0 = x[0]
    del x
    y = f(z + 1) # y is a np.array and contains a lot of data
    y0 = y[0]
    del y

    return y0, x0

我已经编辑了我的示例,使其更类似于我的实际问题.在我的真正问题中,x 和 y 不是列表,而是包含不同大型 np.array 的类.

I have edited my example such that it is more similar to my real problem. In my real problem x and y are not lists but classes that contain different large np.array.

我能够运行代码:

x = f(z)
x0 = x[0]
print(x0)

y = f(z + 1)
y0 = [0]
print(y0)


解决方案

实现使用引用计数来确定何时应该删除变量.

Implementations use reference counting to determine when a variable should be deleted.

变量超出范围后(如您的示例),如果没有剩余的引用,则内存将被释放.

After the variable goes out of scope (as in your example) if there are no remaining references to it, then the memory will be freed.

def a():
    x = 5 # x is within scope while the function is being executed
    print x

a()
# x is now out of scope, has no references and can now be deleted

除了列表中的字典键和元素之外,通常很少有理由在 Python 中手动删除变量.

Aside from dictionary keys and elements in lists, there's usually very little reason to manually delete variables in Python.

不过,正如对这个问题的回答中所说,使用 del可用于显示意图.

Though, as said in the answers to this question, using del can be useful to show intent.

相关文章