Skip to content

Instantly share code, notes, and snippets.

@1st1
Created June 25, 2018 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1st1/8cb311b0a852f342f3f7294e6f1798e7 to your computer and use it in GitHub Desktop.
Save 1st1/8cb311b0a852f342f3f7294e6f1798e7 to your computer and use it in GitHub Desktop.
import asyncio
from twisted.internet import asyncioreactor
asyncioreactor.install()
import treq
from twisted.internet.defer import Deferred, ensureDeferred
from twisted.internet.task import react
async def run():
await treq.get("http://google.com")
await Deferred.fromFuture(asyncio.ensure_future(asyncio.sleep(1)))
react(lambda x: ensureDeferred(run()))
@1st1
Copy link
Author

1st1 commented Jun 25, 2018

Here's an idea how to make asyncio Future objects interact with inlineCallbacks automagically:

diff --git a/src/twisted/internet/defer.py b/src/twisted/internet/defer.py
index b14370604..fb2979614 100644
--- a/src/twisted/internet/defer.py
+++ b/src/twisted/internet/defer.py
@@ -1461,6 +1461,10 @@ def _inlineCallbacks(result, g, status):
             status.deferred.errback()
             return

+        if (hasattr(type(result), '_asyncio_future_blocking') and
+                result._asyncio_future_blocking):
+            result = Deferred.fromFuture(result)
+
         if isinstance(result, Deferred):
             # a deferred was yielded, get the result.
             def gotResult(r):

with the above patch, the following code just works:

import asyncio

from twisted.internet import asyncioreactor
asyncioreactor.install()

import treq
from twisted.internet.defer import Deferred, ensureDeferred
from twisted.internet.task import react

async def run():
    print(1)
    await treq.get("http://google.com")
    print(2)
    await asyncio.sleep(1)
    print(3)

react(lambda x: ensureDeferred(run()))

(note that there are no ensure_future() and fromFuture() calls here)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment