[Zope3-Users] Modified IntId utility

Maken Seteva crapkonto at gmail.com
Wed Sep 26 09:37:17 EDT 2007


On Sep 26, 2007, at 12:48 PM, Benji York wrote:

> Maken Seteva wrote:
>>> On 24. Sep 2007, at 18:53, Maken Seteva wrote:
>>>
>>>> Fellow Zopers.
>>>> I have made a slight modification to my intid util by inheriting  
>>>> from IntId and overriding _generateId().
>>>> I do this to be sure that all new created objects will have an  
>>>> incrementing number where
>>>> the first object created gets id 1, the next gets id 2 and so  
>>>> on. This way I get for "free" sorting by
>>>> oldest/newest.
>
>> Not fully sure how to resolve conflicts though as I'm quite new to  
>> this.
>
> The best way to resolve conflicts is to not create them.  If you  
> use the most significant bits of your int ID as a counter, and fill  
> the least significant bits with conflict busting randomness, you'll  
> be in good shape.  We (ZC) have a package that does just that which  
> we really need to release.  If there's interest I'll take a stab at  
> doing that soon.

Can't wait so :)
Otherwise I wrote a simple one in 10 lines of python:

  class Counter(object):
      def __init__(self, leastSignificantBits=4):
          self.incrementStep = 0x1 << leastSignificantBits
          self.counter = 0
          self.maxrand = pow(2, leastSignificantBits)

      def _increment(self):
          self.counter += self.incrementStep

      def __call__(self):
          self._increment()
          # OR the random bits at the end
          return self.counter | random.randrange(0, self.maxrand)


Test:
 >>> import myintid
 >>> c = myintid.Counter(8)
 >>> print hex(c())
0x181
 >>> for _ in range(17):
...     print hex(c())
...
0x277
0x3aa
0x456
0x5ad
0x6bf
0x794
0x80f
0x9ef
0xade
...

Maybe someone finds it useful
/Seteva


More information about the Zope3-users mailing list