815

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?

dreftymac
  • 27,818
  • 25
  • 108
  • 169
Jonathon Watney
  • 15,080
  • 8
  • 34
  • 40
  • 3
    http://docs.activestate.com/activepython/2.6/python/library/uuid.html – Sridhar Ratnakumar Jan 20 '10 at 17:25
  • 49
    For the love of all that is sacred, it's a UUID - Universal Unique ID http://en.wikipedia.org/wiki/Universally_unique_identifier - its just that unfortunately MS has preferrred GUID. – david.barkhuizen Mar 16 '13 at 20:02
  • 8
    Here's one liner for you: `python -c 'import uuid; print(uuid.uuid4())'` – Ctrl-C Apr 24 '17 at 10:04
  • 2
    I think GUID makes more sense than UUID, as global means global within some namespace, while universal seems to claim true universal uniqueness. In any event we all know what we're talking about here. – duhaime Oct 28 '20 at 12:39

8 Answers8

964

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.

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'
stuartd
  • 62,136
  • 13
  • 120
  • 150
334

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')
jesterjunk
  • 2,074
  • 17
  • 17
Jay
  • 39,240
  • 14
  • 62
  • 82
131

Copied from : https://docs.python.org/2/library/uuid.html (Since the links posted were not active and they keep updating)

>>> import uuid

>>> # make a UUID based on the host ID and current time
>>> uuid.uuid1()
UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')

>>> # make a UUID using an MD5 hash of a namespace UUID and a name
>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

>>> # make a random UUID
>>> uuid.uuid4()
UUID('16fd2706-8baf-433b-82eb-8c7fada847da')

>>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')

>>> # make a UUID from a string of hex digits (braces and hyphens ignored)
>>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')

>>> # convert a UUID to a string of hex digits in standard form
>>> str(x)
'00010203-0405-0607-0809-0a0b0c0d0e0f'

>>> # get the raw 16 bytes of the UUID
>>> x.bytes
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'

>>> # make a UUID from a 16-byte string
>>> uuid.UUID(bytes=x.bytes)
UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')
29

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('=', '')
Chris Dutrow
  • 42,732
  • 59
  • 174
  • 243
  • 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. – ShadowRanger Jan 24 '19 at 02:26
  • @ShadowRanger 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. – Chris Dutrow Feb 15 '19 at 04:19
  • 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('=','')```. – Mark Kortink Feb 18 '20 at 02:41
10

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
0

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
Manoj Selvin
  • 1,422
  • 16
  • 15
  • 3
    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 https://en.wikipedia.org/wiki/Universally_unique_identifier for definition. – miguelr Jan 29 '19 at 02:12
  • 4
    Better avoid this one or you might run into compatibility issues (these are not standard GUIDs) – Sylvain Gantois Sep 10 '19 at 03:56
  • Also, not even remotely guaranteed to be unique. It may be random, but not unique. – regretoverflow Dec 14 '20 at 20:07
0

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://stackoverflow.com/a/58416992/8874388).

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.

Mitch McMabers
  • 1,446
  • 11
  • 16
-4

Check this post, helped me a lot. In short, the best option for me was:

import random 
import string 

# defining function for random 
# string id with parameter 
def ran_gen(size, chars=string.ascii_uppercase + string.digits): 
    return ''.join(random.choice(chars) for x in range(size)) 

# function call for random string 
# generation with size 8 and string  
print (ran_gen(8, "AEIOSUMA23")) 

Because I needed just 4-6 random characters instead of bulky GUID.

QtRoS
  • 1,017
  • 1
  • 16
  • 22