Steps to Check UUID Validity in Python
Let us see each step one by one for a better understanding on how to check Uuid validity in Python.
Import Module
In Python, the uuid module provides tools for generating and handling UUIDs.
import uuid
Validate the UUID
To validate Uuid, we use UUID() function of uuid module, which takes two arguments, the uuid to check and the version type.
This function will attempt to create a UUID object from a string. If the string is not a valid UUID, a ValueError is raised, and the function returns False. If no exception is raised, the function checks if the string representation of the UUID object matches the original string. This ensures that the format is correct.
uuid_obj = uuid.UUID(uuid_to_test, version)
Example: In this example, we create a function that takes the Uuid to be tested and the version number of the Uuid. Then inside a try except block we check for the Uuid validity using the UUID() function.
# import uuid module
import uuid
def is_valid_uuid(uuid_to_test, version=4):
try:
# check for validity of Uuid
uuid_obj = uuid.UUID(uuid_to_test, version=version)
except ValueError:
return "Invalid Uuid"
return "Valid Uuid"
test_uuid = '550e8400-e29b-41d4-a716-446655440000'
print(is_valid_uuid(test_uuid))
invalid_uuid = '550e8400-e29b-41d4-a716-44665544000Z'
print(is_valid_uuid(invalid_uuid))
Output:
Valid Uuid
Invalid Uuid
How To Check Uuid Validity In Python?
UUID (Universally Unique Identifier) is a 128-bit label used for information in computer systems. UUIDs are widely used in various applications and systems to uniquely identify information without requiring a central authority to manage the identifiers.
This article will guide you through checking the validity of a UUID in Python.