Borg with MetaClass ?

Singleton is one of the well known design pattern.

In python, most of us use the Borg Singleton like, which is not a true Singleton, since only the ‘state is shared’. In fact, you use distinct objects but they share the same __dict__.

Yesterday, i played a bit w/ python metaclass. Beside this can be really usefull under certain condition, i discover that you can build a Borg with that too :)

class Single_imp:
def __init__(cls,name,base,dict):
cls.value = 1
def __call__(cls):
return cls
def setValue(cls,value):
cls.value = value

class Single:
__metaclass__ = Single_imp

a = Single()
b = Single()
print a
print b
a.setValue(10)
print b.value

and the result:

<__main__.Single_imp instance at 0x401eb96c>
<__main__.Single_imp instance at 0x401eb96c>
10

Ok .. the code looks strange.. and not a true Singleton .. but how can i build a real true in Python ?



Related Posts

2 thoughts on “Borg with MetaClass ?

  1. __new__ allows you do fairly simply create a singleton.  I think it goes like:

    def __new__(cls):

    _ try:

    _ _ return cls._singleton

    _ except AttributeError:

    _ _ s = cls._singleton = object.__new__(cls)

    _ _ return s

    Or you can do:

    class _SingletonClass: …

    _TheSingleton = _SingletonClass

    def SingletonClass():

    _ return _TheSingleton

    The last one is my preferred solution ;)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>