Note that there are some explanatory texts on larger screens.

plurals
  1. POPython: Queue.Empty Exception Handling
    primarykey
    data
    text
    <p>After a short debate with someone about exception handling in Python - sparked by the handling of a queue object - I thought I'd throw it out there...</p> <h1>METHOD 1:</h1> <pre><code>import Queue q = Queue.Queue() try: task=q.get(False) #Opt 1: Handle task here and call q.task_done() except Queue.Empty: #Handle empty queue here pass #Opt2: Handle task here and call q.task_done() </code></pre> <h1>METHOD 2:</h1> <pre><code>import Queue q = Queue.Queue() if q.empty(): #Handle empty queue here else: task = q.get() #Handle task here q.task_done() </code></pre> <p>One argument is that Method 1 is wrong because the queue being empty is not an error, and therefore should not be handled using Queue.Empty exception. Additionally, it could make debugging more difficult when coded this way if you consider that the task handling part could potentially large.</p> <p>The other argument is that either way is acceptable in Python and that handling the task outside of the try/except could aid debugging if task handling is large, although agreed that this might look uglier than using Method 2. </p> <p>Opinions?</p> <p>UPDATE: A little more info after answer 1 came through.... The debate was started after method 1 was using in some multithreaded code. In which case, the code will acquire the lock (from a threading.Lock object) and release it either once the task it returned or Queue.Empty is thrown</p> <p>UPDATE 2: It was unknown to both of us that the the queue object was thread safe. Looks like try/except is the way to go!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload