How to create a GUID/UUID in Python
Asked Answered
B

8

1246

How do I create a GUID/UUID 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?

Beore answered 10/2, 2009 at 23:51 Comment(6)
docs.activestate.com/activepython/2.6/python/library/uuid.htmlThevenot
For the love of all that is sacred, it's a UUID - Universal Unique ID en.wikipedia.org/wiki/Universally_unique_identifier - its just that unfortunately MS has preferrred GUID.Conglomerate
Here's one liner for you: python -c 'import uuid; print(uuid.uuid4())'Seeing
I think GUID makes more sense than UUID, as <i>global</i> means global within some namespace, while <i>universal</i> seems to claim true universal uniqueness. In any event we all know what we're talking about here.Blandish
what is a guid and a uuid? why not create a unique hash id e.g. #22974999Sinaloa
It is the same thing, people. The RFC 4122 even says UUID is also known as GUID. GUID is easier and more fun to say. ;-)Tess
P
1529

The uuid module provides immutable UUID objects (the UUID class) and the functions uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5 UUIDs as specified in RFC 4122.

If all you want is a unique ID, you should probably call uuid1() or uuid4().

Note that uuid1() may compromise privacy since it creates a UUID containing the computer’s network address.

uuid4() creates a random UUID.

UUID versions 6 and 7 - new Universally Unique Identifier (UUID) formats for use in modern applications and databases (draft) rfc - are available from https://pypi.org/project/uuid6/

Docs:

Examples (for both Python 2 and 3):

>>> import uuid

>>> # make a random UUID
>>> uuid.uuid4()
UUID('bd65600d-8669-4903-8a14-af88203add38')

>>> # Convert a UUID to a string of hex digits in standard form
>>> str(uuid.uuid4())
'f50ec0b7-f960-400d-91f0-c42a6d44e3d0'

>>> # Convert a UUID to a 32-character hexadecimal string
>>> uuid.uuid4().hex
'9fe2c4e93f654fdbb24c02b15259716c'
Palaeontography answered 10/2, 2009 at 23:54 Comment(8)
Also, have a look at the shortuuid module I wrote, as it allows you to generate shorter, readable UUIDs: github.com/stochastic-technologies/shortuuidLinkous
@StavrosKorokithakis: have you written shortuuid module for Python 3.x by any chance?Risarise
@JayPatel Does shortuuid not work for Python 3? If not, please file a bug.Linkous
What's the difference between uuid4().hex and str(uuid4())?Oast
Well, as you can see above, str(uuid4()) returns a string representation of the UUID with the dashes included, while uuid4().hex returns "The UUID as a 32-character hexadecimal string"Palaeontography
@Palaeontography Why do you recommend using uuid4 rather than uuid5 "if all you want is a unique ID"? And is there anything speaking against uuid7 or uuid6 in this regard?Christine
@Christine that advice is quoted from the documentationPalaeontography
For anyone else interested: from what I could gather empirically, the reason they recommend uuid4 for "just a unique ID" is that it requires no parameters, contrary to most other versions.Christine
R
371

If you're using Python 2.5 or later, the uuid module is already included with the Python standard distribution.

Ex:

>>> import uuid
>>> uuid.uuid4()
UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14')
Roundfaced answered 10/2, 2009 at 23:55 Comment(0)
S
31

I use GUIDs as random keys for database type operations.

The hexadecimal form, with the dashes and extra characters seem unnecessarily long to me. But I also like that strings representing hexadecimal numbers are very safe in that they do not contain characters that can cause problems in some situations such as '+','=', etc..

Instead of hexadecimal, I use a url-safe base64 string. The following does not conform to any UUID/GUID spec though (other than having the required amount of randomness).

import base64
import uuid

# get a UUID - URL safe, Base64
def get_a_uuid():
    r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)
    return r_uuid.replace('=', '')
Sabayon answered 11/6, 2012 at 16:47 Comment(3)
If you're not going to bother using it in any UUID contexts, you may as well just use random.getrandbits(128).to_bytes(16, 'little') or (for crypto randomness) os.urandom(16) and get a full 128 bits of random (UUIDv4 uses 6-7 bits on version info). Or use only 15 bytes (losing 1-2 bits of random vs. UUIDv4) and avoid the need to trim off = signs while also reducing the encoded size to 20 bytes (from 24, trimmed to 22), as any multiple of 3 bytes encodes to #bytes / 3 * 4 base64 characters with no padding required.Wershba
@Wershba Yeah thats basically the idea. 128 random bits, as short as conveniently possible, while also being URL safe. Ideally it would only use upper and lower case letters and then numbers. So I guess a base-62 string.Sabayon
When i use your function i get a type error from the return statement expecting a bytes-like object. It can be fixed with return str(r_uuid).replace('=','').Ossy
O
15

