How can I put and get a set of multiple items in a queue?

user1447941 picture user1447941 · Oct 19, 2012 · Viewed 10.1k times · Source

Worker:

def worker():
    while True:
        fruit, colour = q.get()
        print 'A ' + fruit + ' is ' + colour
        q.task_done()

Putting items into queue:

fruit = 'banana'
colour = 'yellow'
q.put(fruit, colour)

Output:

>>> A banana is yellow

How would I be able to achieve this? I tried it and got ValueError: too many values to unpack, only then I realized that my q.put() put both of the variables into the queue.

Is there any way to put a "set" of variables/objects into one single queue item, like I tried to do?

Answer

dav1d picture dav1d · Oct 19, 2012

Yes, use a tuple:

fruit = 'banana'
colour = 'yellow'
q.put((fruit, colour))

It should be automatically unpacked (should, because I can't try it atm).