Generating a unique identifier

Steven D'Aprano steve at
Sat Sep 8 03:31:46 CEST 2007

On Fri, 07 Sep 2007 08:42:45 -0700, Paul Rubin wrote:

> Steven D'Aprano <steve at> writes:
>> def unique_id():
>>     n = 1234567890
>>     while True:
>>         yield n
>>         n += 1
> unique_id = itertools.count(1234567890)


I really must make itertools second-nature. I always forget it.

>> which is easy enough, but I thought I'd check if there was an existing
>> solution in the standard library that I missed. Also, for other
>> applications, I might want them to be rather less predictable.
> def unique_id():
>    return os.urandom(10).encode('hex')

Any time I see something using a random number to generate IDs, I worry 
about collisions. Am I being paranoid? (But even paranoids write code 
with bugs...)

Here's something which is a little less predictable than a straight 

def unpredictable_counter(n=12345678):
    while True:
        n += random.randint(1, 68)
        yield n

def more_unpredictable_counter(n=1234567):
    uc = unpredictable_counter(n)
    pool = []
    while True:
        if not pool:
            pool = [None]*99
            for i in range(99):
                pool[i] =
        yield pool.pop()


More information about the Python-list mailing list