How does Mr. Martelli's Borg recipe work ?

John Roth newsgroups at jhrothjr.com
Tue Jul 22 22:50:38 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 ?). I have gone through the code in the
> debugger several(many) times, and inserted god knows how many print
> statements, but without luck(or skill i guess).
>
> Just so you don't waste your time, i do understand that _shared_state
> is a class field(variable, or what not) and that its state is shared
> by all instances.
>
> Sorry if this question is banal, but I really need to understand this,
> even if it means exposing my complete lack of understanding as far as
> what is probaly basic Python knowledge.

I can kind of understand the justification for the Borg pattern
in Python releases before 2.2, because there was no way of
creating a true singleton in those releases. However, in 2.2 and
later, it's really easy to create one using new style classes.

The trick is to use the __new__() method instead of the
__init__ method. In the __new__ method, test to see if
you've created an instance  yet. If you have, just pass it
back. If you haven't, call object.__new__ to create an
instance, save it, initialize it and pass it back. There are the
usual issues with race conditions if you have multiple
threads before the first call, but those can be avoided
easily.

That being the case, I'd like to see the Borg pattern go the way
of a fondly remembered hack that is no longer necessary.

John Roth
>
> Regards,
>
> Martin






More information about the Python-list mailing list