你是对的;这是twisted.python.rebuild
的限制。它正在更新现有实例的__class__
属性以及导入的函数和类。
一个对付这种方式是简单地submit a patch to Twisted,对于这种情况下修复rebuild
。
但是,如果您想使用Sensitive
达到预期目的,您还可以实现回调保持类,以在当前版本的Twisted上使用rebuild
。以下示例演示如何使用相关类的所有三种方法来更新指向函数的回调字典。请注意,即使没有if needRebuildUpdate...
测试,直接调用x()
将始终获得最新的版本。
from twisted.python.rebuild import rebuild, Sensitive
from twisted.python.filepath import FilePath
p = FilePath("mymodule.py")
def clearcache():
bytecode = p.sibling("mymodule.pyc")
if bytecode.exists():
bytecode.remove()
clearcache()
p.setContent("def x(): return 1")
import mymodule
from mymodule import x
p.setContent("def x(): return 2")
class Something(Sensitive, object):
def __init__(self):
self.stuff = {"something": x}
def invoke(self):
if self.needRebuildUpdate():
for key in list(self.stuff):
self.stuff[key] = self.latestVersionOf(self.stuff[key])
self.rebuildUpToDate()
return self.stuff["something"]()
def test():
print s.invoke()
print x()
s = Something()
test()
clearcache()
rebuild(mymodule)
test()