How does Mr. Martelli's Borg recipe work ?

Terry Reedy tjreedy at udel.edu
Tue Jul 22 22:01:16 EDT 2003


"Mars" <martin_a_clausen at hotmail.com> wrote in message
news:764b8294.0307221520.18017b09 at posting.google.com...
> I have looked long and hard at Mr. Martelli's Borg recipe:
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531
>
> 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 ?).

Yes and no.  The 'value' of a name is the object it is assigned to.
In the last line of the 4 line code and only body line of the __init__

class Borg:
    __shared_state = {}
    def __init__(self):
        self.__dict__ = self.__shared_state

the instance name '__dict__' is rebound to the object also called
__shared_state, so that the two names become aliases for the *same*
object (of type dict).  The original instance dict gets unbound from
the name__dict__ and becomes eligible to be garbage collected.  The
same is true for every Borg instance.  Create 100 Borg instances and
there are 101 aliases for one and the same dict.

Now ,
instance.name = value
is (usually) executed behind the scence as
instance.__dict__['name'] = value
where __dict__ is the dict *currently* bound to instance attribute
__dict__.  (One of the exceptions to this is _dict__ itself.)  In the
Borg scheme, that name is no longer bound to the original dict but to
the shared dict.  So nothing is (or at least need be) ever added to
that dict under its first name of __shared_state.

Terry J. Reedy






More information about the Python-list mailing list