Generating a unique identifier

Steven D'Aprano steve at
Fri Sep 7 14:03:23 CEST 2007

I have an application that will be producing many instances, using them 
for a while, then tossing them away, and I want each one to have a unique 
identifier that won't be re-used for the lifetime of the Python session.

I can't use the id() of the object, because that is only guaranteed to be 
unique during the lifetime of the object.

For my application, it doesn't matter if the ids are predictable, so I 
could do something as simple as this:

def unique_id():
    n = 1234567890
    while True:
        yield n
        n += 1

unique_id = unique_id()

while Application_Is_Running:

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.


More information about the Python-list mailing list