Generating a unique identifier
Marc 'BlackJack' Rintsch
bj_666 at gmx.net
Fri Sep 7 08:45:12 EDT 2007
On Fri, 07 Sep 2007 12:03:23 +0000, Steven D'Aprano 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.
For that easy solution you can use `itertools.count()`.
Ciao,
Marc 'BlackJack' Rintsch
More information about the Python-list
mailing list