SoFunction
Updated on 2025-03-04

Specific use of UUID built-in module in Python

1. Module introduction

uuidModule isPythonPart of the standard library, it provides a generic unique identification code (Universally Unique Identifier, abbreviationUUID) method,UUIDis an identifier standard whose purpose is to provide a globally unique identifier.

2. Module download

pip install uuid

3. Module import

import uuid

4. Module functions

.uuid1()

effectbased onMACAddress, timestamp, random number to generate uniqueuuid, can ensure uniqueness around the world.

grammar

uuid.uuid1(node=None, clock_seq=None)

parameter

  • node48integer of bits, used to represent the machineMACIf not provided, the default is to use the native one.MACaddress
  • clock_seq14bit integer, used in the same timestamp andMACAdditional randomness is provided at the address, if not provided, a randomly generated value is used by default.

Example

import uuid

# Generate a time-based UUIDuuid1 = uuid.uuid1()
print("UUID1:", uuid1)

# If you want to provide a specific MAC address and clock sequencecustom_node = 0x123456789ABC  # MAC address for examplecustom_clock_seq = 0x1234  # Clock sequence for example
custom_uuid1 = uuid.uuid1(node=custom_node, clock_seq=custom_clock_seq)
print("Custom UUID1:", custom_uuid1)

result

UUID1: f1667390-8dc0-11ef-ab64-fcb3bce2e1fe
Custom UUID1: f167111d-8dc0-11ef-9234-123456789abc

.uuid3()

effectBy calculating namespace and nameMD5Hash values ​​to generateUUID, can ensure the uniqueness of different names in the same namespace and the uniqueness of different namespaces, but the same name of the same namespace is generated byUUIDsame.

grammar

uuid.uuid3(namespace, name)

parameter

  • namespaceUUID, used for identification generationUUIDNamespace
  • name: String, indicating the name of the UUID to be generated

other1.uuidNamespace:UUIDNamespace is for the generation of versions3and version5 UUIDsa mechanism used when using. TheseUUIDsIt is calculated by hashing functions based on the namespace and a name (usually a string). NamespaceUUIDsIt's a predefined set ofUUIDs, They provide unique identifiers for different namespaces:

  • uuid.NAMESPACE_DNSDNSNamespace
  • uuid.NAMESPACE_URLURLNamespace
  • uuid.NAMESPACE_OIDISOObject identifier(OID) Namespace
  • uuid.NAMESPACE_X500X.500 DN(Catalog Name) Namespace

Example

import uuid

# Use DNS namespacenamespace = uuid.NAMESPACE_DNS
name = ''

# Generate a UUID based on namespace and nameuuid3 = uuid.uuid3(namespace, name)
print("UUID3:", uuid3)

result

UUID3: 6fa459ea-ee8a-3ca4-894e-db77e160355e

.uuid4()

effectGenerate version4 UUIDsfunction, version4 UUIDsThey are generated based on random numbers (or pseudo-random numbers), so they are extremely unique and suitable for situations where unique identifiers are required.

grammar

uuid.uuid4()

Example

import uuid

# Generate a version 4 UUIDrandom_uuid = uuid.uuid4()

print(f"Randomly generated UUID: {random_uuid}")

result

Randomly generated UUID: 5b38a29b-6a82-4d9b-812e-e030ad7afe4c

.uuid5()

effectGenerate version5 UUIDsfunction, version5 UUIDsis generated based on a namespace and a name, usingSHA-1Hash algorithm, which ensures that as long as the namespace and name are the same, the generatedUUIDIt will be the same.

grammar

uuid.uuid5(namespace, name)

parameter

  • namespaceUUID, used to identifyUUIDNamespace
  • name: String, representing a unique name in the namespace

Example

import uuid

# Define a namespace UUID (usually using a known UUID, such as a DNS or URL namespace)namespace = ('6ba7b810-9dad-11d1-80b4-00c04fd430c8')  # DNS namespacename = ''  # Name in namespace
# Generate a version 5 UUIDnamed_uuid = uuid.uuid5(namespace, name)

print(f"UUID for name '{name}' in namespace '{namespace}': {named_uuid}")

result

UUID for name '' in namespace '6ba7b810-9dad-11d1-80b4-00c04fd430c8': 886313e1-3b8a-5372-9b90-0c9aee199e5d

()

effectGet the hardware address of the current machine (usuallyMACaddress) and convert it into a node represented by an integer valueID

grammar

()

other

  • The return value is an integer representing the unique identifier of the current machine. This value is usually different on different machines unless multiple machines have the same hardware address.
  • It reads the machine's network interface card (NIC)ofMACAddress to generate nodeID, if the machine has multipleNICWhich one to useMACAddresses may vary by operating system and implementation.

Example

import uuid

node_id = ()
print(node_id)

result

277848898331134

()

effectGenerateUUID(Universally Unique Identifier, universal unique identification code).

grammar

(hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None)

parameter

  • hex:expressUUIDof32Hexadecimal string of characters
  • bytes16Byte string or sequence of bytes
  • bytes_le: in small-endian format (little-endian) means16Byte string or sequence of bytes
  • fields:IncludeUUIDTuples for each field
  • int:expressUUIDinteger
  • versionUUIDVersion number, if specified, it will verify that the input value meets the version

Example

import uuid

# Create a UUID from a hexadecimal stringuuid_from_hex = ('12345678-1234-5678-1234-567812345678')
print(f"UUID from hex: {uuid_from_hex}")

# Create a UUID from a byte sequenceuuid_from_bytes = (bytes=b'\x12\x34\x56\x78\x12\x34\x56\x78\x12\x34\x56\x78\x12\x34\x56\x78')
print(f"UUID from bytes: {uuid_from_bytes}")

# Create a UUID from an integeruuid_from_int = (int=0x12345678123456781234567812345678)
print(f"UUID from int: {uuid_from_int}")

# Create a UUID from a fielduuid_from_fields = (fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
print(f"UUID from fields: {uuid_from_fields}")

# Generate a new random UUIDrandom_uuid = uuid.uuid4()
print(f"Random UUID: {random_uuid}")

# Check UUID versionif random_uuid.version == 4:
    print("This is a random UUID.")

result

UUID from hex: 12345678-1234-5678-1234-567812345678
UUID from bytes: 12345678-1234-5678-1234-567812345678
UUID from int: 12345678-1234-5678-1234-567812345678
UUID from fields: 12345678-1234-5678-1234-567812345678
Random UUID: 2e9a79ae-cc0a-4eac-8e2a-102fa9237c57
This is a random UUID

This is the introduction to this article about the specific use of UUID in Python built-in module. For more related Python UUID content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!