If you need to pass UUID for a primary key for your model or unique field then below code returns the UUID object -

 import uuid
 uuid.uuid4()

If you need to pass UUID as a parameter for URL you can do like below code -

import uuid
str(uuid.uuid4())

If you want the hex value for a UUID you can do the below one -

import uuid    
uuid.uuid4().hex
Outturn answered 25/6, 2019 at 8:38 Comment(0)
S
5

If you are making a website or app where you need to every time a unique id. It should be a string a number then UUID is a great package in python which is helping to create a unique id.

**pip install uuid**

import uuid

def get_uuid_id():
    return str(uuid.uuid4())

print(get_uuid_id()) 

OUTPUT example: 89e5b891-cf2c-4396-8d1c-49be7f2ee02d

Sulphur answered 28/4, 2022 at 10:19 Comment(0)
D
1

2019 Answer (for Windows):

If you want a permanent UUID that identifies a machine uniquely on Windows, you can use this trick: (Copied from my answer at https://mcmap.net/q/46639/-get-a-unique-computer-id-in-python-on-windows-and-linux).

from typing import Optional
import re
import subprocess
import uuid

def get_windows_uuid() -> Optional[uuid.UUID]:
    try:
        # Ask Windows for the device's permanent UUID. Throws if command missing/fails.
        txt = subprocess.check_output("wmic csproduct get uuid").decode()

        # Attempt to extract the UUID from the command's result.
        match = re.search(r"\bUUID\b[\s\r\n]+([^\s\r\n]+)", txt)
        if match is not None:
            txt = match.group(1)
            if txt is not None:
                # Remove the surrounding whitespace (newlines, space, etc)
                # and useless dashes etc, by only keeping hex (0-9 A-F) chars.
                txt = re.sub(r"[^0-9A-Fa-f]+", "", txt)

                # Ensure we have exactly 32 characters (16 bytes).
                if len(txt) == 32:
                    return uuid.UUID(txt)
    except:
        pass # Silence subprocess exception.

    return None

print(get_windows_uuid())

Uses Windows API to get the computer's permanent UUID, then processes the string to ensure it's a valid UUID, and lastly returns a Python object (https://docs.python.org/3/library/uuid.html) which gives you convenient ways to use the data (such as 128-bit integer, hex string, etc).

Good luck!

PS: The subprocess call could probably be replaced with ctypes directly calling Windows kernel/DLLs. But for my purposes this function is all I need. It does strong validation and produces correct results.

Dextroglucose answered 16/10, 2019 at 15:37 Comment(0)
A
1

Run this command:

pip install uuid uuid6

And then run you can import uuid1, uuid3, uuid4 and uuid5 functions from the uuid package, and uuid6 and uuid7 functions from the uuid6 package.

An example output of calling each of these functions is as follows (except uuid3 and uuid5 which require parameters):

>>> import uuid, uuid6
>>> print(*(str(i()) for i in [uuid.uuid1, uuid.uuid4, uuid6.uuid6, uuid6.uuid7]), sep="\n")
646e934b-f20c-11ec-ad9f-54a1500ef01b
560e2227-c738-41d9-ad5a-bbed6a3bc273
1ecf20b6-46e9-634b-9e48-b2b9e6010c57
01818aa2-ec45-74e8-1f85-9d74e4846897
Audiophile answered 22/6, 2022 at 9:15 Comment(1)
The uuid module is already available in the stdlib, why does it require to be installed separately?Motorboat
C
-6

This function is fully configurable and generates unique uid based on the format specified

eg:- [8, 4, 4, 4, 12] , this is the format mentioned and it will generate the following uuid

LxoYNyXe-7hbQ-caJt-DSdU-PDAht56cMEWi

 import random as r

 def generate_uuid():
        random_string = ''
        random_str_seq = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        uuid_format = [8, 4, 4, 4, 12]
        for n in uuid_format:
            for i in range(0,n):
                random_string += str(random_str_seq[r.randint(0, len(random_str_seq) - 1)])
            if n != 12:
                random_string += '-'
        return random_string
Cordiacordial answered 24/2, 2018 at 17:11 Comment(5)
UUIDs are standard, and not variable in length. Generating a random string in a configurable way can be useful in some situations, but not in this context. You may check en.wikipedia.org/wiki/Universally_unique_identifier for definition.Pieria
Better avoid this one or you might run into compatibility issues (these are not standard GUIDs)Fork
Also, not even remotely guaranteed to be unique. It may be random, but not unique.Overarch
@Overarch No GUIDs are ever unique, simply so massive that a collision is extremely unlikely.Chaotic
GUID is a string representation of a very long number so 'LxoYNyXe...' does not cut in.Voice

© 2022 - 2024 — McMap. All rights reserved.