Search code examples
pythonpython-3.xuuid

How to combine two UUIDv4 strings to a single unique UUIDv4 string


I have two UUIDv4 strings which I want to combine to a single unique UUIDv4 string, such that the input UUID strings always generate the same UUIDv4 string regardless of their insertion index.

def generate_uuidv4(uuid1,uuid2):
    """
    Combine to single unique uuidv4 string which is replicable based on input strings regardless of insert position
    """
    return uuidv4_string

Note: Input ids are position agnostic.


Solution

  • The most straight forward approach would probably be to combine the int representation of two UUIDs with bitwise operators and construct a new UUID from it:

    >>> from uuid import *
    
    >>> u1 = uuid4()
    >>> u2 = uuid4()
    >>> u3 = UUID(int=u1.int ^ u2.int, version=4)
    >>> u1, u2, u3
    (UUID('2266aff1-a7be-4c71-bc0d-987779f68bd3'),
     UUID('284c5065-299f-479c-9d6b-d353012795d7'), 
     UUID('0a2aff94-8e21-4bed-a166-4b2478d11e04'))
    

    I can't tell you what the best operator for combining here would be, an XOR, OR, AND, or whatever else. Reasoning about how that affects the random distribution of the result is beyond my pay grade.