Borg vs Singleton vs OddClass

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Sep 27 22:45:10 EDT 2008


On Sat, 27 Sep 2008 11:12:00 -0700, 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__():
>         return self


I don't think that pattern works as you give it. I suggest you read the 
thread "What do you call a class not intended to be instantiated", 
started by me on the 21st of September, which covers a similar pattern.

I'm afraid it's a rather long thread, with a lot of people 
misunderstanding what I was asking, but still worth reading. If you only 
have time to read one post, I suggest you read my reply to Ben Finney, 
posted yesterday.

My own feeling is that both your OddClass and my class without instances 
are probably solutions looking for a problem. Well, actually, no, that's 
too strong: I think the concept of "Class Singleton" is a perfectly valid 
solution to certain problems, but it competes with more well-known 
solutions like modules and Borg (in Python) and Singletons (the hammer 
available in Java and C++). As for which is better, that's partly a 
matter of personal taste and partly a matter of familiarity.


> It do have a problem though, that you can't do isinstance(a, OddClass)

But you can say "a is OddClass", which is more appropriate for a 
Singleton.

> The problem with Borg is that it is not inheritable (in certain
> sense[1]) and only work with old-style class (which is due to be
> completely removed on py3k)[2]

No, there is a new-style Borg. Read the comments here:
http://code.activestate.com/recipes/66531/

The new-style Borg is hardly more complicated than old-style: 6 lines 
versus 4.

I like Luke Plant's comment:

"classes and modules are singletons. You don't need singletons in python 
simply because classes and modules are always singletons, and they are 
also first class objects. They can have everything instances have, and as 
import statements don't make copies there is only ever one of them. We 
don't need no stinkin' design patterns."



-- 
Steven



More information about the Python-list mailing list