hash(time.time())总是唯一的

Ger*_*ult 2 python hash time

我正在尝试为某些单元测试生成唯一的ID ,我看到一个建议在某处使用类似的东西:

def unique_id():
    time.sleep(0.000001) # smallest precision for time.time()
    return time.time()
Run Code Online (Sandbox Code Playgroud)

我想知道hash()调用是否总是至少0.000001,所以我可以使用:

def unique_id():
    return hash(time.time())
Run Code Online (Sandbox Code Playgroud)

如果我在单线程应用程序中连续调用它,那么它是否会返回相同的值两次?

编辑:用'NUMBERS'这个词加粗,因为每个人都忽略了它.

Eva*_*ark 6

如果您需要唯一值,建议使用该uuid库.例:

>>> import uuid
>>> uuid.uuid4()
UUID('514c2bd7-75a3-4541-9075-d66560f42b5c')
>>> str(uuid.uuid4())
'6faad714-c2df-448b-b072-f91deb380e84'
Run Code Online (Sandbox Code Playgroud)

如果您需要仅限数字值,请使用该random库.

>>> import random
>>> INT_MAX = sys.maxint #  Set INT_MAX to the max value for your given INT column
>>> random.randint(0, INT_MAX)
5188925271790705047
Run Code Online (Sandbox Code Playgroud)