Python:在交互模式下使用gc模块的不同行为 [英] Python: different behavior using gc module in interactive mode

查看:96
本文介绍了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)

如果在Python解释器提示符下输入了以上代码,则可以执行以下操作:

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 0x100c616d0>,)

万岁.但随后看来,gc.collect()实际上并未在该函数内执行任何操作:

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 0x100c616d0>,)

但是gc.collect()在功能之外时有效:

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

>>> del c
>>> gc.collect()
>>> instances(MyClass)
()

所以,我的问题是:在函数内部时,如何使gc.collect()真正进行完整收集(为什么它不能按原样工作)?有一个必然的问题:是否有更好的方法来实现相同的目标,即返回带有对特定类的对象实例的引用的元组?

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:这一切都在Python 2.7.3中进行了尝试.我尚未在Python 3中进行过尝试,但是我的目标是拥有一个可以在其中一个函数中运行的函数(或至少可以用2to3转换的函数).

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).

编辑(根据下面的每个答案)来说明问题确实与交互模式有关,而不是gc.collect()函数本身.

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

当删除c变量时,del c不是表达式,因此_不变:

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

>>> c = MyClass()
>>> instances(MyClass)
(<__main__.MyClass object at 0x00000000022E1748>,)
>>> del c
>>> _
(<__main__.MyClass object at 0x00000000022E1748>,)

_保留对MyClass实例的引用.调用gc.collect()时,这是一个表达式,因此gc.collect()的返回值替换了_的旧值,并最终收集了c.它与垃圾收集器无关.任何表达式都可以:

_ 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)
()

这篇关于Python:在交互模式下使用gc模块的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