Borg vs Singleton vs OddClass

Miles semanticist at gmail.com
Sat Sep 27 20:22:50 EDT 2008


Lie wrote:
> This is probably unrelated to Python, as this is more about design
> pattern. I'm asking your comments about this design pattern that is
> similar in functionality to Singleton and Borg: to share states.
>
> I'm thinking about this design pattern (I don't know if anyone has
> ever thought of this pattern before):
>
> class OddClass(object):
>    def __init__(self):
>        global OddClass
>        OddClass = self
>    def __call__():

I'll change this to def __call__(self):

>        return self
>
> The OddClass is a class that would overwrite its own class definition
> at its first instantiation. OddClass defines __call__ so that
> subsequent "instantiation" (technically it is no more an
> instantiation, but Duck Typing says it does) of the class would return
> the single instance.

This seems like a terrible idea to me, but then I never really
understood the appeal of the Singleton pattern, especially in Python.

> Singleton and OddClass is inheritable.
>
>>>> class OddClass(object): ...
>>>> s = OddClass()
>>>> class A(OddClass): pass

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
    __init__() takes exactly 1 argument (4 given)

Oops!  And assuming you carefully ordered your code so that OddClass
will never be instantiated before it is subclassed (which seems
fragile), you get behavior like this:

>>> s = OddClass()
>>> s is OddClass()
True
>>> a = A()
>>> s is OddClass()
False
>>> a is OddClass()
True
>>> a is A()
False
>>> a is OddClass()
False

-Miles



More information about the Python-list mailing list