简体   繁体   中英

How to check UUID validity in Python?

I have a string that should be a UUID. Is there any built-in Python function available to check whether the UUID is valid or not, and to check its version?

I found this question while I was looking for a Python answer. To help people in the same situation, I've added the Python solution.

You can use the uuid module:

#!/usr/bin/env python

from uuid import UUID

def is_valid_uuid(uuid_to_test, version=4):
    """
    Check if uuid_to_test is a valid UUID.
    
     Parameters
    ----------
    uuid_to_test : str
    version : {1, 2, 3, 4}
    
     Returns
    -------
    `True` if uuid_to_test is a valid UUID, otherwise `False`.
    
     Examples
    --------
    >>> is_valid_uuid('c9bf9e57-1685-4c89-bafb-ff5af830be8a')
    True
    >>> is_valid_uuid('c9bf9e58')
    False
    """
    
    try:
        uuid_obj = UUID(uuid_to_test, version=version)
    except ValueError:
        return False
    return str(uuid_obj) == uuid_to_test


if __name__ == '__main__':
    import doctest
    doctest.testmod()

All the existing answers use regex. If you're using Python , you might want to consider a try/except in case you don't want to use regex: (Bit shorter than the answer above).

Our validator would then be:

import uuid

def is_valid_uuid(val):
    try:
        uuid.UUID(str(val))
        return True
    except ValueError:
        return False

>>> is_valid_uuid(1)
False
>>> is_valid_uuid("123-UUID-wannabe")
False
>>> is_valid_uuid({"A":"b"})
False
>>> is_valid_uuid([1, 2, 3])
False
>>> is_valid_uuid(uuid.uuid4())
True
>>> is_valid_uuid(str(uuid.uuid4()))
True
>>> is_valid_uuid(uuid.uuid4().hex)
True
>>> is_valid_uuid(uuid.uuid3(uuid.NAMESPACE_DNS, 'example.net'))
True
>>> is_valid_uuid(uuid.uuid5(uuid.NAMESPACE_DNS, 'example.net'))
True
>>> is_valid_uuid("{20f5484b-88ae-49b0-8af0-3a389b4917dd}")
True
>>> is_valid_uuid("20f5484b88ae49b08af03a389b4917dd")
True
import re

UUID_PATTERN = re.compile(r'^[\da-f]{8}-([\da-f]{4}-){3}[\da-f]{12}$', re.IGNORECASE)
uuid = '20f5484b-88ae-49b0-8af0-3a389b4917dd'

if UUID_PATTERN.match(uuid):
    return True
else:
    return False

As Giacomo Alzetta says, UUIDs can be compared as any other object, using == . The UUID constructor normalises the strings, so that it does not matter if the UUID is in a non-standard form.

import uuid
uuid.UUID('302a4299-736e-4ef3-84fc-a9f400e84b24') == uuid.UUID('302a4299-736e-4ef3-84fc-a9f400e84b24')
# => True
uuid.UUID('302a4299736e4ef384fca9f400e84b24') == uuid.UUID('{302a4299-736e-4ef3-84fc-a9f400e84b24}')
# => True

String comparison will compare the literal strings, which may or may not conform to UUID:

'302a4299-736e-4ef3-84fc-a9f400e84b24' == '302a4299-736e-4ef3-84fc-a9f400e84b24'
# => True
'302a4299736e4ef384fca9f400e84b24' == '{302a4299-736e-4ef3-84fc-a9f400e84b24}'
# => False

You can convert UUIDs to strings using str(x) , or strings into UUID objects using uuid.UUID(x) as shown above. Note that you can't compare strings to UUIDs, only strings to strings and UUIDs to UUIDs.

If it really bugs you whether or not an UUID string is in its canonical form, you can try to convert it to an UUID object and back to string (which will give you the canonical form), and compare it to the original:

x = '302a4299-736e-4ef3-84fc-a9f400e84b24'
str(uuid.UUID(x)) == x
# => True
x = '302a4299736e4ef384fca9f400e84b24'
str(uuid.UUID(x)) == x
# => False

However, you really shouldn't care whether a UUID string is canonical - as long as it can be recognised as an UUID string, it should be good enough. If it can't...

uuid.UUID("foo")
# => ValueError: badly formed hexadecimal UUID string

If you need to know the version of the UUID, it's right there in the UUID API :

uuid.UUID('302a4299-736e-4ef3-84fc-a9f400e84b24').version
# => 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM