Borg Pattern Class usable from other classes?

Paolo Invernizzi paoloinvernizzi at dmsware.com
Thu Oct 11 18:54:13 CEST 2001


<troll>er, shouldn't it be called a singleton?</troll>
Alex can kill you for this ;))

> Having hacked around with it I can only conclude that when called from
> within a different module, the Borg class statement is re-evaluated, and
> "__s = {}" is re-evaluated. That doesn't make any sense though, so I must
> be wrong. __s is certainly empty when called from Test.__init(), but I
> don't know why.

I hope that this can help you...

# a.py
class Borg:
    __s = {}
    def __init__(s):
        s.__dict__ = s.__s

if __name__ == "__main__":
    print "a.py id(Borg)->",id(Borg)
    a = Borg()
    a.t = "Huba"
    print "a", a.t
    b=Borg()
    print "b", b.t
    import b
    d=b.Test()

# b.py
import a

class Test:
    def __init__(s):
        print "b.py id(a.Borg)->",id(a.Borg)
        c = a.Borg()
        if hasattr(c, 't'): print 'c', c.t
        else: print 'c has no t'
----------------------------------------
C:\temp>python a.py
a.py id(Borg)-> 8800452
a Huba
b Huba
b.py id(a.Borg)-> 8812652
c has no t
-----------------------------------------
So, in the second module you have to use something like..
-----------------------------------------------------
# b.py
from __main__ import Borg

class Test:
    def __init__(s):
        print "b.py id(Borg)->",id(Borg)
        import pdb; pdb.set_trace()
        c = Borg()
        if hasattr(c, 't'): print 'c', c.t
        else: print 'c has no t'
----------------------------------------------
C:\temp>python a.py
a.py id(Borg)-> 8800452
a Huba
b Huba
b.py id(Borg)-> 8800452
c Huba
------------------------------------------------
At the end of the story: namespaces and import statement are not always so
intuitive as they seem

<Scotty, beam me up ;) >
Paolo Invernizzi







More information about the Python-list mailing list