Generating a unique identifier

stephen.lewitowski at googlemail.com stephen.lewitowski at googlemail.com
Tue Sep 11 00:44:09 CEST 2007


On Sep 7, 1:03 pm, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> 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.

This is very simple. Use a class variable that increments every time a
new object is created. If you need to use it in a number of different
types of object then you could use the code below in a metaclass and
tag all of your classes with the metaclass. Unless you are making
billions of objects then i think that this should suffice.

class MyObj:
   id_count = 0
   def __init__(self):
      self.id = self.id_count
      MyObj.id_count += 1
      print self.id, MyObj.id_count

MyObj()
MyObj()




More information about the Python-list mailing list