Queue: Which form is better/more Pythonic?
Jeff Hinrichs
jlh at cox.net
Sat Feb 22 12:36:55 EST 2003
Is it better to break out of an infinite loop when the queue is empty
while 1:
try:
msg=qMsg.get_nowait()
...do something with msg...
except Queue.Empty:
break
or to loop against the .empty()
while not qMsg.empty():
try:
msg=qMsg.get_nowait()
...do something with msg...
except Queue.Empty:
pass
The docs say that .empty() is not reliable and I want to make sure that I
pass all messages from the producer to a consumer. Although my limited
testing with "while not qMsg.empty()" did not display a problem, the "not
reliable" phrase from the docs made me anxious about using it as a looping
control so I switched to the infinite loop with a break. I've googled and
seen both methods used but no discussion if one is "better" than the other.
The second I consider more readable but the first makes me worry less about
missing a non-empty queue. Am I a worrying too much?
-Jeff Hinrichs
More information about the Python-list
mailing list