你是對的;這是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()