删除/重新分配python列表是否允许垃圾回收?

时间:2015-02-04 14:40:56

标签: python python-2.7 garbage-collection

我知道当Python知道不再引用它们时,它会清除事物的内存。在我的代码中,我正在模拟人口随时间变化。

个人出生并最终死亡。当他们死了,我希望他们从记忆中消失。但与此同时,我已将它们放入各种列表中,然后我就将其删除了。垃圾收集是否已经消失了,它会从内存中清除它们吗?我在代码中跟踪内存(通过guppy)表明内存量正缓慢增加。

这是一个示例代码,可以在每个时间步骤创建4个人,将它们放入列表中,然后转到下一个时间步骤并用新的4个替换这4个。我的问题是当他们被取代时,垃圾收集将意识到他们已经消失了。

class Person:
    def __init__(self,year,id):
        self.id = (year,id)


for year in xrange(100):
    tmplist = []
    for counter in range(4):
        tmplist.append(Person(year,counter))

    mainlist = tmplist
    #do operations to mainlist, but leave it there until replacing it next time through.

(如果您有后续问题,请道歉 - 我在墨尔本时间,所以我要去睡觉了)

1 个答案:

答案 0 :(得分:3)

您可以使用sys.getrefcount进行试验(请注意,结果“通常比您预期的要高一些,因为它包含(临时)引用作为getrefcount()的参数” ):

>>> import sys
>>> class Person(object):
    pass

>>> list1 = [Person() for _ in range(5)]
>>> sys.getrefcount(list1[0])
2  # list1 and getrefcount
>>> list2 = list1[:]
>>> sys.getrefcount(list2[0])
3  # list1, list2 and getrefcount
>>> del list1  # or just reassign e.g. list1 = None
>>> sys.getrefcount(list2[0])
2  # list2 and getrefcount

删除列表(如果它超出范围或显式del如上所述)会减少其中对象的引用计数,因此如果没有其他现存引用(即该列表是最后一个他们被引用的地方)他们的引用数将降至零,最终将被垃圾收集。