Python 内存回收问题

今天遇见一个奇怪的问题,在python中,对自定义类型的局部变量竟然不进行垃圾回收

测试代码如下

# encoding=utf-8
from memory_profiler import profile
import gc
import time

class A(object):
    def __init__(self, id):
        self.id = id
        for i in range(100):
            setattr(self, "test_%s"%i, i)

@profile
def test():
    a = []
    for i in xrange(10000):
        _a = A(i)
        a.append(_a)

@profile
def test1():
    test()
    gc.collect()
    time.sleep(10)

if __name__ == '__main__':
    test1()

  

结果如下:

 

 

在test1中调用test函数,理论上来说,调用完test后,test里的局部变量a应该被释放掉,但实际是没有被释放掉。以上在python2.7 和python3.6中都是一样的结论。

 

posted @ 2020-03-09 23:16  starry_sky  阅读(410)  评论(0编辑  收藏  举报