This is a short & sweet UUID function. Uniqueness is based on network address, time, and random.
Another good point: does not create a "hot spot" when used in a b-tree (database) index. In other words, if your IDs look something like "abc100" and "abc101" and "abc102"; then they will all hit the same spot of a b-tree index, and cause the index to require frequent reorganization. On the other hand, if your IDs look more like "d29fa" and "67b2c" and "e5d36" (nothing alike); then they will spread out over the index, and your index will require infrequent reorganization.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
import time, random, md5 def uuid( *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 = md5.md5(data).hexdigest() return data
Down side: Not especially fast. I would integrate a similar C or java version of this (without the MD5) into my python code if this is a problem.