There are multiple queue implementations, but the difference between queue.Queue
and collections.deque
became a problem.
Originally written using deque
, rewritten using Queue
Original code
from collections import deque
queue = deque()
queue.append("hogehoge")
while queue:
item = queue.popleft()
if n := len(item) == 1:
print(item)
else:
queue.append(item[:n//2])
queue.append(item[n//2:])
Rewritten code
from queue import Queue
queue = Queue()
queue.put("hogehoge")
while queue:
item = queue.get()
if n := len(item) == 1:
print(item)
else:
queue.put(item[:n//2])
queue.put(item[n//2:])
Executing the code below in this state resulted in an infinite loop.
Queue
is judged to be True
even if it is emptyAlthough there is no direct description in https://docs.python.org/ja/3/library/queue.html, it was output as such in REPL.
REPL
from queue import Queue
q = Queue()
bool(q)
> True
q.put("hoge")
bool(q)
> True
Apparently there is Queue.empty ()
, so I tried to rewrite it using it, but the infinite loop was not resolved.
Queue.empty()Code rewritten using
from queue import Queue
queue = Queue()
queue.put("hogehoge")
while not queue.empty():
item = queue.get()
if n := len(item) == 1:
print(item)
else:
queue.put(item[:n//2])
queue.put(item[n//2:])
Recommended Posts