How can I generate a unique ID in Python? [duplicate]
I need to generate a unique ID based on a random value.
Perhaps uuid.uuid4()
might do the job. See uuid for more information.
You might want Python's UUID functions:
21.15. uuid — UUID objects according to RFC 4122
eg:
import uuid
print uuid.uuid4()
7d529dd4-548b-4258-aa8e-23e34dc8d43d
unique and random are mutually exclusive. perhaps you want this?
import random
def uniqueid():
seed = random.getrandbits(32)
while True:
yield seed
seed += 1
Usage:
unique_sequence = uniqueid()
id1 = next(unique_sequence)
id2 = next(unique_sequence)
id3 = next(unique_sequence)
ids = list(itertools.islice(unique_sequence, 1000))
no two returned id is the same (Unique) and this is based on a randomized seed value
Maybe this work for u
str(uuid.uuid4().fields[-1])[:5]
import time
import random
import socket
import hashlib
def guid( *args ):
"""
Generates a universally unique ID.
Any arguments only create more randomness.
"""
t = long( time.time() * 1000 )
r = long( random.random()*100000000000000000L )
try:
a = socket.gethostbyname( socket.gethostname() )
except:
# if we can't get a network address, just imagine one
a = random.random()*100000000000000000L
data = str(t)+' '+str(r)+' '+str(a)+' '+str(args)
data = hashlib.md5(data).hexdigest()
return data