uuid

What is UUID

UUID is a Universally Unique Identifier. You can also call it as GUID, i.e., Globally Unique Identifier.

A UUID is 128 bits long number or ID to uniquely identify the documents, Users, resources or information in computer systems.

  • UUID can guarantee the uniqueness of Identifiers across space and time. when we talk about space and time means when UUID generated according to the standard then the identifier does not duplicate one that has already been created or will be created to identify something else.

Python UUID module implemented as per RFC 4122. RFC 4122 is a standard and Copyright (C) of The Internet Society. RFC 4122 specification includes all the details and algorithms to generate the Unique Identifiers of all the versions. RFC 4122 document specifies three algorithms to generate UUIDs.

Hence using Python UUID module, you can generate versions 1, 3, 4, and 5 UUIDs. UUID generated using this module is immutable.

Python UUID module supports the following versions of UUIDs.

  • UUID1 – Generate UUID using a Host MAC address, sequence number and the current time. This version uses the IEEE 802 MAC addresses.
  • UUID3 and UUID 5 uses cryptographic hashing and application-provided text strings to generate UUID. UUID 3 uses MD5 hashing, and UUID 5 uses SHA-1 hashing.
  • UUID4 uses pseudo-random number generators to generate UUID.

Structure of UUID

As you can see in the output UUID is made up of five components, and each component has a fixed length. A hyphen symbol separates each component. UUID’s presented in the format “8-4-4-4-12”.

UUID 1 to Generate a unique ID using MAC Address

The uuid.uuid1() function is used to generate a UUID from the host ID, sequence number, and the current time. It uses the MAC address of a host as a source of uniqueness.

import uuid

# make a UUID based on the host address and current time
uuidOne = uuid.uuid1()
print(uuidOne)

# f8adce75-04f3-11ed-9cc3-0456e5e23db1

UUID 4 to generate a random UUID

The UUID generated using a uuid4() function is created using a truly Random or Pseudo-Random generator.

import uuid

uuidFour = uuid.uuid4()
print(uuidFour)

UUID 3 and UUID 5 to Create a Name-Based UUID

Version 3 or 5 UUID meant for generating UUIDs from “names.” we can use name and namespace to create a series of unique UUIDs. In simple words version, 3 and  5 UUIDs is nothing but hashing namespace identifier with a name.

The uuid.uuid3(namespace, name) generate a UUID based on the MD5 hash of a namespace identifier (which is a UUID) and a string.

Similarly, the uuid.uuid5(namespace, name) generate a UUID based on the SHA-1 hashing technique of a namespace identifier (which is a UUID) and a name.

The UUID module defines the following namespace identifiers to use with uuid3() or uuid5().

  • UUID.NAMESPACE_DNS means a fully qualified domain name. For example, https://pynative.com.
  • UUID.NAMESPACE_URL When this namespace is specified, It means it is a URL.
  • UUID.NAMESPACE_OID When this namespace is specified, the name string is an ISO OID.
  • UUID.NAMESPACE_X500 When this namespace is specified, the name string is an X.500 DN in DER or a text output format.
import uuid

hostNames = ['pynative.com', 'phaisarn.com']

for host in hostNames:
    print(uuid.uuid3(uuid.NAMESPACE_DNS, host))
    print(uuid.uuid5(uuid.NAMESPACE_DNS, host))
    print()

Extract UUID attributes read-only attributes

The internal representation of a UUID is a specific sequence of bits in memory, as described in RFC4211. It is necessary to convert the bit sequence to a string representation to represent UUID in string format.

UUID module provides the various read-only argument to access the value of each component of the UUID object. You can extract the values from UUID so we can use this value for a different purpose. For example, You want to Extract the time from a UUID version1 in python.

import uuid

UUID = uuid.uuid1()

print("UUID is ", UUID)
print("UUID Type is   ",type(UUID))
print('UUID.bytes    :', UUID.bytes)
print('UUID.bytes_le :', UUID.bytes_le)
print('UUID.hex      :', UUID.hex)
print('UUID.int      :', UUID.int)
print('UUID.urn      :', UUID.urn)
print('UUID.variant  :', UUID.variant)
print('UUID.version  :', UUID.version)
print('UUID.fields   :', UUID.fields)
print("Prining each field seperately")
print('UUID.time_low            : ', UUID.time_low)
print('UUID.time_mid            : ', UUID.time_mid)
print('UUID.time_hi_version     : ', UUID.time_hi_version)
print('UUID.clock_seq_hi_variant: ', UUID.clock_seq_hi_variant)
print('UUID.clock_seq_low       : ', UUID.clock_seq_low)
print('UUID.node                : ', UUID.node)
print('UUID.time                : ', UUID.time)
print('UUID.clock_seq           : ', UUID.clock_seq)
print('UUID.SafeUUID            : ', UUID.is_safe)

UUID to String and String to UUID in Python

When we call a uuid.uuid1 or any other version of UUID you will get an instance of UUID class. When we want UUID in string format for comparison, manipulation or maybe for any reason we can get its string representation using a str class. Let see how do change a UUID to a string.

create string from uuid

import uuid

UUID1 = uuid.uuid1()
print(type(UUID1))
print(UUID1)
print(type(str(UUID1)))
print(str(UUID1))
print(str(UUID1).replace("-", "")) # remove dash

create uuid from string

import uuid

uuid_str = ["{55da37d1-d481-11e8-9013-adaf456d94a0}",
            "018c168c-d509-11e8-b096-ccaf789d94a0",
            "urn:uuid:e5e9394c-daed-498e-b9f3-69228b44fbfa"]

for string in uuid_str:
    # make a UUID from a string of hex digits
    # (braces and hyphens ignored)
    myUUID = uuid.UUID(string)
    print("UUID is", myUUID)
    print("UUID time component is", myUUID.time)
    print()