0

I have this function in python that reads in a dict and is supposed to loop a number of times then give my a set of unique ids into a dict.

import uuid
import time

def generate_cluster_group(template: dict, number: int):
    for i in range(number):
        time.sleep(1)
        if i == 0:
            instance = template
            id_ = uuid.uuid4()
            instance['id'] = str(id_)
            virtualInstances = [template]
        else:
            ninstance = template
            id_ = uuid.uuid4()
            ninstance['id'] = str(id_)
            virtualInstances.append(ninstance)
            
    return virtualInstances
sample_template = {'id': 'none'}

result = generate_cluster_group(sample_template, 3)

### desired result
result = [{'id': 'fe918527-5f27-4333-a8ec-887d755a4002'},
          {'id': '8b97fc31-2e01-4949-8eca-954583f4b8fe'},
          {'id': '5fb021e8-d15d-453c-a8c0-9327e7c88634'}]

but I end up with the same id duplicated

actual_result = [{'id': 'fe918527-5f27-4333-a8ec-887d755a4002'},
          {'id': 'fe918527-5f27-4333-a8ec-887d755a4002'},
          {'id': 'fe918527-5f27-4333-a8ec-887d755a4002'}]

am I misunderstanding how the uuid function works?

KillerSnail
  • 3,321
  • 11
  • 46
  • 64

1 Answers1

0

You are making several mistakes in your function. It could be simplified to this:

def generate_cluster_group(template: dict, number: int):
    virtualInstances = []
    for _ in range(number):
        time.sleep(1)
        ninstance = dict(template)
        ninstance['id'] = str(uuid.uuid4())
        virtualInstances.append(ninstance)
            
    return virtualInstances
quamrana
  • 37,849
  • 12
  • 53
  • 71