python对象的垃圾收集,复杂对象上的python垃圾收集器行为

Does python garbage collector cleans up a compound object if some of its parts are still referenced

e.g.

def foo():

A = [ [1, 3, 5, 7], [2, 4, 6, 8]]

return A[1]

B = foo()

Will A[0] be garbage collected?

Is there a way to confirm the same through code?

解决方案

Nothing references the list A and the nested list A[0], so yes, they will be deleted from memory.

The nested list object referenced by A[1] has no connection back to its original container.

Note that it's not the garbage collector that does this; the GC only deals in breaking circular references. This simple case is handled entirely by reference counting.

The moment foo() returns, the local namespace is cleared up. That means A is removed, which means the list object reference count drops to 0. This clears that list object, which means that the contained lists also see their reference count drop by one. For A[0] that means the count drops to 0 too and it is cleared.

For the list object referenced by A[1], you now have a reference B to it, so it's count is still 1 and it remains 'alive'.

To confirm the same through code, simply use a subclass of list with a __del__ method to let us know when the object is being deleted:

>>> class DelList(list):

... def __del__(self):

... print 'Deleted {}'.format(self)

...

>>> def foo():

... A = DelList([DelList([1, 3, 5, 7]), DelList([2, 4, 6, 8])])

... return A[1]

...

>>> B = foo()

Deleted [[1, 3, 5, 7], [2, 4, 6, 8]]

Deleted [1, 3, 5, 7]

>>> del B

Deleted [2, 4, 6, 8]

All this is specific to CPython (the reference Python implementation); other implementations may handle object lifetimes differently (e.g. do use a garbage collector to destroy objects in sweeps), but the lifetime of A and A[0] doesn't change in those cases; the GC will still collect those in other implementations, albeit at a different point in time perhaps.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值