1

Why asyncio Queue is behaving so weirdly here, even though putting an item there it is showing empty?

In [1]: from multiprocessing import Queue

In [2]: q = Queue()

In [3]: q.empty()
Out[3]: True

In [4]: q.put(100)

In [5]: q.empty()
Out[5]: False

In [6]: from asyncio import Queue

In [7]: q = Queue()

In [8]: q.empty()
Out[8]: True

In [9]: q.put(100)
Out[9]: <generator object Queue.put at 0x7f97849bafc0>

In [10]: q.empty()
Out[10]: True

2 Answers 2

4

Because you didn't put anything:

q.put(100)

put here - is not a plain function, it's a coroutine. You should await it to put item in queue.

For example:

import asyncio
from asyncio import Queue


async def main():
    q = Queue()

    print(q.empty())  # True

    await q.put(100)

    print(q.empty())  # False


if __name__ ==  '__main__':
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(main())
    finally:
        loop.run_until_complete(loop.shutdown_asyncgens())
        loop.close()
Sign up to request clarification or add additional context in comments.

Comments

1

As Mikhail Gerasimov's answer, q.put(100) is a coroutine and explaining more detail...

Calling a coroutine does not start its code running – the coroutine object returned by the call doesn’t do anything until you schedule its execution. There are two basic ways to start it running: call await coroutine or yield from coroutine from another coroutine (assuming the other coroutine is already running!), or schedule its execution using the ensure_future() function or the AbstractEventLoop.create_task() method.

Coroutines (and tasks) can only run when the event loop is running.

It is from Python Coroutines doc.

In the Mikhail Gerasimov's example, Another coroutine async def main() calls await with coroutine q.put(100) and event loop is running loop.run_until_complete(main()) such as the above description.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.