[Twisted-Python] why can't a callback be called with a deferred?

Jean-Paul Calderone exarkun at twistedmatrix.com
Wed Feb 27 08:11:31 MST 2019


On Wed, Feb 27, 2019 at 10:07 AM Scott, Barry <barry.scott at forcepoint.com>
wrote:

>
> The code I have posted is the good version so it works and the assert
> does not fire. My goal is to show what I assume is the correct way to code
> a function that uses internal Deferred(), not give an example that breaks.
>
> This should cause the the assert as the code must wait for the thread to
> return a result.
>
> def doWork():
>         d = Deferred()
>         d2 = deferToThread(doWorkHelper)
>         d.callback(d2)
>         return d
>

Ah.  I see.  Indeed, this code is wrong and triggers the assert.  For what
it's worth, there is a simpler solution than the example you gave.  It uses
the "chainDeferred" method:

    def doWork():
        d = Deferred()
        d2 = deferToThread(doWorkHelper)
        d2.chainDeferred(d)
        return d

Jean-Paul
-------------- next part --------------
An HTML attachment was scrubbed...
URL: </pipermail/twisted-python/attachments/20190227/f9b6e27c/attachment-0002.html>


More information about the Twisted-Python mailing list