gc 模块

gc 模块提供了到内建循环垃圾收集器的接口.

Python 使用引用记数来跟踪什么时候销毁一个对象; 一个对象的最后一个引用一旦消失, 这个对象就会被销毁.

Python 提供了一个循环垃圾收集器, 它每隔一段时间执行. 这个收集器查找指向自身的数据结构, 并尝试破坏循环.

你可以使用 gc.collect 函数来强制完整收集. 这个函数将返回收集器销毁的对象的数量.

跟c++ smartpointer 一样。

注意点:gc 模块是一个“循环”垃圾回收器。

ex:

 1 import gc
 2 import sys
 3 gc.set_debug(gc.DEBUG_STATS | gc.DEBUG_LEAK)
 4 a = []
 5 b = []
 6 
 7 a.append(b)
 8 
 9 print 'a refcount:', sys.getrefcount(a)
10 print 'b refcount:', sys.getrefcount(b)
11 
12 del a
13 del b
14 print gc.collect()

运行结果:

a refcount: 2
gc: collecting generation 2...
b refcount: 3
gc: objects in each generation: 531 3232 0
0
gc: done, 0.0010s elapsed.
gc: collecting generation 2...
gc: objects in each generation: 0 0 3608
gc: done, 0.0000s elapsed.

因为不是循环的引用,gc没有起作用。

a.append(b)
b.append(a)

运行结果:

 1 a refcount: 3
 2 b refcount: 3
 3 gc: collecting generation 2...
 4 2
 5 gc: objects in each generation: 533 3232 0
 6 gc: collectable <list 02085300>
 7 gc: collectable <list 0207D3F0>
 8 gc: done, 2 unreachable, 0 uncollectable, 0.0010s elapsed.
 9 gc: collecting generation 2...
10 gc: objects in each generation: 0 0 3610
11 gc: done, 0.0010s elapsed.

垃圾回收后并不意味着没有内存leak

 1 import gc
 2 import sys
 3 
 4 class A:
 5     def __del__(self):
 6         pass
 7 class B:
 8     def __del__(self):
 9         pass
10 
11 gc.set_debug(gc.DEBUG_STATS | gc.DEBUG_LEAK)
12 
13 
14 a = A()
15 b = B()
16 
17 print hex(id(a))
18 print hex(id(a.__dict__))
19 a.b = b
20 b.a = a
21 
22 print 'a refcount:', sys.getrefcount(a)
23 print 'b refcount:', sys.getrefcount(b)
24 
25 del a
26 del b
27 print gc.collect()
28 print gc.garbage

运行结果:

0x205cfa8
0x205dc00
a refcount: 3
b refcount: 3
gc: collecting generation 2...
4
gc: objects in each generation: 549 3232 0
[<__main__.A instance at 0x0205CFA8>, <__main__.B instance at 0x0205CFD0>, {'b': <__main__.B instance at 0x0205CFD0>}, {'a': <__main__.A instance at 0x0205CFA8>}]
gc: uncollectable <A instance at 0205CFA8>
gc: uncollectable <B instance at 0205CFD0>
gc: uncollectable <dict 0205DC00>
gc: uncollectable <dict 0205D8A0>
gc: done, 4 unreachable, 4 uncollectable, 0.0020s elapsed.
gc: collecting generation 2...
gc: objects in each generation: 2 0 3618
gc: done, 0.0000s elapsed.

 gc.garbage,gc.garbage返回是unreachable对象,且不能被回收的的对象。

原文地址:https://www.cnblogs.com/xiaojiangdraug/p/4492209.html