0

Basing on: How do you create different variable names while in a loop?

I created my nameCreator() function, that within call two other functions. I would like to ask you, what may cause that it doesn't work as I want it.

after printing nameDict is see only {} as result. So as I suppose, the variables aren't even created.

def nameCreator(number):
    nameDict={}
    for x in range(number):
        nameDict["socketMC{0}".format(x)] = socket_creator(arg1, arg2, "analysedSocket{}".format(x))
        nameDict["threadMC{0}".format(x)] = threading.Thread(target=MC_analysis, args=(arg1, arg2, nameDict["socketMC{}".format(x)]))
    print(nameDict)
    return nameDict

I would expect from function to iterate number times, where in each iteration loop creates 2 objects and at the end return nameDict that can be used somewhere else.

Example:

socketMC0, threadMC0
socketMC1, threadMC1

where socketMC{number} is a sock object and threadMC{number} is a thread. How can I achieve this?

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • 4
    how do you call the function? – Brown Bear Sep 05 '19 at 12:06
  • 4
    I don't see why the code you pasted here should fail - are you sure that `number` was not 0 when you called your function? The approach, though, is a bit strange. Are you going to do that `format(...)` thing everytime you want to access something in your dict? It would be simpler to use the number as key, and a dict with socket and thread as value, or simply a list... – Thierry Lathuille Sep 05 '19 at 12:08
  • 1
    Actually you were right about calling function with argument `0`. I had in my program this object and variable: `MCAST_GROUP = [239.0.1.104] number = len(MCAST_GROUP)-1`. I understood my mistake when I added another multicast group to my list, where after calling `nameCreator` it indeedly went once through iteration. I misunderstood fact that in the `for x in range(number):` im not providing index but number of how many `forloop` will be executed. thanks for help :) –  Sep 05 '19 at 12:23

0 Answers0