Python weakref回调和__del__执行顺序

时间:2009-08-04 17:18:12

标签: python weak-references

在Python中,有没有办法在对象完成后调用函数?

我认为weakref中的回调会这样做,但是一旦对象被垃圾收集,但是在调用对象__del__方法之前,似乎会调用weakref的回调。这似乎与the notes on weakrefs and garbage collection in the Python trunk相反。这是一个例子。

import sys
import weakref

class Spam(object) :
  def __init__(self, name) :
    self.name = name

  def __del__(self) :
    sys.stdout.write("Deleting Spam:%s\n" % self.name)
    sys.stdout.flush()

def cleaner(reference) :
  sys.stdout.write("In callback with reference %s\n" % reference)
  sys.stdout.flush()

spam = Spam("first")
wk_spam = weakref.ref(spam, cleaner)
del spam

我得到的输出是

$ python weakref_test.py 
In callback with reference <weakref at 0xc760a8; dead>
Deleting Spam:first

还有其他传统方式可以做我想要的吗?我可以以某种方式强制完成回调中的最终确定吗?

3 个答案:

答案 0 :(得分:3)

如果“做你想做的事”意味着“当资源离开上下文时运行代码”(而不是,例如,“滥用垃圾收集器来做事情”),你看错了方向。 Python将整个想法简化为context-managers,与with语句一起使用。

from __future__ import with_statement
import sys
class Spam(object):
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        sys.stdout.write("Entering Spam:%s\n" % self.name)
        sys.stdout.flush()

    def __exit__(self, type, value, traceback):
        sys.stdout.write("Lets clean up Spam:%s\n" % self.name) 
        if type is None:
            sys.stdout.write("Leaving Spam:%s in peace\n" % self.name)
            return
        else:
            sys.stdout.write("Leaving Spam:%s with Exception:%r\n" % (self.name, value))


with Spam("first") as spam:
    pass

with Spam("2nd") as spam:
    raise Exception("Oh No!")

给出:

Entering Spam:first
Lets clean up Spam:first
Leaving Spam:first in peace
Entering Spam:2nd
Lets clean up Spam:2nd
Leaving Spam:2nd with Exception:Exception('Oh No!',)
Traceback (most recent call last):
  File "asd.py", line 24, in <module>
    raise Exception("Oh No!")
Exception: Oh No!

答案 1 :(得分:0)

这是一个在另一个线程上使用序列化垃圾循环的解决方案。它可能是你得到的最接近的解决方案。

import sys
from threading import Thread
from Queue import Queue
import weakref

alive = weakref.WeakValueDictionary()
dump = Queue()

def garbageloop():
    while True:
        f = dump.get()
        f()

garbage_thread = Thread(target=garbageloop)
garbage_thread.daemon = True
garbage_thread.start()

class Spam(object) :
  def __init__(self, name) :
    self.name = name
    alive[id(self)] = self

  def __del__(self) :
    sys.stdout.write("Deleting Spam:%s\n" % self.name)
    sys.stdout.flush()
    dump.put(lambda:cleaner(id(self)))

def cleaner(address):
  if address in alive:
    sys.stdout.write("Object was still alive\n")
  else:
    sys.stdout.write("Object is dead\n")
  sys.stdout.flush()

spam = Spam("first")
del spam

答案 2 :(得分:0)

有关弱引用,__del__和垃圾回收的“比您想了解的更多”文档,请查看cpython源代码中的Modules/gc_weakref.txt