My Queue usage typically involves a producer thread and a consumer thread. The producer calls queue.put(value) until it's done at which point it calls queue.put(sentinel). My consumers almost always look like this:
while True: value = queue.get() if value != sentinel: # do something with value else: break
That logic can be abstracted away into a generator function that allows consumer code to look like this instead:
for value in iterQueue(queue, sentinel): # do something with value
1 2 3 4 5 6 7 8
def iterQueue(queue, sentinel): """Iterate over the values in queue until sentinel is reached.""" while True: value = queue.get() if value != sentinel: yield value else: return
Generators functions provide a powerful tool for abstracting looping logic into separate functions. This can make code much easier to read.
This is built in (but fairly obscure!). You don't need this - the built in iter() function allows you to do this:
Until I saw this recipe, I'd forgotten about it, though!
Cool! I want to pass arguments to Queue.get as well, so I added:
Now I can
to my heart's desire :-)