How to randomly shuffle asyncio.Queue in Python?

Viewed 1571

When I want to randomly shuffle a list in Python, I do:

from random import shuffle
shuffle(mylist)

How would I do the equivalent to an instance of asyncio.Queue? Do I have to convert the queue to a list, shuffle the list, and then put them back on the Queue? Or is there a way to do it directly?

1 Answers

As you can see in Queue source code, items in Queue are actually stored in _queue attribute. It can be used to extend Queue through inheritance:

import asyncio
from random import shuffle


class MyQueue(asyncio.Queue):
    def shuffle(self):
        shuffle(self._queue)


async def main():
    queue = MyQueue()    
    await queue.put(1)
    await queue.put(2)
    await queue.put(3)

    queue.shuffle()

    while not queue.empty():
        item = await queue.get()
        print(item)


if __name__ == '__main__':
    asyncio.run(main())

If you want to shuffle existing Queue instance, you can do it directly:

queue = asyncio.Queue()
shuffle(queue._queue)

It's usually not a good solution for obvious reason, but on the other hand probability that Queue's implementation will change in future in a way to make it problem seems relatively low (to me at least).

Related