开发者

Callback inside inlineCallbacks function

开发者 https://www.devze.com 2023-03-11 05:27 出处:网络
Let\'s say I have a function like this: def display(this, that): print this, that and a class: class Runner(object):

Let's say I have a function like this:

def display(this, that):
    print this, that

and a class:

class Runner(object):
    def __init__(self, callback):
        self.callback = callback
        self.loop = twisted.internet.task.LoopingCall(repeat)
        self.loop.start(0)

    @defer.inlineCallbacks
    def repeat(self):
        this = yield do_this()
        that = yield do_that()

        if this and that:
      开发者_如何学JAVA      # now I want to call the callback function
            yield self.callback(this, that) # makes sense?

runner = Runner(display)
reactor.run()

Basically what I want to do is I want to create a Runner class which will do some specific tasks and every time it gets a result, it will call the given callback function. Instead of creating a new function which does a specific thing, I want to create a generic class which does only one thing. E.g:

class TwitterReader(object):
    def __init__(self, callback):
        ...
        ...

    @defer.inlineCallbacks
    def get_messages(self):
        ...
        ...
        yield callback(messages)

class MessageFilter(object):
    def __init__(self):
        self.bad_messages = open('bad_messages.txt', 'w')
        self.twitter = TwitterReader(self.message_received)

    def message_received(messages):
        for message in messages:
            for bad_word in BAD_WORDS:
                if bad_word in message:
                    self.bad_messages.write(message)
                    break

I'm new to twisted. So, I'm not sure if this is the right way to do it. Is it?

Thanks


Your problem is that callback inside repeat should instead be self.callback.

Other than that your example should work exactly as written.


You'd only need to yield self.callback if it returned a deferred and you wanted to wait for the result before exiting the repeat function. In your example, your callback is a normal function (which effectively returns None), so there is no advantage to yielding - however it is allowed to yield non-deferred values so no harm is done. From the inlineCallbacks docs:

Things that are not Deferreds may also be yielded, and your generator will be resumed with the same object sent back. This means yield performs an operation roughly equivalent to maybeDeferred.

If your callback did return a deferred (eg, if it was also an inlineCallbacks decorated function) then yielding would pause execution of repeat until the deferred completed. This may or may not be desirable in your application.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号