Generating a unique identifier

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Sep 7 08:03:23 EDT 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:
    make_an_object(id=unique_id())
    do_stuff_with_objects()
    delete_some_of_them()

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.



-- 
Steven.



More information about the Python-list mailing list