python: how to convert a valid uuid from String to UUID?

Python Programming

Question or problem about Python programming:

I receive the data as

        "name": "Unknown",
        "parent": "Uncategorized",
        "uuid": "06335e84-2872-4914-8c5d-3ed07d2a2f16"

and I need to convert the uuid from String to uuid

I did not find a way on the python docs, or am I missing something basic here?

How to solve the problem:

Solution 1:

Just pass it to uuid.UUID:

import uuid

o = {
    "name": "Unknown",
    "parent": "Uncategorized",
    "uuid": "06335e84-2872-4914-8c5d-3ed07d2a2f16"

print uuid.UUID(o['uuid']).hex

Solution 2:

Don’t call .hex on the UUID object unless you need the string representation of that uuid.

>>> import uuid
>>> some_uuid = uuid.uuid4()
>>> type(some_uuid)

>>> some_uuid_str = some_uuid.hex
>>> some_uuid_str
>>> type(some_uuid_str)

Then as others mentioned above to convert a uuid string back to UUID instance do:

>>> uuid.UUID(some_uuid_str)
>>> (some_uuid == uuid.UUID(some_uuid_str))
>>> (some_uuid == some_uuid_str)

You could even set up a small helper utility function to validate the str and return the UUID back if you wanted to:

def is_valid_uuid(val):
        return uuid.UUID(str(val))
    except ValueError:
        return None

Then to use it:

>>> some_uuid = uuid.uuid4()
>>> is_valid_uuid(some_uuid)
>>> type(is_valid_uuid(some_uuid))

Solution 3:

If the above answer didn’t work for you for converting a valid UUID in string format back to an actual UUID object… using uuid.UUID(your_uuid_string) worked for me.

In [6]: import uuid
   ...: o = {
   ...:     "name": "Unknown",
   ...:     "parent": "Uncategorized",
   ...:     "uuid": "06335e84-2872-4914-8c5d-3ed07d2a2f16"
   ...: }
   ...: print uuid.UUID(o['uuid']).hex
   ...: print type(uuid.UUID(o['uuid']).hex)

In [7]: your_uuid_string = uuid.UUID(o['uuid']).hex

In [8]: print uuid.UUID(your_uuid_string)

In [9]: print type(uuid.UUID(your_uuid_string))

Hope this helps!