Python - asyncio - Wait for a future inside a callback
<p>Here is my code, I want <code>my_reader</code> to wait maximum 5 seconds for a future then do something with the <code>my_future.result()</code>. Please note that <code>my_reader</code> is <strong>not</strong> a <strong>coroutine</strong>, it is a <strong>callback</strong>.</p>

<pre><code>import asyncio, socket

sock = ...

async def my_coroutine():
    ...

def my_reader():
    my_future = asyncio.Future()
    ...

    # I want to wait (with a timeout) for my_future


loop = asyncio.get_event_loop()
loop.add_reader(sock, my_reader)
loop.run_forever()
loop.close()
</code></pre>

<p>I don't want to use either:</p>

<ul>
<li><code>AbstractEventLoop.create_datagram_endpoint()</code></li>
<li><code>AbstractEventLoop.create_connection()</code></li>
<li>...</li>
</ul>

<p>The socket I have is returned from another module and I have to read packets with a given size. The transfer must happen under 5 seconds.</p>

<p><strong>How to wait for a future inside a callback?</strong></p>

<p>Sorry, waiting in <strong>callbacks</strong> is impossible.
Callback should be executed instantly by definition -- otherwise event loop hangs on callback execution period.</p>

<p>Your logic should be built on <strong>coroutines</strong> but low-level <em>on_read</em> callback may inform these coroutines by setting a value of future.</p>

<p>See <a href="https://github.com/aio-libs/aiopg/blob/master/aiopg/connection.py" rel="nofollow">aiopg.connection</a> for inspiration. The callback is named <code>Connection._ready</code>.</p>

python python-3.5 python-asyncio