Borg identity [was Re: why () is () and [] is [] work in other way?]

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Apr 27 12:56:10 EDT 2012


On Thu, 26 Apr 2012 04:42:36 -0700, Adam Skutt wrote:

> You're going to have to explain the value of an "ID" that's not 1:1 with
> an object's identity, for at least the object's lifecycle, for a
> programmer.  If you can't come up with a useful case, then you haven't
> said anything of merit.

I gave an example earlier, but you seem to have misunderstood it, so I'll 
give more detail.


In the Borg design pattern, every Borg instance shares state and are 
indistinguishable, with only one exception: object identity. We can 
distinguish two Borg instances by using "is".

Since the whole point of the pattern is for Borg instances to be 
indistinguishable, the existence of a way to distinguish Borg instances 
is a flaw and may be undesirable. At least, it's exposing an 
implementation detail which some people argue should not be exposed.

Why should the caller care whether they are dealing with a singleton 
object or an unspecified number of Borg objects all sharing state? A 
clever interpreter could make many Borg instances appear to be a 
singleton. A really clever one could also make a singleton appear to be 
many Borg instances.

Note that this is virtually the same situation as that which John Nagle 
objects to, namely that the implementation detail of small ints being 
singletons is exposed. There is only ever one 0 instance, but potentially 
many 3579 instances.

John's argument is that Python should raise an exception if you compare 
"2 is 2", or for that matter "3579 is 3579", which is foolish. If you're 
going to change the semantics of "is", why not do something useful and 
ensure that "3579 is 3579" returns True regardless of whether they 
actually are the same instance or not?

That would be far more useful than raising an exception. It would 
complicate the definition of "is", but perhaps that's a price people are 
willing to pay for avoiding the (trivial) confusion about object identity.

[...]
>> identities. The Borg design pattern, for example, would be an excellent
>> candidate for ID:identity being treated as many-to-one.
> 
> How would inheritance work if I did that?

You don't inherit from Borg instances, and instances inherit from their 
class the same as any other instance.


-- 
Steven



More information about the Python-list mailing list