Queue: Which form is better/more Pythonic?

Alex Martelli aleax at aleax.it
Sat Feb 22 12:53:15 EST 2003


Jeff Hinrichs wrote:

> 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

The queue COULD be empty just because the producer isn't finished
producing yet, and that's a risk you run with either approach (also,
get_nowait used like this will produce a busy loop chewing up your
CPU).  I suggest that you should rather have the producer post to
the queue a special message conventionally meaning "OK, I'm done!"
and that you break out of your "while 1:" loop when you meet it: this
is FAR more reliable.  Also, use get, not get_nowait, for performance.

> missing a non-empty queue.  Am I a worrying too much?

No, just, I suspect, worrying about the wrong things.


Alex





More information about the Python-list mailing list