|
12 | 12 | import sys
|
13 | 13 | from distutils.version import LooseVersion
|
14 | 14 |
|
| 15 | +try: |
| 16 | + from inspect import isawaitable |
| 17 | +except ImportError: |
| 18 | + def isawaitable(f): |
| 19 | + """If isawaitable is undefined, nothing is awaitable""" |
| 20 | + return False |
| 21 | + |
| 22 | +try: |
| 23 | + from concurrent.futures import Future as ConcurrentFuture |
| 24 | +except ImportError: |
| 25 | + class ConcurrentFuture: |
| 26 | + """If concurrent.futures isn't importable, nothing will be a c.f.Future""" |
| 27 | + pass |
| 28 | + |
15 | 29 | try:
|
16 | 30 | from urllib.parse import quote, unquote, urlparse
|
17 | 31 | except ImportError:
|
18 | 32 | from urllib import quote, unquote
|
19 | 33 | from urlparse import urlparse
|
20 | 34 |
|
| 35 | +# tornado.concurrent.Future is asyncio.Future |
| 36 | +# in tornado >=5 with Python 3 |
| 37 | +from tornado.concurrent import Future as TornadoFuture |
| 38 | +from tornado import gen |
21 | 39 | from ipython_genutils import py3compat
|
22 | 40 |
|
23 | 41 | # UF_HIDDEN is a stat flag not defined in the stat module.
|
@@ -305,3 +323,32 @@ def _check_pid_posix(pid):
|
305 | 323 | check_pid = _check_pid_win32
|
306 | 324 | else:
|
307 | 325 | check_pid = _check_pid_posix
|
| 326 | + |
| 327 | + |
| 328 | +def maybe_future(obj): |
| 329 | + """Like tornado's gen.maybe_future |
| 330 | + but more compatible with asyncio for recent versions |
| 331 | + of tornado |
| 332 | + """ |
| 333 | + if isinstance(obj, TornadoFuture): |
| 334 | + return obj |
| 335 | + elif isawaitable(obj): |
| 336 | + return asyncio.ensure_future(obj) |
| 337 | + elif isinstance(obj, ConcurrentFuture): |
| 338 | + return asyncio.wrap_future(obj) |
| 339 | + else: |
| 340 | + # not awaitable, wrap scalar in future |
| 341 | + f = TornadoFuture() |
| 342 | + f.set_result(obj) |
| 343 | + return f |
| 344 | + |
| 345 | +# monkeypatch tornado gen.maybe_future |
| 346 | +# on Python 3 |
| 347 | +# TODO: remove monkeypatch after backporting smaller fix to 5.x |
| 348 | +try: |
| 349 | + import asyncio |
| 350 | +except ImportError: |
| 351 | + pass |
| 352 | +else: |
| 353 | + import tornado.gen |
| 354 | + tornado.gen.maybe_future = maybe_future |
0 commit comments