Diez B. Roggisch deets at
Wed Oct 10 17:37:53 CEST 2007

Steven D'Aprano wrote:

> On Wed, 10 Oct 2007 06:57:15 -0700, Carl Banks wrote:
>> On Oct 10, 9:39 am, Steven D'Aprano <st... at REMOVE-THIS-
>>> wrote:
>>> On Wed, 10 Oct 2007 09:36:56 +0000, pythoncurious wrote:
>>> > So how do people solve this? Is there an obvious way that I missed?
>>> Mostly by avoiding singletons. Why do you need only one instance?
>>> Perhaps you should consider the Borg pattern instead.
>> That wouldn't help.  In the OP's case, it would create two borgs.
> Two borgs, or two million, the whole point of using borgs is that it
> doesn't matter.

It does matter where the classes live (module-wise). Which is the problem
the OP had, borg or not to borg.

class Borg(object):
    __shared_state = {}

    def __init__(self):
        self.__dict__ = self.__shared_state

if __name__ == "__main__":
    import test
    mainBorg = Borg()
    mainBorg.a = 100
    testBorg = test.Borg()
    testBorg.a = 200
    print mainBorg.a
    print testBorg.a

Run this as this:

droggisch at ganesha:/tmp$ ll *py
-rw-r--r-- 1 droggisch  298 2007-10-10 17:30
droggisch at ganesha:/tmp$ python

You will see that there are _two_ different Borg-Cubes, as the output
indicates. This has hit me more than once, and Carl Banks pointed that
error out to the OP.

And if you'd follow your own advice of " take each word to have it's normal
English meaning," then the OP is not

"struggling to get a singleton working"

but struggling to get "some sort of singleton working", as you cite
yourself, and first tried to implement his needs using no singleton-recipe
(or borg pattern) but a module:

The first approach was simply to use a module, and every variable in
it will be seen by all who import the module.
That works in some cases, but not if I have the following structure:

Which didn't work out for the same reason his singleton approach didn't work
and your beloved Borg-pattern doesn't as well.



More information about the Python-list mailing list