How to create a GUID/UUID in Python

Posted on

Question :

How to create a GUID/UUID in Python

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?

Answer #1:

The uuid module provides RFC compliant UUID
generation. See the module docs and the RFC for details. [source]


Example (working on 2 and 3):

>>> import uuid
>>> uuid.uuid4()
>>> str(uuid.uuid4())
>>> uuid.uuid4().hex
Answered By: stuartd

Answer #2:

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


>>> import uuid
>>> uuid.uuid4()
Answered By: Jay

Answer #3:

Copied from : (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()

>>> # make a UUID using an MD5 hash of a namespace UUID and a name
>>> uuid.uuid3(uuid.NAMESPACE_DNS, '')

>>> # make a random UUID
>>> uuid.uuid4()

>>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
>>> uuid.uuid5(uuid.NAMESPACE_DNS, '')

>>> # 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)

>>> # get the raw 16 bytes of the UUID
>>> x.bytes

>>> # make a UUID from a 16-byte string
>>> uuid.UUID(bytes=x.bytes)

Answer #4:

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('=', '')
Answered By: Chris Dutrow

Answer #5:

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

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

import uuid

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

import uuid    
Answered By: Mobasshir Bhuiyan

Answer #6:

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

from typing import Optional
import re
import subprocess
import uuid

def get_windows_uuid() -> Optional[uuid.UUID]:
        # 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 ="bUUIDb[srn]+([^srn]+)", txt)
        if match is not None:
            txt =
            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)
        pass # Silence subprocess exception.

    return None


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 ( 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.

Answered By: Mitch McMabers

Answer #7:

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


 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
Answered By: Manoj Selvin

Answer #8:

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.

Answered By: QtRoS

Leave a Reply

Your email address will not be published. Required fields are marked *