2

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().

tadon11Aaa
  • 400
  • 2
  • 11

4 Answers4

8

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"]]
Yassine Faris
  • 951
  • 6
  • 26
4

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)
brunns
  • 2,689
  • 1
  • 13
  • 24
1

You can use the locals() function to access variables in the local scope by name:

chooseQueue = locals()["output" + str(json["part"])]
John Gordon
  • 29,573
  • 7
  • 33
  • 58
1

Most of the answers tell you that you should use the built-in locals() function, and while they are right, I'd like to notify you of the globals() function which returns a dictionary of global variables, which you create using the global keyword.

For example, in a Python 3 terminal the globals() function returns:

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}

Good luck.

Malekai
  • 4,765
  • 5
  • 25
  • 60