python的gc模块,Python:在交互模式下使用gc模块的不同行为

I wanted to be able to get a tuple of references to any existing object instances of a class. What I came up with was:

import gc

def instances(theClass):

instances = []

gc.collect()

for i in gc.get_referrers(theClass):

if isinstance(i, theClass):

instances.append(i)

return tuple(instances)

If the above code is entered at the Python intepreter prompt, then you can do the below:

>>> class MyClass(object):

>>> pass

>>> c = MyClass()

>>> instances(MyClass)

(<__main__.myclass object at>,)

Hooray. But then it seems as though gc.collect() doesn't actually do anything inside the function:

>>> del c

>>> instances(MyClass)

(<__main__.myclass object at>,)

But gc.collect() works when outside the function:

>>> del c

>>> gc.collect()

>>> instances(MyClass)

()

So, my question is: How do I make gc.collect() actually do a full collection when inside the function (and why doesn't it work as is)? With corollary question: Is there a better way to accomplish the same goal of returning a tuple with references to object instances for a specific class?

NB: This was all tried in Python 2.7.3. I haven't yet tried it in Python 3, but my goal would be to have a function that works in either (or at least which can be converted with 2to3).

Edited (per answer below) to clarify that the issue was really about interactive mode, not the gc.collect() function per se.

解决方案

When you work in interactive mode, there's a magic built-in variable _ that holds the result of the last expression statement you ran:

>>> 3 + 4

7

>>> _

7

When you delete the c variable, del c isn't an expression, so _ is unchanged:

>>> c = MyClass()

>>> instances(MyClass)

(<__main__.myclass object at>,)

>>> del c

>>> _

(<__main__.myclass object at>,)

_ is keeping a reference to the MyClass instance. When you call gc.collect(), that's an expression, so the return value of gc.collect() replaces the old value of _, and c finally gets collected. It doesn't have anything to do with the garbage collector; any expression would do:

>>> 4

4

>>> instances(MyClass)

()

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值