pythonpython-3.xuniqueidentifier

Shortest possible generated unique ID


So we can generate a unique id with str(uuid.uuid4()), which is 36 characters long.

Is there another method to generate a unique ID which is shorter in terms of characters?

EDIT:


Solution

  • If this is for use as a primary key field in db, consider just using auto-incrementing integer instead.

    str(uuid.uuid4()) is 36 chars but it has four useless dashes (-) in it, and it's limited to 0-9 a-f.

    Better uuid4 in 32 chars:

    >>> uuid.uuid4().hex
    'b327fc1b6a2343e48af311343fc3f5a8'
    

    Or just b64 encode and slice some urandom bytes (up to you to guarantee uniqueness):

    >>> base64.b64encode(os.urandom(32))[:8]
    b'iR4hZqs9'