[Zope] Re: Unique id product
Steve Alexander
steve@cat-box.net
Fri, 28 Jul 2000 18:20:21 +0100
On 2 July, 2000 Steve Alexander wrote:
>
> If you just want ids that are unique to a folder, try the following
> algorithm (taken originally from the Discussion object code in the PTK).
> The variable "self" is the one passed to the constructor method of a
> particular Python class, and represents the folder you want to put the
> new object into. I'm assuming the object is a "FooBar Item". The
> "foobar-%06d" bit generates a unique id for the object that looks like
> "foobar-290172837", based on the current time.
>
> id = int(DateTime().timeTime())
> while hasattr(self, str(id)):
> id = id +1
> id = 'foobar-%09d' % id
>
> The advantage of this approach is that there is very little contention
> in most cases.
I just looked back over some code where I used this algorithm, and I
realised that it doesn't actually work :-( The identifiers that are
searched for do not reflect the identifiers that are produced.
The original code from the PTK does work. Here it is, adapted very
slightly:
# Find an unused id in location
id = int(DateTime().timeTime())
while hasattr(self, `id`):
id = id + 1
return id
Here's my own, now fixed, code. Note the addition of a "max_tries"
variable.
if id == 'auto' or id == None:
n = int(DateTime().timeTime())
max_tries = 10
fk = lambda key: 'foobar-%d' % key # function to format key
id = fk(n)
while max_tries and hasattr(self, str(id)):
n = n + 1
max_tries = max_tries-1
id = fk(n)
Sorry for posting such rubbish the first time around :-/
--
Steve Alexander
Software Engineer
Cat-Box limited
http://www.cat-box.net