Python:是“旧的"为变量分配新内容时是否释放了内存?

问题描述:

如果为变量分配了任何新内容,分配给旧内容"的内存是否将被适当"释放?例如,在下面的脚本中,在为"a"分配了一些新内容之后,将释放作为零数组的变量"a"的内存

If a variable is assigned any new content, will the memory allocated for the "old content" be "properly" free'd? For example, in the following script, will the memory for variable "a" as an array of zeros be free'd after "a" is assigned some new stuff

import numpy
a = numpy.zeros(1000)
a = a+1

我想想,Python足够聪明,可以使用所谓的垃圾收集"来干净地完成所有工作,而我从来没有真正读过它.任何确认吗?我会很感激的.

I would imaging Python is smart enough to do everything cleanly, using the so-called 'garbage collection', which I never really be able to read through. Any confirmation? I'd appreciate it.

最终,旧内存将被释放,尽管您无法预测何时会发生这种情况.它取决于Python的实现和许多其他因素.

Eventually, the old memory will be freed, though you cannot predict when this will happen. It is dependent on the Python implementation and many other factors.

也就是说,对于您给出的示例和CPython实现,应该在分配过程中对旧数组进行垃圾回收.

That said, for the example you gave and the CPython implementation, the old array should be garbage collected during the assignment.

(请注意,NumPy数组是讨论垃圾收集器行为的特别复杂的示例.)

(Note that NumPy arrays are a particularly complex example for discussing garbage-collector behaviour.)