Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

will hash(time.time()) always be unique

Tags:

python

time

hash

I am trying to generate unique ID numbers for some unit tests, and I saw a suggestion somewhere to use something like:

def unique_id():
    time.sleep(0.000001) # smallest precision for time.time()
    return time.time()

I'm wondering if the hash() call will always take at least 0.000001, so I could use:

def unique_id():
    return hash(time.time())

Could that ever return the same value twice, if I'm calling it in succession within a single threaded application?

edit: bolded the word 'NUMBERS' because every single person has overlooked it.

like image 835
Gerald Thibault Avatar asked Dec 18 '22 21:12

Gerald Thibault


1 Answers

If you need a unique value, it's recommended to use the uuid library. Example:

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

If you need number-only values, use the random library.

>>> import random
>>> INT_MAX = sys.maxint #  Set INT_MAX to the max value for your given INT column
>>> random.randint(0, INT_MAX)
5188925271790705047
like image 126
Evan Fosmark Avatar answered Dec 21 '22 10:12

Evan Fosmark