Check if String is Valid UUID using Python

uuid library

The code snippet defines a function is_valid_uuid that takes in a single argument value. To check if the value is a valid UUID, the function attempts to create a uuid.UUID object. If the input string value represents a valid UUID, then the object is created successfully, and the is_valid_uuid function returns True. If the input string value is not a valid UUID, then the ValueError exception is raised. In this case, the is_valid_uuid function catches the exception using a try/except block and returns False.

The code then calls the is_valid_uuid function with the input UUID strings. In the first case, the input string is a valid UUID. In the second case, the input string is not a valid UUID because it contains a non-hexadecimal character (x).

import uuid


def is_valid_uuid(value):
    try:
        uuid.UUID(str(value))

        return True
    except ValueError:
        return False


isValid = is_valid_uuid('5338d5e4-6f3e-45fe-8af5-e2d96213b3f0')
print(isValid)  # True

isValid = is_valid_uuid('xx38d5e4-6f3e-45fe-8af5-e2d96213b3f0')
print(isValid)  # False

The 2 Comments Found

  1. Avatar
    Tyler Pruitt Reply

    If you convert your input to a string first, it will help save some headaches.

    uuid.UUID(str(value))

    • Avatar
      lindevs Reply

      Input can provided not only as a string. For example, input can be integer. I updated the code snippet. Great suggestion. Thanks, Tyler.

Leave a Comment

Cancel reply

Your email address will not be published.