How To Generate A Human Friendly Unique Id In Python?
Solution 1:
For emails, what I use is:
from base64 import b64encode
from os import urandom
key = b64encode(urandom(9))
You can increase/decrease the length by changing the number. Sometimes you will get + and / characters and you can strip them out if you like.
Edit:
Since you also want to pass them over the phone maybe b32encode(urandom(5))
would be a better choice since it wont give you any lowercase or unusual characters.
Solution 2:
How about something like Amazon's payphrases? Convert the binary ID to a sequence of english words.
If you want something with the same range as a UUID, you need to represent 16 bytes. To keep it reasonable, restrict the phrase to 4 words, so each word represents 4 bytes, or 65536 possibilities, so you'll need a dictionary of 262,144 words.
EDIT: Actually on reflection what might be better is a sort of mad lib sentence - it will restrict the number of needed words and may make it easier to remember since it has a grammatical structure. It will need to be longer, of course, perhaps something like this:
(a/an/the/#) (adj) (noun) (verb)(tense) (adverb) while (a/an/the/#) (adj) (noun) (verb) (adverb).
Solution 3:
Sure, but it requires a few more restrictions on your problem space, namely:
- There is only one thing generating unique IDs
- Your items have some concept of a title
- You can persist a list of strings
Then you'd do something like:
_UID_INTERNALS =set()
def getID(obj):
if hasattr(obj, 'UID'):
return obj.UID
title = obj.title.encode("ascii", errors="ignore")
title = title.lower()
title ="-".join(title.split())
if not title:
title ="unnamed-object"UID= title
num =1whileUIDin _UID_INTERNALS:
UID= title + str(num)
num +=1
_UID_INTERNALS.add(UID)
obj.UID=UIDreturnUID
Solution 4:
Here's a uuid-based example. Adjust the 1000000 to increase or decrease the range of your ids. Since you're reducing the range of the id, you'll probably have to check to see if the ID already exists.
>>>import uuid>>>hash(str(uuid.uuid1())) % 1000000
380539
>>>hash(str(uuid.uuid1())) % 1000000
411563
Post a Comment for "How To Generate A Human Friendly Unique Id In Python?"