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

前端 未结 3 696
花落未央
花落未央 2021-02-03 16:47

I receive the data as

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


        
3条回答
  •  无人共我
    2021-02-03 17:38

    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
    '5b77bdbade7b4fcb838f8111b68e18ae'
    >>> type(some_uuid_str)
    
    

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

    >>> uuid.UUID(some_uuid_str)
    UUID('5b77bdba-de7b-4fcb-838f-8111b68e18ae')
    >>> (some_uuid == uuid.UUID(some_uuid_str))
    True
    >>> (some_uuid == some_uuid_str)
    False
    

    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):
        try:
            return uuid.UUID(str(val))
        except ValueError:
            return None
    

    Then to use it:

    >>> some_uuid = uuid.uuid4()
    >>> is_valid_uuid(some_uuid)
    UUID('aa6635e1-e394-463b-b43d-69eb4c3a8570')
    >>> type(is_valid_uuid(some_uuid))
    
    

提交回复
热议问题