Borg - is that a singleton?

Giovanni Bajo noway at sorry.com
Fri Feb 28 15:16:53 CET 2003


Hello,

Since Borg (as in
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531) rebinds the
dictionaries to Borg.__shared_state, which is unique across the program, I
fail to see how this can be used as singleton without counter-intuitive
side-effects like:

class Foo(Borg):
    def __init__(self, a, x):
        Borg.__init__(self)
        self.a = a
        self.x = x

class Bar(Borg):
    def __init__(self, x, y):
        Borg.__init__(self)
        self.x = x
        self.y = y

if __name__ == "__main__":
    f1 = Foo(10,11)
    f2 = Foo(14,15)
    b1 = Bar(1,2)
    b2 = Bar(3,4)

    print f1.a, f1.x
    print f2.a, f2.x
    print b1.x, b1.y
    print b2.x, b2.y

Which obviously prints:

14 3
14 3
3 4
3 4

since 'x' now refers to the same attribute for any borg'd instance, even
across different classes. Citing GoF, usually you have only one monitor and
only one printer in your system, but you don't want the current draw
position to be the same on both (or whatever, just a silly example). Being a
beginner, my naive solution was:

class Borg:
    def __init__(self):
        cls = self.__class__
        try: cls.__shared_state
        except:
            cls.__shared_state = {}
        self.__dict__ = cls.__shared_state

Which leads to what seems to me the expected behaviour from a singleton,
that is:

14 15
14 15
3 4
3 4

Comments?

Giovanni Bajo






More information about the Python-list mailing list