调用忽略了方法装饰器

时间:2016-01-19 17:23:55

标签: python twisted python-decorators

我正在使用PyDispatcher以及Wrapt@synchronized装饰器。当PyDispatcher调用我的一个处理程序方法时,它忽略了函数装饰器。

我为此创建了一个测试用例。运行以下代码同时运行两个线程,但预期的行为是@synchronized装饰器应阻止第二个线程在_method_b完成之前输入_method_a方法:

from wrapt.decorators import synchronized
import time
from twisted.internet import reactor, threads
from twisted.internet.defer import inlineCallbacks
from pydispatch import dispatcher

class TestSync(object):

    def __init__(self):
        dispatcher.connect(self._method_a, signal="A")
        dispatcher.connect(self._method_b, signal="B")

    @synchronized
    def _method_a(self):
        print "Before Sleep A"
        time.sleep(2)
        print "After Sleep A"

    @synchronized
    def _method_b(self):
        print "Before Sleep B"
        time.sleep(2)
        print "After Sleep B"

    def method_a(self):
        self._method_a()

    def method_b(self):
        self._method_b()

    def test(self):
        reactor.callInThread(dispatcher.send, signal="A")
        reactor.callInThread(dispatcher.send, signal="B")

ts = TestSync()
reactor.callLater(0, ts.test)
reactor.run()

但是,如果不是从Pydispatch调用方法,而是从另一个方法调用它们,@synchronized装饰器确实按预期工作。这可以使用method_amethod_b方法进行测试,这些方法又会调用修饰的方法:

def __init__(self):
    dispatcher.connect(self.method_a, signal="A")
    dispatcher.connect(self.method_b, signal="B")

这是预期的行为吗?我如何告诉Pydispatch不要忽视装饰者?

0 个答案:

没有答案