Python iterable Queue

前端 未结 2 1760
感情败类
感情败类 2021-02-14 12:21

I need to know when a Queue is closed and wont have more items so I can end the iteration.

I did it by putting a sentinel in the queue:

from Queue import         


        
2条回答
  •  我寻月下人不归
    2021-02-14 12:29

    A sentinel is a reasonable way for a producer to send a message that no more queue tasks are forthcoming.

    FWIW, your code can be simplified quite a bit with the two argument form of iter():

    from Queue import Queue
    
    class IterableQueue(Queue): 
    
        _sentinel = object()
    
        def __iter__(self):
            return iter(self.get, self._sentinel)
    
        def close(self):
            self.put(self._sentinel)
    

提交回复
热议问题