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

前端 未结 6 1459
暗喜
暗喜 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条回答
  •  旧时难觅i
    2020-12-15 15:33

    Since the straight-forward solution hasn't been posted yet to generate consistent version 4 UUIDs:

    import random
    import uuid
    
    rnd = random.Random()
    rnd.seed(123)
    
    uuid = uuid.UUID(int=rnd.getrandbits(128), version=4)
    
    

    where you can see then:

    >>> uuid.version
    4
    

    This doesn't just "mock" the version information. It creates a proper UUIDv4:

    The version argument is optional; if given, the resulting UUID will have its variant and version number set according to RFC 4122, overriding bits in the given hex, bytes, bytes_le, fields, or int.

    Python 3.8 docs

提交回复
热议问题