How to generate a random UUID which is reproducible (with a seed) in Python

前端 未结 6 1460
暗喜
暗喜 2020-12-15 14:57

The uuid4() function of Python\'s module uuid generates a random UUID, and seems to generate a different one every time:

In [1]: import uuid

In          


        
6条回答
  •  情书的邮戳
    2020-12-15 15:38

    Gonna add this here if anyone needs to monkey patch in a seeded UUID. My code uses uuid.uuid4() but for testing I wanted consistent UUIDs. The following code is how I did that:

    import uuid
    import random
    
    # -------------------------------------------
    # Remove this block to generate different
    # UUIDs everytime you run this code.
    # This block should be right below the uuid
    # import.
    rd = random.Random()
    rd.seed(0)
    uuid.uuid4 = lambda: uuid.UUID(int=rd.getrandbits(128))
    # -------------------------------------------
    
    # Then normal code:
    
    print(uuid.uuid4().hex)
    print(uuid.uuid4().hex)
    print(uuid.uuid4().hex)
    print(uuid.uuid4().hex)
    

提交回复
热议问题