简体   繁体   中英

python systemrandom for unique numbers

I need to generate a globally unique integer identifier.

Does the number generated using

from random import SystemRandom
SystemRandom().getrandbits(64)

Is guaranteed to be unique?

No. In general, random number generators can't ensure uniqueness of the numbers they produce. (There are specific algorithms that can generate a sequence of unique random-looking numbers, including "full-period" linear congruential generators, but it's not generally the case that an RNG produces unique random numbers.)

However, there are several things to keep in mind when generating unique identifiers (and I mention them in " Unique Random Identifiers "). You should give further information in your question on why you need unique identifiers, so that I can help you better.

It is not guaranteed, but if you test you can that is almost impossible to generate the same number twice. I was working in something like that some time ago, and found this: How can I create a random number that is cryptographically secure in python?

I don't know the context of your question, but if you wnat to get a unique code or something like that, you try using GUID. Link: https://www.geeksforgeeks.org/generating-random-ids-using-uuid-python/

Not only that random numbers are not guaranteed to be unique. They must not be guaranteed to be unique, or they would not be truly random. Therefore, it is perfectly valid (although very very unlikely, one can easily calculate exactly how unlikey) to get the same number 100 times in a row from a perfect random generator.

If you want unique identifiers, use UUIDs. They are meant for that purpose. Are they guaranteed to be unique? Not exactly, but let's say they are unique enough that you should not care about the details. They are the standard way to do that. Use them.

>>> import uuid
>>> uuid.uuid4()
UUID('bc64667f-503c-416e-964d-93486a02f3fd')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM