How does Mr. Martelli's Borg recipe work ?

Erik Max Francis max at alcyone.com
Tue Jul 22 22:18:42 EDT 2003


Mars wrote:

> It is a very useful substitute for a Singleton, but I can't figure out
> how it works. _shared_state is never assigned any value, only
> self.__dict__ is assigend self._shared_sate's value - or rather
> (self.)_shared_state must be assigned a value at some point, otherwise
> the code wouldn't work(right ?).

It is assigned a value; it's bound to a new, empty dictionary.  Since
it's a class attribute, that means that empty dictionary is shared by
all instances.

_All_ instances have precisely the same __dict__ object.  They all are
exactly the same.  That's how the pattern works.

>>> class Borg:
...  __sharedState = {}
...  def __init__(self):
...   self.__dict__ = self.__sharedState
... 
>>> x = Borg()
>>> y = Borg()
>>> x is y
0
>>> x.__dict__ is y.__dict__
1
>>> x.a = 123
>>> y.a
123
>>> y.b = 321
>>> x.b
321

-- 
   Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ People say that life is the thing, but I prefer reading.
\__/  Logan Pearsall Smith




More information about the Python-list mailing list