Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python asyncio: yield from wasn't used with future?

I'm attempting to use asyncio to make an asynchronous client/server setup.

For some reason I'm getting AssertionError: yield from wasn't used with future when running the client.

Searching for this error didn't turn up much.
What does this error mean and what's causing it?

#!/usr/bin/env python3

import asyncio
import pickle
import uuid

port = 9999

class ClientProtocol(asyncio.Protocol):
    def __init__(self, loop):
        self.loop = loop
        self.conn = None
        self.uuid = uuid.uuid4()
        self.other_clients = []

    def connection_made(self, transport):
        print("Connected to server")
        self.conn = transport

        m = "hello"
        self.conn.write(m)

    def data_received(self, data):
        print('Data received: {!r}'.format(data))


    def connection_lost(self, exc):
        print('The server closed the connection')
        print('Stop the event loop')
        self.loop.stop()



# note that in my use-case, main() is called continuously by an external game engine
client_init = False
def main():
    # use a global here only for the purpose of providing example code runnable outside of aforementioned game engine
    global client_init

    if client_init != True:
        loop = asyncio.get_event_loop()
        coro = loop.create_connection(lambda: ClientProtocol(loop), '127.0.0.1', port)
        task = asyncio.Task(coro)

        transport, protocol = loop.run_until_complete(coro)

        client_init = True

    # to avoid blocking the execution of main (and of game engine calling it), only run one iteration of the event loop
    loop.stop()
    loop.run_forever()

    if transport:
        transport.write("some data")

if __name__ == "__main__":
    main()

Traceback:

Traceback (most recent call last):
  File "TCPclient.py", line 57, in <module>
    main()
  File "TCPclient.py", line 45, in main
    transport, protocol = loop.run_until_complete(coro)
  File "/usr/lib/python3.5/asyncio/base_events.py", line 337, in run_until_complete
    return future.result()
  File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result
    raise self._exception
  File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step
    result = coro.send(None)
  File "/usr/lib/python3.5/asyncio/base_events.py", line 599, in create_connection
    yield from tasks.wait(fs, loop=self)
  File "/usr/lib/python3.5/asyncio/tasks.py", line 341, in wait
    return (yield from _wait(fs, timeout, return_when, loop))
  File "/usr/lib/python3.5/asyncio/tasks.py", line 424, in _wait
    yield from waiter
  File "/usr/lib/python3.5/asyncio/futures.py", line 359, in __iter__
    assert self.done(), "yield from wasn't used with future"
AssertionError: yield from wasn't used with future
like image 229
gandalf3 Avatar asked May 24 '16 04:05

gandalf3


1 Answers

The problem seems to be that you create a task from your coroutine, but then pass the coroutine to run_until_complete instead:

    coro = loop.create_connection(lambda: ClientProtocol(loop), '127.0.0.1', port)
    task = asyncio.Task(coro)

    transport, protocol = loop.run_until_complete(coro)

Either pass the task:

    coro = loop.create_connection(lambda: ClientProtocol(loop), '127.0.0.1', port)
    task = asyncio.Task(coro)

    transport, protocol = loop.run_until_complete(task)

Or don't create the task and pass the coroutine. run_until_complete will create a task for you

    coro = loop.create_connection(lambda: ClientProtocol(loop), '127.0.0.1', port)

    transport, protocol = loop.run_until_complete(coro)

In addition, you need to ensure the strings you are writing are byte strings. String literals in Python 3 default to unicode. You can either encode these, or just write byte strings in the first place

    transport.write("some data".encode('utf-8'))
    transport.write(b"some data")

EDIT It's not clear to me why this is an issue, however the source for run_until_complete has this to say:

WARNING: It would be disastrous to call run_until_complete() with the same coroutine twice -- it would wrap it in two different Tasks and that can't be good.

I suppose creating a task and then passing in the coroutine (which causes a task to be created) has the same effect.

like image 95
Peter Gibson Avatar answered Sep 18 '22 17:09

Peter Gibson