Welcome to this tutorial on different ways of generating UUID (Universally Unique Identifier) in Python. UUIDs are commonly used to uniquely identify resources or entities in various systems. In this tutorial, we will explore several methods to generate UUIDs in Python, along with examples for each method.
UUID1 generates a UUID based on the current time and the MAC address of the host system. This method guarantees uniqueness across different systems unless the MAC address is changed.
import uuid uuid_obj = uuid.uuid1() print(f"Generated UUID1: {uuid_obj}")
UUID3 generates a UUID based on a given namespace and name using the MD5 hash algorithm.
import uuid namespace_uuid = uuid.UUID('00000000-0000-0000-0000-000000000000') name = 'example' uuid_obj = uuid.uuid3(namespace_uuid, name) print(f"Generated UUID3: {uuid_obj}")
UUID4 generates a random UUID using a cryptographically secure random number generator.
import uuid uuid_obj = uuid.uuid4() print(f"Generated UUID4: {uuid_obj}")
UUID5 generates a UUID based on a given namespace and name using the SHA-1 hash algorithm.
import uuid namespace_uuid = uuid.UUID('00000000-0000-0000-0000-000000000000') name = 'example' uuid_obj = uuid.uuid5(namespace_uuid, name) print(f"Generated UUID5: {uuid_obj}")
In this tutorial, we explored four different methods to generate UUIDs in Python. We covered UUID1, which generates a time-based UUID, UUID3 and UUID5, which generate name-based UUIDs using MD5 and SHA-1 algorithms respectively, and UUID4, which generates a random UUID. You can choose the appropriate method based on your use case and requirements.