Mark
Mark

Reputation: 6484

Does standard library support generating unique IDs?

Assuming I have the following sequences:

A-B-C-D
A-C-C-E
B-B-B-D
A-A-E-D
...

I need to assign unique numerical IDs to every element, e.g. A=0, B=1 and so on and work with those IDs. At the moment I generate ID with the following function:

    id = -1
    ids = dict()

    def getid():
        global id
        id += 1
        return id

    def genid(s):
        global id
        if not s in ids:
            ids[s] = getid()

        return ids[s]

I'm beginner, so it may not be the perfect solution, but it works. However, I worry that it will be very slow/inefficient for large number of.sequences and elements (imagine instead of A, B etc. it has combination of letters ABCD, XYZ and so on). I believe Python has mechanisms to achieve this in a more compact way. May be collections library has something that can achieve this in 1-2 lines?

Upvotes: 0

Views: 104

Answers (2)

EliadL
EliadL

Reputation: 7088

You can avoid global altogether, and as suggested use count:

from itertools import count

id_counter = count()
ids = dict()

def getid():
    return next(id_counter)

def genid(s):
    if s not in ids:
        ids[s] = getid()
    return ids[s]

You could use some "python magic" to make it shorter:

from itertools import count

def genid(s, id_counter=count(), ids={}):
    if s not in ids:
        ids[s] = next(id_counter)
    return ids[s]

Upvotes: 0

Axe319
Axe319

Reputation: 4365

uuid will generate a unique random id which can be represented as an int, bytes, or hex.

Just import uuid and then use uuid.uuid1().bytes or uuid.uuid1().int or uuid.uuid1().hex to get your id.

Upvotes: 1

Related Questions