pythonvariablestask-queue

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


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?


Solution

  • Yes, use a tuple:

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

    It will be automatically unpacked.