How do I create a GUID in Python that is platform independent? I hear there is a method using ActivePython on Windows but it's Windows only because it uses COM. Is there a method using plain Python?
"The uuid module, in Python 2.5 and up, provides RFC compliant UUID generation. See the module docs and the RFC for details."
http://mail.python.org/pipermail/python-list/2007-November/1106916.html
If you're using Python 2.5 or later, the uuid module is already included with the Python standard distribution.
Ex:
>>> import uuid
>>> uuid.uuid1()
UUID('5a35a426-f7ce-11dd-abd2-0017f227cfc7')
Pre python 2.5 you could use something like this:
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
If all you want is a number that's extremely unlikely to be repeated, just concatenate the date, time (with microseconds) and a number from random.SystemRandom. The chances that another item was created at the exact same microsecond of the exact same day as yours is low. Add a nice long random number generated at that time, and you have some good uniqueness, imho. But, I'm no expert on randomness. I'd be interested in feedback from someone who is an expert.