Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent to get() in python? [duplicate]

I have a sequence of messages in json and they include a field called part, which is an integer from 0 to 2. I have three message queues and the value of part determines which queue I send the message over to.

This is my current code.

output0 = queue.Queue()
output1 = queue.Queue()
output2 = queue.Queue()

json = json.loads('{"test": "message", "part": "2"}')
part = int(json["part"])

if part == 0:
    output0.put(json)

elif part == 1:
    output1.put(json)

elif part == 2:
    output2.put(json)

I'd like to simplify it with something like.

chooseQueue = "output" + str(json["part"])
chooseQueue.put(json)

It serves me this error AttributeError: 'str' object has no attribute 'put'

In R, I can use a string as a variable name by using as.formula() or get().

like image 586
tadon11Aaa Avatar asked Mar 22 '26 06:03

tadon11Aaa


2 Answers

The answer to your question is locals().

The answer to you problem is a dict

queue_dict = {'1': queue.Queue(), '2': queue.Queue(), '3': queue.Queue()}
queue = queue_dict[json["part"]]
like image 64
Yassine Faris Avatar answered Mar 23 '26 20:03

Yassine Faris


You can, but you'd be much better off keeping your queues in a dict:

queues = {"output0": queue.Queue(),
          "output1": queue.Queue(),
          "output2": queue.Queue(),
         }
chooseQueue = "output" + str(json["part"])
queues[chooseQueue].put(json)
like image 45
brunns Avatar answered Mar 23 '26 19:03

brunns