[Python-Dev] Weird use of hash() -- will this work?

M.-A. Lemburg mal@lemburg.com
Thu, 18 Jan 2001 18:10:14 +0100

"Eric S. Raymond" wrote:
> So I'm writing a module to that needs to generate unique cookies.  The
> module will run inside one of two environments: (1) a trivial test wrapper,
> not threaded, and (2) a lomg-running multithreaded server.
> Because Python garbage-collects, hash() of a just-created object isn't
> good enough.  Because we may be threading, millisecond time isn't
> good enough.  Because we may *not* be threading, thread ID isn't good
> either.
> On the other hand, I'm on Linux getting millisecond time resolution.
> And it's not hard to notice that an object hash is a memory address.
> So, how about `time.time()` + hex(hash([]))?
> It looks to me like this will remain unique forever, because another thread
> would have to create an object at the same memory address during the same
> millisecond to collide.
> Furthermore, it looks to me like this hack might be portable to any OS
> with a clock tick shorter than its timeslice.
> Comments?

A combination of time.time(), process id and counter should
work in all cases. Make sure you use a lock around the counter,

Marc-Andre Lemburg
Company:                                        http://www.egenix.com/
Consulting:                                    http://www.lemburg.com/
Python Pages:                           http://www.lemburg.com/python/