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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With