Singleton vs Proxies DP (was Re: Solution: Direct access to Printer I/O lines)

Rainer Deyke root at
Sun Dec 17 04:26:32 CET 2000

"Alex Martelli" <aleaxit at> wrote in message
news:91gkh801e49 at
> It's not rare to desire that a certain resource (e.g., a RDBMS
> running on another process/machine) be handled through one,
> and one only, 'bottleneck'.  Singleton does ensure that, yes.
> There is a space for singletons.  But the Singleton _Design
> Pattern_ need not be the best way to have singletons.

I consider the singleton pattern as stated in the GOF to be overly
cumbersome in the context of Python.  (It is necessary in C++ because of
object creation order.)

The purpose of singletons is to implement unique behavior/state.  How you
choose to expose this behavior is another issue.  It is always possible to
add extra layers of abstraction (such as light-weight proxies), thereby
increasing flexibility of a sort while removing the flexibility inherent in
small pieces of code that are easy to read, understand, modify, and replace.

There are already singletons in Python.  They are called modules.
Unfortunately, modules cannot have overloaded operators or
__getattr__/__setattr__, and they require the error-prone and ugly 'global'
statement to modify their state.

My preference for standardized singletons in Python is this:

singleton C:
  pass # class definition here

The singleton statement would be equivalent to the following:

class __tmp:
  pass # class definition here
C = __tmp()
del __tmp

Unfortunately, the singleton statement would require a modification to the
Python core, which is generally a Bad Thing(tm).  There are two
alternatives: use the __tmp idiom above (which is ugly but otherwise works)
or use metaclasses.

The metaclass approach would look like this:

class C(Singleton):
  pass # class definition here

Here Singleton is an instance of a (meta-)class that implements singletons.
Let's call it MetaSingleton.  C is also instance of MetaSingleton.  Writing
the MetaSingleton class could be difficult though.

Rainer Deyke (root at
Shareware computer games           - 
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor

More information about the Python-list mailing list