Smalltalk and Python

Carel Fellinger cfelling at iae.nl
Fri Dec 15 10:13:57 EST 2000


Rainer Deyke <root at rainerdeyke.com> wrote:

> (where Singleton is an instance of the (meta-)class that implements
> singletons, not listed here because I haven't written or found it yet)

I once tried the mixin approach, but was left with to many loose ends
so I would go for the factory approach like:

'''Singleton Pattern

Using the singleton factory each class keeps track of its own singleton,
unless some base class had the magic attribute "__singleton" set to [].
In that case all derived classes share their singleton; so all instances
in use better be in a sole inheritance line from that base class up and
you better take care to instantiate the last class in that particular
derivation chain first!
'''

def singleton(Class):
    if hasattr(Class, "__singleton"):
        a = Class.__singleton
        if a == []:
            a.append(Class())
        return a[0]
    else:
        name = '_%s__singleton' % Class.__name__
        if not Class.__dict__.has_key(name):
            Class.__dict__[name] = Class()
        return Class.__dict__[name]


#singleton=instance

if __name__ == "__main__":
    class A: pass
    class AA(A): pass

    setattr(A, "__singleton", [])
    assert singleton(AA) is singleton(A)
    assert singleton(A) is singleton(A)
    assert singleton(AA) is singleton(AA)

    del A.__singleton
    assert not singleton(AA) is singleton(A)
    assert singleton(A) is singleton(A)
    assert singleton(AA) is singleton(AA)
-- 
groetjes, carel



More information about the Python-list mailing list